dexorder
This commit is contained in:
312
lib_openzeppelin_contracts/contracts/token/ERC20/ERC20.sol
Normal file
312
lib_openzeppelin_contracts/contracts/token/ERC20/ERC20.sol
Normal file
@@ -0,0 +1,312 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "./IERC20.sol";
|
||||
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {IERC20Errors} from "../../interfaces/draft-IERC6093.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}.
|
||||
*
|
||||
* TIP: For a detailed writeup see our guide
|
||||
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
|
||||
* to implement supply mechanisms].
|
||||
*
|
||||
* The default value of {decimals} is 18. To change this, you should override
|
||||
* this function so it returns a different value.
|
||||
*
|
||||
* 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 ERC-20
|
||||
* applications.
|
||||
*/
|
||||
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
|
||||
mapping(address account => uint256) private _balances;
|
||||
|
||||
mapping(address account => mapping(address spender => uint256)) private _allowances;
|
||||
|
||||
uint256 private _totalSupply;
|
||||
|
||||
string private _name;
|
||||
string private _symbol;
|
||||
|
||||
/**
|
||||
* @dev Sets the values for {name} and {symbol}.
|
||||
*
|
||||
* 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 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 default value returned by this function, unless
|
||||
* it's 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 returns (uint8) {
|
||||
return 18;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 See {IERC20-transfer}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - the caller must have a balance of at least `value`.
|
||||
*/
|
||||
function transfer(address to, uint256 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_transfer(owner, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-allowance}.
|
||||
*/
|
||||
function allowance(address owner, address spender) public view virtual returns (uint256) {
|
||||
return _allowances[owner][spender];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-approve}.
|
||||
*
|
||||
* NOTE: If `value` 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 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_approve(owner, spender, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-transferFrom}.
|
||||
*
|
||||
* Skips emitting an {Approval} event indicating an allowance update. This is not
|
||||
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
|
||||
*
|
||||
* 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 `value`.
|
||||
* - the caller must have allowance for ``from``'s tokens of at least
|
||||
* `value`.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
|
||||
address spender = _msgSender();
|
||||
_spendAllowance(from, spender, value);
|
||||
_transfer(from, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to`.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _transfer(address from, address to, uint256 value) internal {
|
||||
if (from == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
if (to == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
|
||||
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
|
||||
* this function.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual {
|
||||
if (from == address(0)) {
|
||||
// Overflow check required: The rest of the code assumes that totalSupply never overflows
|
||||
_totalSupply += value;
|
||||
} else {
|
||||
uint256 fromBalance = _balances[from];
|
||||
if (fromBalance < value) {
|
||||
revert ERC20InsufficientBalance(from, fromBalance, value);
|
||||
}
|
||||
unchecked {
|
||||
// Overflow not possible: value <= fromBalance <= totalSupply.
|
||||
_balances[from] = fromBalance - value;
|
||||
}
|
||||
}
|
||||
|
||||
if (to == address(0)) {
|
||||
unchecked {
|
||||
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
|
||||
_totalSupply -= value;
|
||||
}
|
||||
} else {
|
||||
unchecked {
|
||||
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
|
||||
_balances[to] += value;
|
||||
}
|
||||
}
|
||||
|
||||
emit Transfer(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
|
||||
* Relies on the `_update` mechanism
|
||||
*
|
||||
* Emits a {Transfer} event with `from` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _mint(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(address(0), account, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
|
||||
* Relies on the `_update` mechanism.
|
||||
*
|
||||
* Emits a {Transfer} event with `to` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead
|
||||
*/
|
||||
function _burn(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
_update(account, address(0), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `value` 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.
|
||||
*
|
||||
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value) internal {
|
||||
_approve(owner, spender, value, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
|
||||
*
|
||||
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
|
||||
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
|
||||
* `Approval` event during `transferFrom` operations.
|
||||
*
|
||||
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
|
||||
* true using the following override:
|
||||
*
|
||||
* ```solidity
|
||||
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
|
||||
* super._approve(owner, spender, value, true);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Requirements are the same as {_approve}.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
|
||||
if (owner == address(0)) {
|
||||
revert ERC20InvalidApprover(address(0));
|
||||
}
|
||||
if (spender == address(0)) {
|
||||
revert ERC20InvalidSpender(address(0));
|
||||
}
|
||||
_allowances[owner][spender] = value;
|
||||
if (emitEvent) {
|
||||
emit Approval(owner, spender, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
|
||||
*
|
||||
* Does not update the allowance value in case of infinite allowance.
|
||||
* Revert if not enough allowance is available.
|
||||
*
|
||||
* Does not emit an {Approval} event.
|
||||
*/
|
||||
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
|
||||
uint256 currentAllowance = allowance(owner, spender);
|
||||
if (currentAllowance != type(uint256).max) {
|
||||
if (currentAllowance < value) {
|
||||
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
|
||||
}
|
||||
unchecked {
|
||||
_approve(owner, spender, currentAllowance - value, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
79
lib_openzeppelin_contracts/contracts/token/ERC20/IERC20.sol
Normal file
79
lib_openzeppelin_contracts/contracts/token/ERC20/IERC20.sol
Normal file
@@ -0,0 +1,79 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-20 standard as defined in the ERC.
|
||||
*/
|
||||
interface IERC20 {
|
||||
/**
|
||||
* @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 Returns the value of tokens in existence.
|
||||
*/
|
||||
function totalSupply() external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the value of tokens owned by `account`.
|
||||
*/
|
||||
function balanceOf(address account) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to` using the
|
||||
* allowance mechanism. `value` 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 value) external returns (bool);
|
||||
}
|
||||
70
lib_openzeppelin_contracts/contracts/token/ERC20/README.adoc
Normal file
70
lib_openzeppelin_contracts/contracts/token/ERC20/README.adoc
Normal file
@@ -0,0 +1,70 @@
|
||||
= ERC-20
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc20
|
||||
|
||||
This set of interfaces, contracts, and utilities are all related to the https://eips.ethereum.org/EIPS/eip-20[ERC-20 Token Standard].
|
||||
|
||||
TIP: For an overview of ERC-20 tokens and a walk through on how to create a token contract read our xref:ROOT:erc20.adoc[ERC-20 guide].
|
||||
|
||||
There are a few core contracts that implement the behavior specified in the ERC:
|
||||
|
||||
* {IERC20}: the interface all ERC-20 implementations should conform to.
|
||||
* {IERC20Metadata}: the extended ERC-20 interface including the <<ERC20-name,`name`>>, <<ERC20-symbol,`symbol`>> and <<ERC20-decimals,`decimals`>> functions.
|
||||
* {ERC20}: the implementation of the ERC-20 interface, including the <<ERC20-name,`name`>>, <<ERC20-symbol,`symbol`>> and <<ERC20-decimals,`decimals`>> optional standard extension to the base interface.
|
||||
|
||||
Additionally there are multiple custom extensions, including:
|
||||
|
||||
* {ERC20Permit}: gasless approval of tokens (standardized as ERC-2612).
|
||||
* {ERC20Burnable}: destruction of own tokens.
|
||||
* {ERC20Capped}: enforcement of a cap to the total supply when minting tokens.
|
||||
* {ERC20Pausable}: ability to pause token transfers.
|
||||
* {ERC20FlashMint}: token level support for flash loans through the minting and burning of ephemeral tokens (standardized as ERC-3156).
|
||||
* {ERC20Votes}: support for voting and vote delegation.
|
||||
* {ERC20Wrapper}: wrapper to create an ERC-20 backed by another ERC-20, with deposit and withdraw methods. Useful in conjunction with {ERC20Votes}.
|
||||
* {ERC1363}: support for calling the target of a transfer or approval, enabling code execution on the receiver within a single transaction.
|
||||
* {ERC4626}: tokenized vault that manages shares (represented as ERC-20) that are backed by assets (another ERC-20).
|
||||
|
||||
Finally, there are some utilities to interact with ERC-20 contracts in various ways:
|
||||
|
||||
* {SafeERC20}: a wrapper around the interface that eliminates the need to handle boolean return values.
|
||||
|
||||
Other utilities that support ERC-20 assets can be found in codebase:
|
||||
|
||||
* ERC-20 tokens can be timelocked (held tokens for a beneficiary until a specified time) or vested (released following a given schedule) using a {VestingWallet}.
|
||||
|
||||
NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC-20 (such as <<ERC20-_mint-address-uint256-,`_mint`>>) and expose them as external functions in the way they prefer.
|
||||
|
||||
== Core
|
||||
|
||||
{{IERC20}}
|
||||
|
||||
{{IERC20Metadata}}
|
||||
|
||||
{{ERC20}}
|
||||
|
||||
== Extensions
|
||||
|
||||
{{IERC20Permit}}
|
||||
|
||||
{{ERC20Permit}}
|
||||
|
||||
{{ERC20Burnable}}
|
||||
|
||||
{{ERC20Capped}}
|
||||
|
||||
{{ERC20Pausable}}
|
||||
|
||||
{{ERC20Votes}}
|
||||
|
||||
{{ERC20Wrapper}}
|
||||
|
||||
{{ERC20FlashMint}}
|
||||
|
||||
{{ERC1363}}
|
||||
|
||||
{{ERC4626}}
|
||||
|
||||
== Utilities
|
||||
|
||||
{{SafeERC20}}
|
||||
@@ -0,0 +1,198 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
|
||||
|
||||
import {IERC1363} from "../../../interfaces/IERC1363.sol";
|
||||
import {IERC1363Receiver} from "../../../interfaces/IERC1363Receiver.sol";
|
||||
import {IERC1363Spender} from "../../../interfaces/IERC1363Spender.sol";
|
||||
|
||||
/**
|
||||
* @title ERC1363
|
||||
* @dev Extension of {ERC20} tokens that adds support for code execution after transfers and approvals
|
||||
* on recipient contracts. Calls after transfers are enabled through the {ERC1363-transferAndCall} and
|
||||
* {ERC1363-transferFromAndCall} methods while calls after approvals can be made with {ERC1363-approveAndCall}
|
||||
*/
|
||||
abstract contract ERC1363 is ERC20, ERC165, IERC1363 {
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC1363InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `spender`. Used in approvals.
|
||||
* @param spender Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC1363InvalidSpender(address spender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure within the {transfer} part of a transferAndCall operation.
|
||||
*/
|
||||
error ERC1363TransferFailed(address to, uint256 value);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure within the {transferFrom} part of a transferFromAndCall operation.
|
||||
*/
|
||||
error ERC1363TransferFromFailed(address from, address to, uint256 value);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure within the {approve} part of a approveAndCall operation.
|
||||
*/
|
||||
error ERC1363ApproveFailed(address spender, uint256 value);
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC165
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
|
||||
return interfaceId == type(IERC1363).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from the caller's account to `to`
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `to` must implement the {IERC1363Receiver} interface.
|
||||
* - The target must return the {IERC1363Receiver-onTransferReceived} selector to accept the transfer.
|
||||
* - The internal {transfer} must succeed (returned `true`).
|
||||
*/
|
||||
function transferAndCall(address to, uint256 value) public returns (bool) {
|
||||
return transferAndCall(to, value, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {transferAndCall} that accepts an additional `data` parameter with
|
||||
* no specified format.
|
||||
*/
|
||||
function transferAndCall(address to, uint256 value, bytes memory data) public virtual returns (bool) {
|
||||
if (!transfer(to, value)) {
|
||||
revert ERC1363TransferFailed(to, value);
|
||||
}
|
||||
_checkOnTransferReceived(_msgSender(), to, value, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `to` must implement the {IERC1363Receiver} interface.
|
||||
* - The target must return the {IERC1363Receiver-onTransferReceived} selector to accept the transfer.
|
||||
* - The internal {transferFrom} must succeed (returned `true`).
|
||||
*/
|
||||
function transferFromAndCall(address from, address to, uint256 value) public returns (bool) {
|
||||
return transferFromAndCall(from, to, value, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {transferFromAndCall} that accepts an additional `data` parameter with
|
||||
* no specified format.
|
||||
*/
|
||||
function transferFromAndCall(
|
||||
address from,
|
||||
address to,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) public virtual returns (bool) {
|
||||
if (!transferFrom(from, to, value)) {
|
||||
revert ERC1363TransferFromFailed(from, to, value);
|
||||
}
|
||||
_checkOnTransferReceived(from, to, value, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
|
||||
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `spender` must implement the {IERC1363Spender} interface.
|
||||
* - The target must return the {IERC1363Spender-onApprovalReceived} selector to accept the approval.
|
||||
* - The internal {approve} must succeed (returned `true`).
|
||||
*/
|
||||
function approveAndCall(address spender, uint256 value) public returns (bool) {
|
||||
return approveAndCall(spender, value, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {approveAndCall} that accepts an additional `data` parameter with
|
||||
* no specified format.
|
||||
*/
|
||||
function approveAndCall(address spender, uint256 value, bytes memory data) public virtual returns (bool) {
|
||||
if (!approve(spender, value)) {
|
||||
revert ERC1363ApproveFailed(spender, value);
|
||||
}
|
||||
_checkOnApprovalReceived(spender, value, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs a call to {IERC1363Receiver-onTransferReceived} on a target address.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `to` must implement the {IERC1363Receiver} interface.
|
||||
* - The target must return the {IERC1363Receiver-onTransferReceived} selector to accept the transfer.
|
||||
*/
|
||||
function _checkOnTransferReceived(address from, address to, uint256 value, bytes memory data) private {
|
||||
if (to.code.length == 0) {
|
||||
revert ERC1363InvalidReceiver(to);
|
||||
}
|
||||
|
||||
try IERC1363Receiver(to).onTransferReceived(_msgSender(), from, value, data) returns (bytes4 retval) {
|
||||
if (retval != IERC1363Receiver.onTransferReceived.selector) {
|
||||
revert ERC1363InvalidReceiver(to);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
revert ERC1363InvalidReceiver(to);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs a call to {IERC1363Spender-onApprovalReceived} on a target address.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `spender` must implement the {IERC1363Spender} interface.
|
||||
* - The target must return the {IERC1363Spender-onApprovalReceived} selector to accept the approval.
|
||||
*/
|
||||
function _checkOnApprovalReceived(address spender, uint256 value, bytes memory data) private {
|
||||
if (spender.code.length == 0) {
|
||||
revert ERC1363InvalidSpender(spender);
|
||||
}
|
||||
|
||||
try IERC1363Spender(spender).onApprovalReceived(_msgSender(), value, data) returns (bytes4 retval) {
|
||||
if (retval != IERC1363Spender.onApprovalReceived.selector) {
|
||||
revert ERC1363InvalidSpender(spender);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
revert ERC1363InvalidSpender(spender);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {Context} from "../../../utils/Context.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 ERC20Burnable is Context, ERC20 {
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from the caller.
|
||||
*
|
||||
* See {ERC20-_burn}.
|
||||
*/
|
||||
function burn(uint256 value) public virtual {
|
||||
_burn(_msgSender(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of 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
|
||||
* `value`.
|
||||
*/
|
||||
function burnFrom(address account, uint256 value) public virtual {
|
||||
_spendAllowance(account, _msgSender(), value);
|
||||
_burn(account, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Capped.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
|
||||
*/
|
||||
abstract contract ERC20Capped is ERC20 {
|
||||
uint256 private immutable _cap;
|
||||
|
||||
/**
|
||||
* @dev Total supply cap has been exceeded.
|
||||
*/
|
||||
error ERC20ExceededCap(uint256 increasedSupply, uint256 cap);
|
||||
|
||||
/**
|
||||
* @dev The supplied cap is not a valid cap.
|
||||
*/
|
||||
error ERC20InvalidCap(uint256 cap);
|
||||
|
||||
/**
|
||||
* @dev Sets the value of the `cap`. This value is immutable, it can only be
|
||||
* set once during construction.
|
||||
*/
|
||||
constructor(uint256 cap_) {
|
||||
if (cap_ == 0) {
|
||||
revert ERC20InvalidCap(0);
|
||||
}
|
||||
_cap = cap_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the cap on the token's total supply.
|
||||
*/
|
||||
function cap() public view virtual returns (uint256) {
|
||||
return _cap;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC20-_update}.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual override {
|
||||
super._update(from, to, value);
|
||||
|
||||
if (from == address(0)) {
|
||||
uint256 maxSupply = cap();
|
||||
uint256 supply = totalSupply();
|
||||
if (supply > maxSupply) {
|
||||
revert ERC20ExceededCap(supply, maxSupply);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20FlashMint.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC3156FlashBorrower} from "../../../interfaces/IERC3156FlashBorrower.sol";
|
||||
import {IERC3156FlashLender} from "../../../interfaces/IERC3156FlashLender.sol";
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC-3156 Flash loans extension, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
|
||||
*
|
||||
* Adds the {flashLoan} method, which provides flash loan support at the token
|
||||
* level. By default there is no fee, but this can be changed by overriding {flashFee}.
|
||||
*
|
||||
* NOTE: When this extension is used along with the {ERC20Capped} or {ERC20Votes} extensions,
|
||||
* {maxFlashLoan} will not correctly reflect the maximum that can be flash minted. We recommend
|
||||
* overriding {maxFlashLoan} so that it correctly reflects the supply cap.
|
||||
*/
|
||||
abstract contract ERC20FlashMint is ERC20, IERC3156FlashLender {
|
||||
bytes32 private constant RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
|
||||
|
||||
/**
|
||||
* @dev The loan token is not valid.
|
||||
*/
|
||||
error ERC3156UnsupportedToken(address token);
|
||||
|
||||
/**
|
||||
* @dev The requested loan exceeds the max loan value for `token`.
|
||||
*/
|
||||
error ERC3156ExceededMaxLoan(uint256 maxLoan);
|
||||
|
||||
/**
|
||||
* @dev The receiver of a flashloan is not a valid {IERC3156FlashBorrower-onFlashLoan} implementer.
|
||||
*/
|
||||
error ERC3156InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Returns the maximum amount of tokens available for loan.
|
||||
* @param token The address of the token that is requested.
|
||||
* @return The amount of token that can be loaned.
|
||||
*
|
||||
* NOTE: This function does not consider any form of supply cap, so in case
|
||||
* it's used in a token with a cap like {ERC20Capped}, make sure to override this
|
||||
* function to integrate the cap instead of `type(uint256).max`.
|
||||
*/
|
||||
function maxFlashLoan(address token) public view virtual returns (uint256) {
|
||||
return token == address(this) ? type(uint256).max - totalSupply() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the fee applied when doing flash loans. This function calls
|
||||
* the {_flashFee} function which returns the fee applied when doing flash
|
||||
* loans.
|
||||
* @param token The token to be flash loaned.
|
||||
* @param value The amount of tokens to be loaned.
|
||||
* @return The fees applied to the corresponding flash loan.
|
||||
*/
|
||||
function flashFee(address token, uint256 value) public view virtual returns (uint256) {
|
||||
if (token != address(this)) {
|
||||
revert ERC3156UnsupportedToken(token);
|
||||
}
|
||||
return _flashFee(token, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the fee applied when doing flash loans. By default this
|
||||
* implementation has 0 fees. This function can be overloaded to make
|
||||
* the flash loan mechanism deflationary.
|
||||
* @param token The token to be flash loaned.
|
||||
* @param value The amount of tokens to be loaned.
|
||||
* @return The fees applied to the corresponding flash loan.
|
||||
*/
|
||||
function _flashFee(address token, uint256 value) internal view virtual returns (uint256) {
|
||||
// silence warning about unused variable without the addition of bytecode.
|
||||
token;
|
||||
value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the receiver address of the flash fee. By default this
|
||||
* implementation returns the address(0) which means the fee amount will be burnt.
|
||||
* This function can be overloaded to change the fee receiver.
|
||||
* @return The address for which the flash fee will be sent to.
|
||||
*/
|
||||
function _flashFeeReceiver() internal view virtual returns (address) {
|
||||
return address(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs a flash loan. New tokens are minted and sent to the
|
||||
* `receiver`, who is required to implement the {IERC3156FlashBorrower}
|
||||
* interface. By the end of the flash loan, the receiver is expected to own
|
||||
* value + fee tokens and have them approved back to the token contract itself so
|
||||
* they can be burned.
|
||||
* @param receiver The receiver of the flash loan. Should implement the
|
||||
* {IERC3156FlashBorrower-onFlashLoan} interface.
|
||||
* @param token The token to be flash loaned. Only `address(this)` is
|
||||
* supported.
|
||||
* @param value The amount of tokens to be loaned.
|
||||
* @param data An arbitrary datafield that is passed to the receiver.
|
||||
* @return `true` if the flash loan was successful.
|
||||
*/
|
||||
// This function can reenter, but it doesn't pose a risk because it always preserves the property that the amount
|
||||
// minted at the beginning is always recovered and burned at the end, or else the entire function will revert.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
function flashLoan(
|
||||
IERC3156FlashBorrower receiver,
|
||||
address token,
|
||||
uint256 value,
|
||||
bytes calldata data
|
||||
) public virtual returns (bool) {
|
||||
uint256 maxLoan = maxFlashLoan(token);
|
||||
if (value > maxLoan) {
|
||||
revert ERC3156ExceededMaxLoan(maxLoan);
|
||||
}
|
||||
uint256 fee = flashFee(token, value);
|
||||
_mint(address(receiver), value);
|
||||
if (receiver.onFlashLoan(_msgSender(), token, value, fee, data) != RETURN_VALUE) {
|
||||
revert ERC3156InvalidReceiver(address(receiver));
|
||||
}
|
||||
address flashFeeReceiver = _flashFeeReceiver();
|
||||
_spendAllowance(address(receiver), address(this), value + fee);
|
||||
if (fee == 0 || flashFeeReceiver == address(0)) {
|
||||
_burn(address(receiver), value + fee);
|
||||
} else {
|
||||
_burn(address(receiver), value);
|
||||
_transfer(address(receiver), flashFeeReceiver, fee);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Pausable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {Pausable} from "../../../utils/Pausable.sol";
|
||||
|
||||
/**
|
||||
* @dev ERC-20 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.
|
||||
*
|
||||
* IMPORTANT: This contract does not include public pause and unpause functions. In
|
||||
* addition to inheriting this contract, you must define both functions, invoking the
|
||||
* {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate
|
||||
* access control, e.g. using {AccessControl} or {Ownable}. Not doing so will
|
||||
* make the contract pause mechanism of the contract unreachable, and thus unusable.
|
||||
*/
|
||||
abstract contract ERC20Pausable is ERC20, Pausable {
|
||||
/**
|
||||
* @dev See {ERC20-_update}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the contract must not be paused.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual override whenNotPaused {
|
||||
super._update(from, to, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20Permit} from "./IERC20Permit.sol";
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
|
||||
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
|
||||
import {Nonces} from "../../../utils/Nonces.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
|
||||
*
|
||||
* Adds the {permit} method, which can be used to change an account's ERC-20 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.
|
||||
*/
|
||||
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
|
||||
bytes32 private constant PERMIT_TYPEHASH =
|
||||
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
|
||||
|
||||
/**
|
||||
* @dev Permit deadline has expired.
|
||||
*/
|
||||
error ERC2612ExpiredSignature(uint256 deadline);
|
||||
|
||||
/**
|
||||
* @dev Mismatched signature.
|
||||
*/
|
||||
error ERC2612InvalidSigner(address signer, address owner);
|
||||
|
||||
/**
|
||||
* @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 ERC-20 token name.
|
||||
*/
|
||||
constructor(string memory name) EIP712(name, "1") {}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC20Permit
|
||||
*/
|
||||
function permit(
|
||||
address owner,
|
||||
address spender,
|
||||
uint256 value,
|
||||
uint256 deadline,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual {
|
||||
if (block.timestamp > deadline) {
|
||||
revert ERC2612ExpiredSignature(deadline);
|
||||
}
|
||||
|
||||
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
|
||||
|
||||
bytes32 hash = _hashTypedDataV4(structHash);
|
||||
|
||||
address signer = ECDSA.recover(hash, v, r, s);
|
||||
if (signer != owner) {
|
||||
revert ERC2612InvalidSigner(signer, owner);
|
||||
}
|
||||
|
||||
_approve(owner, spender, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC20Permit
|
||||
*/
|
||||
function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
|
||||
return super.nonces(owner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC20Permit
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
|
||||
return _domainSeparatorV4();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Votes.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {Votes} from "../../../governance/utils/Votes.sol";
|
||||
import {Checkpoints} from "../../../utils/structs/Checkpoints.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of ERC-20 to support Compound-like voting and delegation. This version is more generic than Compound's,
|
||||
* and supports token supply up to 2^208^ - 1, while COMP is limited to 2^96^ - 1.
|
||||
*
|
||||
* NOTE: This contract does not provide interface compatibility with Compound's COMP token.
|
||||
*
|
||||
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
|
||||
* by calling the {Votes-delegate} function directly, or by providing a signature to be used with {Votes-delegateBySig}. Voting
|
||||
* power can be queried through the public accessors {Votes-getVotes} and {Votes-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.
|
||||
*/
|
||||
abstract contract ERC20Votes is ERC20, Votes {
|
||||
/**
|
||||
* @dev Total supply cap has been exceeded, introducing a risk of votes overflowing.
|
||||
*/
|
||||
error ERC20ExceededSafeSupply(uint256 increasedSupply, uint256 cap);
|
||||
|
||||
/**
|
||||
* @dev Maximum token supply. Defaults to `type(uint208).max` (2^208^ - 1).
|
||||
*
|
||||
* This maximum is enforced in {_update}. It limits the total supply of the token, which is otherwise a uint256,
|
||||
* so that checkpoints can be stored in the Trace208 structure used by {Votes}. Increasing this value will not
|
||||
* remove the underlying limitation, and will cause {_update} to fail because of a math overflow in
|
||||
* {Votes-_transferVotingUnits}. An override could be used to further restrict the total supply (to a lower value) if
|
||||
* additional logic requires it. When resolving override conflicts on this function, the minimum should be
|
||||
* returned.
|
||||
*/
|
||||
function _maxSupply() internal view virtual returns (uint256) {
|
||||
return type(uint208).max;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Move voting power when tokens are transferred.
|
||||
*
|
||||
* Emits a {IVotes-DelegateVotesChanged} event.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual override {
|
||||
super._update(from, to, value);
|
||||
if (from == address(0)) {
|
||||
uint256 supply = totalSupply();
|
||||
uint256 cap = _maxSupply();
|
||||
if (supply > cap) {
|
||||
revert ERC20ExceededSafeSupply(supply, cap);
|
||||
}
|
||||
}
|
||||
_transferVotingUnits(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the voting units of an `account`.
|
||||
*
|
||||
* WARNING: Overriding this function may compromise the internal vote accounting.
|
||||
* `ERC20Votes` assumes tokens map to voting units 1:1 and this is not easy to change.
|
||||
*/
|
||||
function _getVotingUnits(address account) internal view virtual override returns (uint256) {
|
||||
return balanceOf(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Get number of checkpoints for `account`.
|
||||
*/
|
||||
function numCheckpoints(address account) public view virtual returns (uint32) {
|
||||
return _numCheckpoints(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Get the `pos`-th checkpoint for `account`.
|
||||
*/
|
||||
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint208 memory) {
|
||||
return _checkpoints(account, pos);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Wrapper.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
|
||||
import {SafeERC20} from "../utils/SafeERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of the ERC-20 token contract to support token wrapping.
|
||||
*
|
||||
* Users can deposit and withdraw "underlying tokens" and receive a matching number of "wrapped tokens". This is useful
|
||||
* in conjunction with other modules. For example, combining this wrapping mechanism with {ERC20Votes} will allow the
|
||||
* wrapping of an existing "basic" ERC-20 into a governance token.
|
||||
*
|
||||
* WARNING: Any mechanism in which the underlying token changes the {balanceOf} of an account without an explicit transfer
|
||||
* may desynchronize this contract's supply and its underlying balance. Please exercise caution when wrapping tokens that
|
||||
* may undercollateralize the wrapper (i.e. wrapper's total supply is higher than its underlying balance). See {_recover}
|
||||
* for recovering value accrued to the wrapper.
|
||||
*/
|
||||
abstract contract ERC20Wrapper is ERC20 {
|
||||
IERC20 private immutable _underlying;
|
||||
|
||||
/**
|
||||
* @dev The underlying token couldn't be wrapped.
|
||||
*/
|
||||
error ERC20InvalidUnderlying(address token);
|
||||
|
||||
constructor(IERC20 underlyingToken) {
|
||||
if (underlyingToken == this) {
|
||||
revert ERC20InvalidUnderlying(address(this));
|
||||
}
|
||||
_underlying = underlyingToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC20-decimals}.
|
||||
*/
|
||||
function decimals() public view virtual override returns (uint8) {
|
||||
try IERC20Metadata(address(_underlying)).decimals() returns (uint8 value) {
|
||||
return value;
|
||||
} catch {
|
||||
return super.decimals();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the underlying ERC-20 token that is being wrapped.
|
||||
*/
|
||||
function underlying() public view returns (IERC20) {
|
||||
return _underlying;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
|
||||
*/
|
||||
function depositFor(address account, uint256 value) public virtual returns (bool) {
|
||||
address sender = _msgSender();
|
||||
if (sender == address(this)) {
|
||||
revert ERC20InvalidSender(address(this));
|
||||
}
|
||||
if (account == address(this)) {
|
||||
revert ERC20InvalidReceiver(account);
|
||||
}
|
||||
SafeERC20.safeTransferFrom(_underlying, sender, address(this), value);
|
||||
_mint(account, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
|
||||
*/
|
||||
function withdrawTo(address account, uint256 value) public virtual returns (bool) {
|
||||
if (account == address(this)) {
|
||||
revert ERC20InvalidReceiver(account);
|
||||
}
|
||||
_burn(_msgSender(), value);
|
||||
SafeERC20.safeTransfer(_underlying, account, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake or acquired from
|
||||
* rebasing mechanisms. Internal function that can be exposed with access control if desired.
|
||||
*/
|
||||
function _recover(address account) internal virtual returns (uint256) {
|
||||
uint256 value = _underlying.balanceOf(address(this)) - totalSupply();
|
||||
_mint(account, value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
|
||||
import {SafeERC20} from "../utils/SafeERC20.sol";
|
||||
import {IERC4626} from "../../../interfaces/IERC4626.sol";
|
||||
import {Math} from "../../../utils/math/Math.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
|
||||
*
|
||||
* This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
|
||||
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
|
||||
* the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
|
||||
* contract and not the "assets" token which is an independent contract.
|
||||
*
|
||||
* [CAUTION]
|
||||
* ====
|
||||
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
|
||||
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
|
||||
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
|
||||
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
|
||||
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
|
||||
* verifying the amount received is as expected, using a wrapper that performs these checks such as
|
||||
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
|
||||
*
|
||||
* Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
|
||||
* The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
|
||||
* and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
|
||||
* itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
|
||||
* offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
|
||||
* of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
|
||||
* With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
|
||||
* underlying math can be found xref:erc4626.adoc#inflation-attack[here].
|
||||
*
|
||||
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
|
||||
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
|
||||
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
|
||||
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
|
||||
* `_convertToShares` and `_convertToAssets` functions.
|
||||
*
|
||||
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
|
||||
* ====
|
||||
*/
|
||||
abstract contract ERC4626 is ERC20, IERC4626 {
|
||||
using Math for uint256;
|
||||
|
||||
IERC20 private immutable _asset;
|
||||
uint8 private immutable _underlyingDecimals;
|
||||
|
||||
/**
|
||||
* @dev Attempted to deposit more assets than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Attempted to mint more shares than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Attempted to redeem more shares than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
|
||||
*/
|
||||
constructor(IERC20 asset_) {
|
||||
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
|
||||
_underlyingDecimals = success ? assetDecimals : 18;
|
||||
_asset = asset_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
|
||||
*/
|
||||
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
|
||||
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
|
||||
abi.encodeCall(IERC20Metadata.decimals, ())
|
||||
);
|
||||
if (success && encodedDecimals.length >= 32) {
|
||||
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
|
||||
if (returnedDecimals <= type(uint8).max) {
|
||||
return (true, uint8(returnedDecimals));
|
||||
}
|
||||
}
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
|
||||
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
|
||||
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
|
||||
*
|
||||
* See {IERC20Metadata-decimals}.
|
||||
*/
|
||||
function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
|
||||
return _underlyingDecimals + _decimalsOffset();
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-asset}. */
|
||||
function asset() public view virtual returns (address) {
|
||||
return address(_asset);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-totalAssets}. */
|
||||
function totalAssets() public view virtual returns (uint256) {
|
||||
return _asset.balanceOf(address(this));
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-convertToShares}. */
|
||||
function convertToShares(uint256 assets) public view virtual returns (uint256) {
|
||||
return _convertToShares(assets, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-convertToAssets}. */
|
||||
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
|
||||
return _convertToAssets(shares, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxDeposit}. */
|
||||
function maxDeposit(address) public view virtual returns (uint256) {
|
||||
return type(uint256).max;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxMint}. */
|
||||
function maxMint(address) public view virtual returns (uint256) {
|
||||
return type(uint256).max;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxWithdraw}. */
|
||||
function maxWithdraw(address owner) public view virtual returns (uint256) {
|
||||
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxRedeem}. */
|
||||
function maxRedeem(address owner) public view virtual returns (uint256) {
|
||||
return balanceOf(owner);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewDeposit}. */
|
||||
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
|
||||
return _convertToShares(assets, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewMint}. */
|
||||
function previewMint(uint256 shares) public view virtual returns (uint256) {
|
||||
return _convertToAssets(shares, Math.Rounding.Ceil);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewWithdraw}. */
|
||||
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
|
||||
return _convertToShares(assets, Math.Rounding.Ceil);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewRedeem}. */
|
||||
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
|
||||
return _convertToAssets(shares, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-deposit}. */
|
||||
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
|
||||
uint256 maxAssets = maxDeposit(receiver);
|
||||
if (assets > maxAssets) {
|
||||
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
|
||||
}
|
||||
|
||||
uint256 shares = previewDeposit(assets);
|
||||
_deposit(_msgSender(), receiver, assets, shares);
|
||||
|
||||
return shares;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-mint}. */
|
||||
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
|
||||
uint256 maxShares = maxMint(receiver);
|
||||
if (shares > maxShares) {
|
||||
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
|
||||
}
|
||||
|
||||
uint256 assets = previewMint(shares);
|
||||
_deposit(_msgSender(), receiver, assets, shares);
|
||||
|
||||
return assets;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-withdraw}. */
|
||||
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
|
||||
uint256 maxAssets = maxWithdraw(owner);
|
||||
if (assets > maxAssets) {
|
||||
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
|
||||
}
|
||||
|
||||
uint256 shares = previewWithdraw(assets);
|
||||
_withdraw(_msgSender(), receiver, owner, assets, shares);
|
||||
|
||||
return shares;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-redeem}. */
|
||||
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
|
||||
uint256 maxShares = maxRedeem(owner);
|
||||
if (shares > maxShares) {
|
||||
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
|
||||
}
|
||||
|
||||
uint256 assets = previewRedeem(shares);
|
||||
_withdraw(_msgSender(), receiver, owner, assets, shares);
|
||||
|
||||
return assets;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
|
||||
*/
|
||||
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
|
||||
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
|
||||
*/
|
||||
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
|
||||
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Deposit/mint common workflow.
|
||||
*/
|
||||
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
|
||||
// If _asset is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
|
||||
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
|
||||
// calls the vault, which is assumed not malicious.
|
||||
//
|
||||
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
|
||||
// assets are transferred and before the shares are minted, which is a valid state.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
|
||||
_mint(receiver, shares);
|
||||
|
||||
emit Deposit(caller, receiver, assets, shares);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Withdraw/redeem common workflow.
|
||||
*/
|
||||
function _withdraw(
|
||||
address caller,
|
||||
address receiver,
|
||||
address owner,
|
||||
uint256 assets,
|
||||
uint256 shares
|
||||
) internal virtual {
|
||||
if (caller != owner) {
|
||||
_spendAllowance(owner, caller, shares);
|
||||
}
|
||||
|
||||
// If _asset is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
|
||||
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
|
||||
// calls the vault, which is assumed not malicious.
|
||||
//
|
||||
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
|
||||
// shares are burned and after the assets are transferred, which is a valid state.
|
||||
_burn(owner, shares);
|
||||
SafeERC20.safeTransfer(_asset, receiver, assets);
|
||||
|
||||
emit Withdraw(caller, receiver, owner, assets, shares);
|
||||
}
|
||||
|
||||
function _decimalsOffset() internal view virtual returns (uint8) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../IERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface for the optional metadata functions from the ERC-20 standard.
|
||||
*/
|
||||
interface IERC20Metadata is IERC20 {
|
||||
/**
|
||||
* @dev Returns the name of the token.
|
||||
*/
|
||||
function name() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the symbol of the token.
|
||||
*/
|
||||
function symbol() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the decimals places of the token.
|
||||
*/
|
||||
function decimals() external view returns (uint8);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
|
||||
*
|
||||
* Adds the {permit} method, which can be used to change an account's ERC-20 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.
|
||||
*
|
||||
* ==== Security Considerations
|
||||
*
|
||||
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
|
||||
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
|
||||
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
|
||||
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
|
||||
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
|
||||
* generally recommended is:
|
||||
*
|
||||
* ```solidity
|
||||
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
|
||||
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
|
||||
* doThing(..., value);
|
||||
* }
|
||||
*
|
||||
* function doThing(..., uint256 value) public {
|
||||
* token.safeTransferFrom(msg.sender, address(this), value);
|
||||
* ...
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
|
||||
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
|
||||
* {SafeERC20-safeTransferFrom}).
|
||||
*
|
||||
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
|
||||
* contracts should have entry points that don't rely on permit.
|
||||
*/
|
||||
interface IERC20Permit {
|
||||
/**
|
||||
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
|
||||
* given ``owner``'s signed approval.
|
||||
*
|
||||
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
|
||||
* ordering also apply here.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `spender` cannot be the zero address.
|
||||
* - `deadline` must be a timestamp in the future.
|
||||
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
|
||||
* over the EIP712-formatted function arguments.
|
||||
* - the signature must use ``owner``'s current nonce (see {nonces}).
|
||||
*
|
||||
* For more information on the signature format, see the
|
||||
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
|
||||
* section].
|
||||
*
|
||||
* CAUTION: See Security Considerations above.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../IERC20.sol";
|
||||
import {IERC1363} from "../../../interfaces/IERC1363.sol";
|
||||
import {Address} from "../../../utils/Address.sol";
|
||||
|
||||
/**
|
||||
* @title SafeERC20
|
||||
* @dev Wrappers around ERC-20 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;
|
||||
|
||||
/**
|
||||
* @dev An operation with an ERC-20 token failed.
|
||||
*/
|
||||
error SafeERC20FailedOperation(address token);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failed `decreaseAllowance` request.
|
||||
*/
|
||||
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
|
||||
|
||||
/**
|
||||
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
|
||||
* non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeTransfer(IERC20 token, address to, uint256 value) internal {
|
||||
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
|
||||
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
|
||||
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
|
||||
* non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
|
||||
uint256 oldAllowance = token.allowance(address(this), spender);
|
||||
forceApprove(token, spender, oldAllowance + value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
|
||||
* value, non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
|
||||
unchecked {
|
||||
uint256 currentAllowance = token.allowance(address(this), spender);
|
||||
if (currentAllowance < requestedDecrease) {
|
||||
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
|
||||
}
|
||||
forceApprove(token, spender, currentAllowance - requestedDecrease);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
|
||||
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
|
||||
* to be set to zero before setting it to a non-zero value, such as USDT.
|
||||
*/
|
||||
function forceApprove(IERC20 token, address spender, uint256 value) internal {
|
||||
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
|
||||
|
||||
if (!_callOptionalReturnBool(token, approvalCall)) {
|
||||
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
|
||||
_callOptionalReturn(token, approvalCall);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
|
||||
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
|
||||
* targeting contracts.
|
||||
*
|
||||
* Reverts if the returned value is other than `true`.
|
||||
*/
|
||||
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
|
||||
if (to.code.length == 0) {
|
||||
safeTransfer(token, to, value);
|
||||
} else if (!token.transferAndCall(to, value, data)) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
|
||||
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
|
||||
* targeting contracts.
|
||||
*
|
||||
* Reverts if the returned value is other than `true`.
|
||||
*/
|
||||
function transferFromAndCallRelaxed(
|
||||
IERC1363 token,
|
||||
address from,
|
||||
address to,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) internal {
|
||||
if (to.code.length == 0) {
|
||||
safeTransferFrom(token, from, to, value);
|
||||
} else if (!token.transferFromAndCall(from, to, value, data)) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
|
||||
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
|
||||
* targeting contracts.
|
||||
*
|
||||
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
|
||||
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
|
||||
* once without retrying, and relies on the returned value to be true.
|
||||
*
|
||||
* Reverts if the returned value is other than `true`.
|
||||
*/
|
||||
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
|
||||
if (to.code.length == 0) {
|
||||
forceApprove(token, to, value);
|
||||
} else if (!token.approveAndCall(to, value, data)) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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).
|
||||
*
|
||||
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
|
||||
*/
|
||||
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
|
||||
// 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 cannot use {Address-functionCall} here since this should return false
|
||||
// and not revert is the subcall reverts.
|
||||
|
||||
(bool success, bytes memory returndata) = address(token).call(data);
|
||||
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user