// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @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
* ====
*/functionisContract(address account) internalviewreturns (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].
*/functionsendValue(addresspayable 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._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytesmemory 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._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
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._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytesmemory 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._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytesmemory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function_verifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) privatepurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MITpragmasolidity ^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.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
// SPDX-License-Identifier: MITpragmasolidity ^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.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 10 of 28: ERC721.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"./IERC721.sol";
import"./IERC721Receiver.sol";
import"./extensions/IERC721Metadata.sol";
import"../../utils/Address.sol";
import"../../utils/Context.sol";
import"../../utils/Strings.sol";
import"../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/contractERC721isContext, ERC165, IERC721, IERC721Metadata{
usingAddressforaddress;
usingStringsforuint256;
// Token namestringprivate _name;
// Token symbolstringprivate _symbol;
// Mapping from token ID to owner addressmapping(uint256=>address) private _owners;
// Mapping owner address to token countmapping(address=>uint256) private _balances;
// Mapping from token ID to approved addressmapping(uint256=>address) private _tokenApprovals;
// Mapping from owner to operator approvalsmapping(address=>mapping(address=>bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC721).interfaceId||
interfaceId ==type(IERC721Metadata).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner) publicviewvirtualoverridereturns (uint256) {
require(owner !=address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewvirtualoverridereturns (address) {
address owner = _owners[tokenId];
require(owner !=address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/functiontokenURI(uint256 tokenId) publicviewvirtualoverridereturns (stringmemory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
stringmemory baseURI = _baseURI();
returnbytes(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() internalviewvirtualreturns (stringmemory) {
return"";
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicvirtualoverride{
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}.
*/functiongetApproved(uint256 tokenId) publicviewvirtualoverridereturns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtualoverride{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
//solhint-disable-next-line max-line-lengthrequire(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) publicvirtualoverride{
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(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) internalvirtual{
_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) internalviewvirtualreturns (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) internalviewvirtualreturns (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) internalvirtual{
_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,
bytesmemory _data
) internalvirtual{
_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) internalvirtual{
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) internalvirtual{
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(addressfrom,
address to,
uint256 tokenId
) internalvirtual{
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) internalvirtual{
_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(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) privatereturns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
returntrue;
}
}
/**
* @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(addressfrom,
address to,
uint256 tokenId
) internalvirtual{}
}
Contract Source Code
File 11 of 28: EnumerableSet.sol
// SPDX-License-Identifier: MITpragmasolidity ^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.
*/libraryEnumerableSet{
// 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.structSet {
// Storage of set valuesbytes32[] _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) privatereturns (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;
returntrue;
} else {
returnfalse;
}
}
/**
* @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) privatereturns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slotuint256 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 slotdelete set._indexes[value];
returntrue;
} else {
returnfalse;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/function_contains(Set storage set, bytes32 value) privateviewreturns (bool) {
return set._indexes[value] !=0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/function_length(Set storage set) privateviewreturns (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) privateviewreturns (bytes32) {
return set._values[index];
}
// Bytes32SetstructBytes32Set {
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.
*/functionadd(Bytes32Set storage set, bytes32 value) internalreturns (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.
*/functionremove(Bytes32Set storage set, bytes32 value) internalreturns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(Bytes32Set storage set, bytes32 value) internalviewreturns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(Bytes32Set storage set) internalviewreturns (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}.
*/functionat(Bytes32Set storage set, uint256 index) internalviewreturns (bytes32) {
return _at(set._inner, index);
}
// AddressSetstructAddressSet {
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.
*/functionadd(AddressSet storage set, address value) internalreturns (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.
*/functionremove(AddressSet storage set, address value) internalreturns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(AddressSet storage set, address value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(AddressSet storage set) internalviewreturns (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}.
*/functionat(AddressSet storage set, uint256 index) internalviewreturns (address) {
returnaddress(uint160(uint256(_at(set._inner, index))));
}
// UintSetstructUintSet {
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.
*/functionadd(UintSet storage set, uint256 value) internalreturns (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.
*/functionremove(UintSet storage set, uint256 value) internalreturns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(UintSet storage set, uint256 value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/functionlength(UintSet storage set) internalviewreturns (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}.
*/functionat(UintSet storage set, uint256 index) internalviewreturns (uint256) {
returnuint256(_at(set._inner, index));
}
}
Contract Source Code
File 12 of 28: IDCAGlobalParameters.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity ^0.8.6;import'./ITimeWeightedOracle.sol';
import'./IDCATokenDescriptor.sol';
/// @title The interface for handling parameters the affect the whole DCA ecosystem/// @notice This contract will manage configuration that affects all pairs, swappers, etcinterfaceIDCAGlobalParameters{
/// @notice A compilation of all parameters that affect a swapstructSwapParameters {
// The address of the fee recipientaddress feeRecipient;
// Whether swaps are paused or notbool isPaused;
// The swap feeuint32 swapFee;
// The oracle contract
ITimeWeightedOracle oracle;
}
/// @notice A compilation of all parameters that affect a loanstructLoanParameters {
// The address of the fee recipientaddress feeRecipient;
// Whether loans are paused or notbool isPaused;
// The loan feeuint32 loanFee;
}
/// @notice Emitted when a new fee recipient is set/// @param _feeRecipient The address of the new fee recipienteventFeeRecipientSet(address _feeRecipient);
/// @notice Emitted when a new NFT descriptor is set/// @param _descriptor The new NFT descriptor contracteventNFTDescriptorSet(IDCATokenDescriptor _descriptor);
/// @notice Emitted when a new oracle is set/// @param _oracle The new oracle contracteventOracleSet(ITimeWeightedOracle _oracle);
/// @notice Emitted when a new swap fee is set/// @param _feeSet The new swap feeeventSwapFeeSet(uint32 _feeSet);
/// @notice Emitted when a new loan fee is set/// @param _feeSet The new loan feeeventLoanFeeSet(uint32 _feeSet);
/// @notice Emitted when new swap intervals are allowed/// @param _swapIntervals The new swap intervals/// @param _descriptions The descriptions for each swap intervaleventSwapIntervalsAllowed(uint32[] _swapIntervals, string[] _descriptions);
/// @notice Emitted when some swap intervals are no longer allowed/// @param _swapIntervals The swap intervals that are no longer allowedeventSwapIntervalsForbidden(uint32[] _swapIntervals);
/// @notice Thrown when trying to set a fee higher than the maximum allowederrorHighFee();
/// @notice Thrown when trying to support new swap intervals, but the amount of descriptions doesn't matcherrorInvalidParams();
/// @notice Thrown when trying to support a new swap interval of value zeroerrorZeroInterval();
/// @notice Thrown when trying a description for a new swap interval is emptyerrorEmptyDescription();
/// @notice Returns the address of the fee recipient/// @return _feeRecipient The address of the fee recipientfunctionfeeRecipient() externalviewreturns (address _feeRecipient);
/// @notice Returns fee charged on swaps/// @return _swapFee The fee itselffunctionswapFee() externalviewreturns (uint32 _swapFee);
/// @notice Returns fee charged on loans/// @return _loanFee The fee itselffunctionloanFee() externalviewreturns (uint32 _loanFee);
/// @notice Returns the NFT descriptor contract/// @return _nftDescriptor The contract itselffunctionnftDescriptor() externalviewreturns (IDCATokenDescriptor _nftDescriptor);
/// @notice Returns the time-weighted oracle contract/// @return _oracle The contract itselffunctionoracle() externalviewreturns (ITimeWeightedOracle _oracle);
/// @notice Returns the precision used for fees/// @dev Cannot be modified/// @return _precision The precision used for fees// solhint-disable-next-line func-name-mixedcasefunctionFEE_PRECISION() externalviewreturns (uint24 _precision);
/// @notice Returns the max fee that can be set for either swap or loans/// @dev Cannot be modified/// @return _maxFee The maximum possible fee// solhint-disable-next-line func-name-mixedcasefunctionMAX_FEE() externalviewreturns (uint32 _maxFee);
/// @notice Returns a list of all the allowed swap intervals/// @return _allowedSwapIntervals An array with all allowed swap intervalsfunctionallowedSwapIntervals() externalviewreturns (uint32[] memory _allowedSwapIntervals);
/// @notice Returns the description for a given swap interval/// @return _description The swap interval's descriptionfunctionintervalDescription(uint32 _swapInterval) externalviewreturns (stringmemory _description);
/// @notice Returns whether a swap interval is currently allowed/// @return _isAllowed Whether the given swap interval is currently allowedfunctionisSwapIntervalAllowed(uint32 _swapInterval) externalviewreturns (bool _isAllowed);
/// @notice Returns whether swaps and loans are currently paused/// @return _isPaused Whether swaps and loans are currently pausedfunctionpaused() externalviewreturns (bool _isPaused);
/// @notice Returns a compilation of all parameters that affect a swap/// @return _swapParameters All parameters that affect a swapfunctionswapParameters() externalviewreturns (SwapParameters memory _swapParameters);
/// @notice Returns a compilation of all parameters that affect a loan/// @return _loanParameters All parameters that affect a loanfunctionloanParameters() externalviewreturns (LoanParameters memory _loanParameters);
/// @notice Sets a new fee recipient address/// @dev Will revert with ZeroAddress if the zero address is passed/// @param _feeRecipient The new fee recipient addressfunctionsetFeeRecipient(address _feeRecipient) external;
/// @notice Sets a new swap fee/// @dev Will rever with HighFee if the fee is higher than the maximum/// @param _fee The new swap feefunctionsetSwapFee(uint32 _fee) external;
/// @notice Sets a new loan fee/// @dev Will rever with HighFee if the fee is higher than the maximum/// @param _fee The new loan feefunctionsetLoanFee(uint32 _fee) external;
/// @notice Sets a new NFT descriptor/// @dev Will revert with ZeroAddress if the zero address is passed/// @param _descriptor The new descriptor contractfunctionsetNFTDescriptor(IDCATokenDescriptor _descriptor) external;
/// @notice Sets a new time-weighted oracle/// @dev Will revert with ZeroAddress if the zero address is passed/// @param _oracle The new oracle contractfunctionsetOracle(ITimeWeightedOracle _oracle) external;
/// @notice Adds new swap intervals to the allowed list/// @dev Will revert with:/// InvalidParams if the amount of swap intervals is different from the amount of descriptions passed/// ZeroInterval if any of the swap intervals is zero/// EmptyDescription if any of the descriptions is empty/// @param _swapIntervals The new swap intervals/// @param _descriptions Their descriptionsfunctionaddSwapIntervalsToAllowedList(uint32[] calldata _swapIntervals, string[] calldata _descriptions) external;
/// @notice Removes some swap intervals from the allowed list/// @param _swapIntervals The swap intervals to removefunctionremoveSwapIntervalsFromAllowedList(uint32[] calldata _swapIntervals) external;
/// @notice Pauses all swaps and loansfunctionpause() external;
/// @notice Unpauses all swaps and loansfunctionunpause() external;
}
Contract Source Code
File 13 of 28: IDCAPair.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity ^0.8.6;import'@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
import'./IDCAGlobalParameters.sol';
/// @title The interface for all state related queries/// @notice These methods allow users to read the pair's current valuesinterfaceIDCAPairParameters{
/// @notice Returns the global parameters contract/// @dev Global parameters has information about swaps and pairs, like swap intervals, fees charged, etc./// @return The Global Parameters contractfunctionglobalParameters() externalviewreturns (IDCAGlobalParameters);
/// @notice Returns the token A contract/// @return The contract for token AfunctiontokenA() externalviewreturns (IERC20Metadata);
/// @notice Returns the token B contract/// @return The contract for token BfunctiontokenB() externalviewreturns (IERC20Metadata);
/// @notice Returns how much will the amount to swap differ from the previous swap/// @dev f.e. if the returned value is -100, then the amount to swap will be 100 less than the swap just before it/// @param _swapInterval The swap interval to check/// @param _from The 'from' token of the deposits/// @param _swap The swap number to check/// @return _delta How much will the amount to swap differ, when compared to the swap just before this onefunctionswapAmountDelta(uint32 _swapInterval,
address _from,
uint32 _swap
) externalviewreturns (int256 _delta);
/// @notice Returns if a certain swap interval is active or not/// @dev We consider a swap interval to be active if there is at least one active position on that interval/// @param _swapInterval The swap interval to check/// @return _isActive Whether the given swap interval is currently activefunctionisSwapIntervalActive(uint32 _swapInterval) externalviewreturns (bool _isActive);
/// @notice Returns the amount of swaps executed for a certain interval/// @param _swapInterval The swap interval to check/// @return _swaps The amount of swaps performed on the given intervalfunctionperformedSwaps(uint32 _swapInterval) externalviewreturns (uint32 _swaps);
}
/// @title The interface for all position related matters in a DCA pair/// @notice These methods allow users to create, modify and terminate their positionsinterfaceIDCAPairPositionHandlerisIDCAPairParameters{
/// @notice The position of a certain userstructUserPosition {
// The token that the user deposited and will be swapped in exchange for "to"
IERC20Metadata from;
// The token that the user will get in exchange for their "from" tokens in each swap
IERC20Metadata to;
// How frequently the position's swaps should be executeduint32 swapInterval;
// How many swaps were executed since deposit, last modification, or last withdrawuint32 swapsExecuted;
// How many "to" tokens can currently be withdrawnuint256 swapped;
// How many swaps left the position has to executeuint32 swapsLeft;
// How many "from" tokens there are left to swapuint256 remaining;
// How many "from" tokens need to be traded in each swapuint160 rate;
}
/// @notice Emitted when a position is terminated/// @param _user The address of the user that terminated the position/// @param _dcaId The id of the position that was terminated/// @param _returnedUnswapped How many "from" tokens were returned to the caller/// @param _returnedSwapped How many "to" tokens were returned to the callereventTerminated(addressindexed _user, uint256 _dcaId, uint256 _returnedUnswapped, uint256 _returnedSwapped);
/// @notice Emitted when a position is created/// @param _user The address of the user that created the position/// @param _dcaId The id of the position that was created/// @param _fromToken The address of the "from" token/// @param _rate How many "from" tokens need to be traded in each swap/// @param _startingSwap The number of the swap when the position will be executed for the first time/// @param _swapInterval How frequently the position's swaps should be executed/// @param _lastSwap The number of the swap when the position will be executed for the last timeeventDeposited(addressindexed _user,
uint256 _dcaId,
address _fromToken,
uint160 _rate,
uint32 _startingSwap,
uint32 _swapInterval,
uint32 _lastSwap
);
/// @notice Emitted when a user withdraws all swapped tokens from a position/// @param _user The address of the user that executed the withdraw/// @param _dcaId The id of the position that was affected/// @param _token The address of the withdrawn tokens. It's the same as the position's "to" token/// @param _amount The amount that was withdrawneventWithdrew(addressindexed _user, uint256 _dcaId, address _token, uint256 _amount);
/// @notice Emitted when a user withdraws all swapped tokens from many positions/// @param _user The address of the user that executed the withdraw/// @param _dcaIds The ids of the positions that were affected/// @param _swappedTokenA The total amount that was withdrawn in token A/// @param _swappedTokenB The total amount that was withdrawn in token BeventWithdrewMany(addressindexed _user, uint256[] _dcaIds, uint256 _swappedTokenA, uint256 _swappedTokenB);
/// @notice Emitted when a position is modified/// @param _user The address of the user that modified the position/// @param _dcaId The id of the position that was modified/// @param _rate How many "from" tokens need to be traded in each swap/// @param _startingSwap The number of the swap when the position will be executed for the first time/// @param _lastSwap The number of the swap when the position will be executed for the last timeeventModified(addressindexed _user, uint256 _dcaId, uint160 _rate, uint32 _startingSwap, uint32 _lastSwap);
/// @notice Thrown when a user tries to create a position with a token that is neither token A nor token BerrorInvalidToken();
/// @notice Thrown when a user tries to create that a position with an unsupported swap intervalerrorInvalidInterval();
/// @notice Thrown when a user tries operate on a position that doesn't exist (it might have been already terminated)errorInvalidPosition();
/// @notice Thrown when a user tries operate on a position that they don't have access toerrorUnauthorizedCaller();
/// @notice Thrown when a user tries to create or modify a position by setting the rate to be zeroerrorZeroRate();
/// @notice Thrown when a user tries to create a position with zero swapserrorZeroSwaps();
/// @notice Thrown when a user tries to add zero funds to their positionerrorZeroAmount();
/// @notice Thrown when a user tries to modify the rate of a position that has already been completederrorPositionCompleted();
/// @notice Thrown when a user tries to modify a position that has too much swapped balance. This error/// is thrown so that the user doesn't lose any funds. The error indicates that the user must perform a withdraw/// before modifying their positionerrorMandatoryWithdraw();
/// @notice Returns a DCA position/// @param _dcaId The id of the position/// @return _position The position itselffunctionuserPosition(uint256 _dcaId) externalviewreturns (UserPosition memory _position);
/// @notice Creates a new position/// @dev Will revert:/// With InvalidToken if _tokenAddress is neither token A nor token B/// With ZeroRate if _rate is zero/// With ZeroSwaps if _amountOfSwaps is zero/// With InvalidInterval if _swapInterval is not a valid swap interval/// @param _tokenAddress The address of the token that will be deposited/// @param _rate How many "from" tokens need to be traded in each swap/// @param _amountOfSwaps How many swaps to execute for this position/// @param _swapInterval How frequently the position's swaps should be executed/// @return _dcaId The id of the created positionfunctiondeposit(address _tokenAddress,
uint160 _rate,
uint32 _amountOfSwaps,
uint32 _swapInterval
) externalreturns (uint256 _dcaId);
/// @notice Withdraws all swapped tokens from a position/// @dev Will revert:/// With InvalidPosition if _dcaId is invalid/// With UnauthorizedCaller if the caller doesn't have access to the position/// @param _dcaId The position's id/// @return _swapped How much was withdrawnfunctionwithdrawSwapped(uint256 _dcaId) externalreturns (uint256 _swapped);
/// @notice Withdraws all swapped tokens from many positions/// @dev Will revert:/// With InvalidPosition if any of the ids in _dcaIds is invalid/// With UnauthorizedCaller if the caller doesn't have access to any of the positions in _dcaIds/// @param _dcaIds The positions' ids/// @return _swappedTokenA How much was withdrawn in token A/// @return _swappedTokenB How much was withdrawn in token BfunctionwithdrawSwappedMany(uint256[] calldata _dcaIds) externalreturns (uint256 _swappedTokenA, uint256 _swappedTokenB);
/// @notice Modifies the rate of a position. Could request more funds or return deposited funds/// depending on whether the new rate is greater than the previous one./// @dev Will revert:/// With InvalidPosition if _dcaId is invalid/// With UnauthorizedCaller if the caller doesn't have access to the position/// With PositionCompleted if position has already been completed/// With ZeroRate if _newRate is zero/// With MandatoryWithdraw if the user must execute a withdraw before modifying their position/// @param _dcaId The position's id/// @param _newRate The new rate to setfunctionmodifyRate(uint256 _dcaId, uint160 _newRate) external;
/// @notice Modifies the amount of swaps of a position. Could request more funds or return/// deposited funds depending on whether the new amount of swaps is greater than the swaps left./// @dev Will revert:/// With InvalidPosition if _dcaId is invalid/// With UnauthorizedCaller if the caller doesn't have access to the position/// With MandatoryWithdraw if the user must execute a withdraw before modifying their position/// @param _dcaId The position's id/// @param _newSwaps The new amount of swapsfunctionmodifySwaps(uint256 _dcaId, uint32 _newSwaps) external;
/// @notice Modifies both the rate and amount of swaps of a position. Could request more funds or return/// deposited funds depending on whether the new parameters require more or less than the the unswapped funds./// @dev Will revert:/// With InvalidPosition if _dcaId is invalid/// With UnauthorizedCaller if the caller doesn't have access to the position/// With ZeroRate if _newRate is zero/// With MandatoryWithdraw if the user must execute a withdraw before modifying their position/// @param _dcaId The position's id/// @param _newRate The new rate to set/// @param _newSwaps The new amount of swapsfunctionmodifyRateAndSwaps(uint256 _dcaId,
uint160 _newRate,
uint32 _newSwaps
) external;
/// @notice Takes the unswapped balance, adds the new deposited funds and modifies the position so that/// it is executed in _newSwaps swaps/// @dev Will revert:/// With InvalidPosition if _dcaId is invalid/// With UnauthorizedCaller if the caller doesn't have access to the position/// With ZeroAmount if _amount is zero/// With ZeroSwaps if _newSwaps is zero/// With MandatoryWithdraw if the user must execute a withdraw before modifying their position/// @param _dcaId The position's id/// @param _amount Amounts of funds to add to the position/// @param _newSwaps The new amount of swapsfunctionaddFundsToPosition(uint256 _dcaId,
uint256 _amount,
uint32 _newSwaps
) external;
/// @notice Terminates the position and sends all unswapped and swapped balance to the caller/// @dev Will revert:/// With InvalidPosition if _dcaId is invalid/// With UnauthorizedCaller if the caller doesn't have access to the position/// @param _dcaId The position's idfunctionterminate(uint256 _dcaId) external;
}
/// @title The interface for all swap related matters in a DCA pair/// @notice These methods allow users to get information about the next swap, and how to execute itinterfaceIDCAPairSwapHandler{
/// @notice Information about an available swap for a specific swap intervalstructSwapInformation {
// The affected swap intervaluint32 interval;
// The number of the swap that will be performeduint32 swapToPerform;
// The amount of token A that needs swappinguint256 amountToSwapTokenA;
// The amount of token B that needs swappinguint256 amountToSwapTokenB;
}
/// @notice All information about the next swapstructNextSwapInformation {
// All swaps that can be executed
SwapInformation[] swapsToPerform;
// How many entries of the swapsToPerform array are validuint8 amountOfSwaps;
// How much can be borrowed in token A during a flash swapuint256 availableToBorrowTokenA;
// How much can be borrowed in token B during a flash swapuint256 availableToBorrowTokenB;
// How much 10**decimals(tokenB) is when converted to token Auint256 ratePerUnitBToA;
// How much 10**decimals(tokenA) is when converted to token Buint256 ratePerUnitAToB;
// How much token A will be sent to the platform in terms of feeuint256 platformFeeTokenA;
// How much token B will be sent to the platform in terms of feeuint256 platformFeeTokenB;
// The amount of tokens that need to be provided by the swapperuint256 amountToBeProvidedBySwapper;
// The amount of tokens that will be sent to the swapper optimisticallyuint256 amountToRewardSwapperWith;
// The token that needs to be provided by the swapper
IERC20Metadata tokenToBeProvidedBySwapper;
// The token that will be sent to the swapper optimistically
IERC20Metadata tokenToRewardSwapperWith;
}
/// @notice Emitted when a swap is executed/// @param _sender The address of the user that initiated the swap/// @param _to The address that received the reward + loan/// @param _amountBorrowedTokenA How much was borrowed in token A/// @param _amountBorrowedTokenB How much was borrowed in token B/// @param _fee How much was charged as a swap fee to position owners/// @param _nextSwapInformation All information related to the swapeventSwapped(addressindexed _sender,
addressindexed _to,
uint256 _amountBorrowedTokenA,
uint256 _amountBorrowedTokenB,
uint32 _fee,
NextSwapInformation _nextSwapInformation
);
/// @notice Thrown when trying to execute a swap, but none is availableerrorNoSwapsToExecute();
/// @notice Returns when the next swap will be available for a given swap interval/// @param _swapInterval The swap interval to check/// @return _when The moment when the next swap will be available. Take into account that if the swap is already available, this result could/// be in the pastfunctionnextSwapAvailable(uint32 _swapInterval) externalviewreturns (uint32 _when);
/// @notice Returns the amount of tokens that needed swapping in the last swap, for all positions in the given swap interval that were deposited in the given token/// @param _swapInterval The swap interval to check/// @param _from The address of the token that all positions used to deposit/// @return _amount The amount that needed swapping in the last swapfunctionswapAmountAccumulator(uint32 _swapInterval, address _from) externalviewreturns (uint256);
/// @notice Returns all information related to the next swap/// @return _nextSwapInformation The information about the next swapfunctiongetNextSwapInfo() externalviewreturns (NextSwapInformation memory _nextSwapInformation);
/// @notice Executes a swap/// @dev This method assumes that the required amount has already been sent. Will revert with:/// Paused if swaps are paused by protocol/// NoSwapsToExecute if there are no swaps to execute/// LiquidityNotReturned if the required tokens were not sent before calling the functionfunctionswap() external;
/// @notice Executes a flash swap/// @dev Will revert with:/// Paused if swaps are paused by protocol/// NoSwapsToExecute if there are no swaps to execute/// InsufficientLiquidity if asked to borrow more than the actual reserves/// LiquidityNotReturned if the required tokens were not back during the callback/// @param _amountToBorrowTokenA How much to borrow in token A/// @param _amountToBorrowTokenB How much to borrow in token B/// @param _to Address to send the reward + the borrowed tokens/// @param _data Bytes to send to the caller during the callback. If this parameter is empty, the callback won't be executedfunctionswap(uint256 _amountToBorrowTokenA,
uint256 _amountToBorrowTokenB,
address _to,
bytescalldata _data
) external;
/// @notice Returns how many seconds left until the next swap is available/// @return _secondsUntilNextSwap The amount of seconds until next swap. Returns 0 if a swap can already be executedfunctionsecondsUntilNextSwap() externalviewreturns (uint32 _secondsUntilNextSwap);
}
/// @title The interface for all loan related matters in a DCA pair/// @notice These methods allow users to ask how much is available for loans, and also to execute theminterfaceIDCAPairLoanHandler{
/// @notice Emitted when a flash loan is executed/// @param _sender The address of the user that initiated the loan/// @param _to The address that received the loan/// @param _amountBorrowedTokenA How much was borrowed in token A/// @param _amountBorrowedTokenB How much was borrowed in token B/// @param _loanFee How much was charged as a feeeventLoaned(addressindexed _sender, addressindexed _to, uint256 _amountBorrowedTokenA, uint256 _amountBorrowedTokenB, uint32 _loanFee);
// @notice Thrown when trying to execute a flash loan but without actually asking for tokenserrorZeroLoan();
/// @notice Returns the amount of tokens that can be asked for during a flash loan/// @return _amountToBorrowTokenA The amount of token A that is available for borrowing/// @return _amountToBorrowTokenB The amount of token B that is available for borrowingfunctionavailableToBorrow() externalviewreturns (uint256 _amountToBorrowTokenA, uint256 _amountToBorrowTokenB);
/// @notice Executes a flash loan, sending the required amounts to the specified loan recipient/// @dev Will revert:/// With ZeroLoan if both _amountToBorrowTokenA & _amountToBorrowTokenB are 0/// With Paused if loans are paused by protocol/// With InsufficientLiquidity if asked for more that reserves/// @param _amountToBorrowTokenA The amount to borrow in token A/// @param _amountToBorrowTokenB The amount to borrow in token B/// @param _to Address that will receive the loan. This address should be a contract that implements IDCAPairLoanCallee/// @param _data Any data that should be passed through to the callbackfunctionloan(uint256 _amountToBorrowTokenA,
uint256 _amountToBorrowTokenB,
address _to,
bytescalldata _data
) external;
}
interfaceIDCAPairisIDCAPairParameters, IDCAPairSwapHandler, IDCAPairPositionHandler, IDCAPairLoanHandler{}
Contract Source Code
File 14 of 28: IDCAPairLoanCallee.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity ^0.8.6;import'@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
/// @title The interface for handling flash loans/// @notice Users that want to execute flash loans must implement this interfaceinterfaceIDCAPairLoanCallee{
/// @notice Handles the flash loan callback/// @param _sender The loan originator/// @param _tokenA Address for token A/// @param _tokenB Address for token B/// @param _amountBorrowedTokenA Amount borrowed in token A/// @param _amountBorrowedTokenB Amount borrowed in token B/// @param _feeTokenA How much extra to return in fees in token A/// @param _feeTokenB How much extra to return in fees in token B/// @param _data Arbitrary bytes sent to the pair when initiating the loan// solhint-disable-next-line func-name-mixedcasefunctionDCAPairLoanCall(address _sender,
IERC20Metadata _tokenA,
IERC20Metadata _tokenB,
uint256 _amountBorrowedTokenA,
uint256 _amountBorrowedTokenB,
uint256 _feeTokenA,
uint256 _feeTokenB,
bytescalldata _data
) external;
}
Contract Source Code
File 15 of 28: IDCAPairSwapCallee.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity ^0.8.6;import'@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
/// @title The interface for handling flash swaps/// @notice Users that want to execute flash swaps must implement this interfaceinterfaceIDCAPairSwapCallee{
/// @notice Handles the flash swap callback/// @param _sender The swap originator/// @param _tokenA Address for token A/// @param _tokenB Address for token B/// @param _amountBorrowedTokenA Amount borrowed in token A/// @param _amountBorrowedTokenB Amount borrowed in token B/// @param _isRewardTokenA Determines which token is the reward and which to provide to the pair/// @param _rewardAmount How much was sent to this contract optimistically/// @param _amountToProvide How much needs to be sent back to the pair/// @param _data Arbitrary bytes sent to the pair when initiating the swap// solhint-disable-next-line func-name-mixedcasefunctionDCAPairSwapCall(address _sender,
IERC20Metadata _tokenA,
IERC20Metadata _tokenB,
uint256 _amountBorrowedTokenA,
uint256 _amountBorrowedTokenB,
bool _isRewardTokenA,
uint256 _rewardAmount,
uint256 _amountToProvide,
bytescalldata _data
) external;
}
Contract Source Code
File 16 of 28: IDCATokenDescriptor.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity ^0.8.6;import'./IDCAPair.sol';
/// @title The interface for generating a token's description/// @notice Contracts that implement this interface must return a base64 JSON with the entire descriptioninterfaceIDCATokenDescriptor{
/// @notice Generates a token's description, both the JSON and the image inside/// @param _positionHandler The pair where the position was created/// @param _tokenId The token/position id/// @return _description The position's descriptionfunctiontokenURI(IDCAPairPositionHandler _positionHandler, uint256 _tokenId) externalviewreturns (stringmemory _description);
}
Contract Source Code
File 17 of 28: IERC165.sol
// SPDX-License-Identifier: MITpragmasolidity ^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}.
*/interfaceIERC165{
/**
* @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.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 18 of 28: IERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (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.
*/functiontransfer(address recipient, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 amount) externalreturns (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.
*/functiontransferFrom(address sender,
address recipient,
uint256 amount
) externalreturns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
}
Contract Source Code
File 19 of 28: IERC20Metadata.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 20 of 28: IERC721.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (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.
*/functionsafeTransferFrom(addressfrom,
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.
*/functiontransferFrom(addressfrom,
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.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (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.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (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.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytescalldata data
) external;
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @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`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
Contract Source Code
File 23 of 28: ITimeWeightedOracle.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;import'@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
/// @title The interface for an oracle that provies TWAP quotes/// @notice These methods allow users to add support for pairs, and then ask for quotesinterfaceITimeWeightedOracle{
/// @notice Emitted when the oracle add supports for a new pair/// @param _tokenA One of the pair's tokens/// @param _tokenB The other of the pair's tokenseventAddedSupportForPair(address _tokenA, address _tokenB);
/// @notice Returns whether this oracle can support this pair of tokens/// @dev _tokenA and _tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order/// @param _tokenA One of the pair's tokens/// @param _tokenB The other of the pair's tokens/// @return _canSupport Whether the given pair of tokens can be supported by the oraclefunctioncanSupportPair(address _tokenA, address _tokenB) externalviewreturns (bool _canSupport);
/// @notice Returns a quote, based on the given tokens and amount/// @param _tokenIn The token that will be provided/// @param _amountIn The amount that will be provided/// @param _tokenOut The token we would like to quote/// @return _amountOut How much _tokenOut will be returned in exchange for _amountIn amount of _tokenInfunctionquote(address _tokenIn,
uint128 _amountIn,
address _tokenOut
) externalviewreturns (uint256 _amountOut);
/// @notice Add support for a given pair to the contract. This function will let the oracle take some actions to/// configure the pair for future quotes. Could be called more than one in order to let the oracle re-configure for a new context./// @dev Will revert if pair cannot be supported. _tokenA and _tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order/// @param _tokenA One of the pair's tokens/// @param _tokenB The other of the pair's tokensfunctionaddSupportForPair(address _tokenA, address _tokenB) external;
}
/// @title An implementation of ITimeWeightedOracle that uses Uniswap V3 pool oracles/// @notice This oracle will attempt to use all fee tiers of the same pair when calculating quotesinterfaceIUniswapV3OracleAggregatorisITimeWeightedOracle{
/// @notice Emitted when a new fee tier is added/// @return _feeTier The added fee tiereventAddedFeeTier(uint24 _feeTier);
/// @notice Emitted when a new period is set/// @return _period The new periodeventPeriodChanged(uint32 _period);
/// @notice Returns the Uniswap V3 Factory/// @return _factory The Uniswap V3 Factoryfunctionfactory() externalviewreturns (IUniswapV3Factory _factory);
/// @notice Returns a list of all supported Uniswap V3 fee tiers/// @return _feeTiers An array of all supported fee tiersfunctionsupportedFeeTiers() externalviewreturns (uint24[] memory _feeTiers);
/// @notice Returns a list of all Uniswap V3 pools used for a given pair/// @dev _tokenA and _tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order/// @return _pools An array with all pools used for quoting the given pairfunctionpoolsUsedForPair(address _tokenA, address _tokenB) externalviewreturns (address[] memory _pools);
/// @notice Returns the period used for the TWAP calculation/// @return _period The period used for the TWAPfunctionperiod() externalviewreturns (uint16 _period);
/// @notice Returns minimum possible period/// @dev Cannot be modified/// @return The minimum possible period// solhint-disable-next-line func-name-mixedcasefunctionMINIMUM_PERIOD() externalviewreturns (uint16);
/// @notice Returns maximum possible period/// @dev Cannot be modified/// @return The maximum possible period// solhint-disable-next-line func-name-mixedcasefunctionMAXIMUM_PERIOD() externalviewreturns (uint16);
/// @notice Returns the minimum liquidity that a pool needs to have in order to be used for a pair's quote/// @dev This check is only performed when adding support for a pair. If the pool's liquidity then/// goes below the threshold, then it will still be used for the quote calculation/// @return The minimum liquidity threshold// solhint-disable-next-line func-name-mixedcasefunctionMINIMUM_LIQUIDITY_THRESHOLD() externalviewreturns (uint16);
/// @notice Adds support for a new Uniswap V3 fee tier/// @dev Will revert if the provided fee tier is not supported by Uniswap V3/// @param _feeTier The new fee tierfunctionaddFeeTier(uint24 _feeTier) external;
/// @notice Sets the period to be used for the TWAP calculation/// @dev Will revert it is lower than MINIMUM_PERIOD or greater than MAXIMUM_PERIOD/// WARNING: increasing the period could cause big problems, because Uniswap V3 pools might not support a TWAP so old./// @param _period The new periodfunctionsetPeriod(uint16 _period) external;
}
Contract Source Code
File 24 of 28: IUniswapV3Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title The interface for the Uniswap V3 Factory/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol feesinterfaceIUniswapV3Factory{
/// @notice Emitted when the owner of the factory is changed/// @param oldOwner The owner before the owner was changed/// @param newOwner The owner after the owner was changedeventOwnerChanged(addressindexed oldOwner, addressindexed newOwner);
/// @notice Emitted when a pool is created/// @param token0 The first token of the pool by address sort order/// @param token1 The second token of the pool by address sort order/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/// @param tickSpacing The minimum number of ticks between initialized ticks/// @param pool The address of the created pooleventPoolCreated(addressindexed token0,
addressindexed token1,
uint24indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory/// @param fee The enabled fee, denominated in hundredths of a bip/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given feeeventFeeAmountEnabled(uint24indexed fee, int24indexed tickSpacing);
/// @notice Returns the current owner of the factory/// @dev Can be changed by the current owner via setOwner/// @return The address of the factory ownerfunctionowner() externalviewreturns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee/// @return The tick spacingfunctionfeeAmountTickSpacing(uint24 fee) externalviewreturns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order/// @param tokenA The contract address of either token0 or token1/// @param tokenB The contract address of the other token/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/// @return pool The pool addressfunctiongetPool(address tokenA,
address tokenB,
uint24 fee
) externalviewreturns (address pool);
/// @notice Creates a pool for the given two tokens and fee/// @param tokenA One of the two tokens in the desired pool/// @param tokenB The other of the two tokens in the desired pool/// @param fee The desired fee for the pool/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments/// are invalid./// @return pool The address of the newly created poolfunctioncreatePool(address tokenA,
address tokenB,
uint24 fee
) externalreturns (address pool);
/// @notice Updates the owner of the factory/// @dev Must be called by the current owner/// @param _owner The new owner of the factoryfunctionsetOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing/// @dev Fee amounts may never be removed once enabled/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amountfunctionenableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
Contract Source Code
File 25 of 28: Math.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity ^0.8.6;libraryMath{
functiontryMul(uint256 a, uint256 b) internalpurereturns (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/522if (a ==0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
}
Contract Source Code
File 26 of 28: ReentrancyGuard.sol
// SPDX-License-Identifier: MITpragmasolidity ^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].
*/abstractcontractReentrancyGuard{
// 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.uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _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.
*/modifiernonReentrant() {
// On the first call to nonReentrant, _notEntered will be truerequire(_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;
}
}
Contract Source Code
File 27 of 28: SafeERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^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.
*/librarySafeERC20{
usingAddressforaddress;
functionsafeTransfer(
IERC20 token,
address to,
uint256 value
) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
functionsafeTransferFrom(
IERC20 token,
addressfrom,
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.
*/functionsafeApprove(
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));
}
functionsafeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
functionsafeDecreaseAllowance(
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, bytesmemory 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.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length>0) {
// Return data is optionalrequire(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
Contract Source Code
File 28 of 28: Strings.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
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.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(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");
returnstring(buffer);
}
}