Index
IERC1363Spender
onApprovalReceived
function onApprovalReceived(address owner, uint256 value, bytes data) external returns (bytes4)
Handle the approval of ERC1363 tokens
Any ERC1363 smart contract calls this function on the recipient after an `approve`. This function MAY throw to revert and reject the approval. Return of other than the magic value MUST result in the transaction being reverted. Note: the token contract address is always the message sender.
owner
address
address The address which called `approveAndCall` function
value
uint256
uint256 The amount of tokens to be spent
data
bytes
bytes Additional data with no specified format
[0]
bytes4
`bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` unless throwing
IBErc20Token
mint
function mint(uint256 mintAmount) external returns (uint256)
Sender supplies assets into the market and receives cTokens in exchange
Accrues interest whether or not the operation succeeds, unless reverted
mintAmount
uint256
The amount of the underlying asset to supply
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
redeem
function redeem(uint256 redeemTokens) external returns (uint256)
Sender redeems cTokens in exchange for the underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemTokens
uint256
The number of cTokens to redeem into underlying
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
redeemUnderlying
function redeemUnderlying(uint256 redeemAmount) external returns (uint256)
Sender redeems cTokens in exchange for a specified amount of underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemAmount
uint256
The amount of underlying to redeem
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
borrow
function borrow(uint256 borrowAmount) external returns (uint256)
Sender borrows assets from the protocol to their own address
borrowAmount
uint256
The amount of the underlying asset to borrow
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
repayBorrow
function repayBorrow(uint256 repayAmount) external returns (uint256)
Sender repays their own borrow
repayAmount
uint256
The amount to repay
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
repayBorrowBehalf
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256)
Sender repays a borrow belonging to borrower
borrower
address
the account with the debt being payed off
repayAmount
uint256
The amount to repay
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
liquidateBorrow
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external returns (uint256)
The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator.
borrower
address
The borrower of this cToken to be liquidated
repayAmount
uint256
The amount of the underlying borrowed asset to repay
cTokenCollateral
address
The market in which to seize collateral from the borrower
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
balanceOf
function balanceOf(address owner) external view returns (uint256)
Get the token balance of the `owner`
owner
address
The address of the account to query
[0]
uint256
The number of tokens owned by `owner`
accountTokens
function accountTokens(address owner) external returns (uint256)
Get the underlying balance of the `owner`
This also accrues interest in a transaction
owner
address
The address of the account to query
[0]
uint256
The amount of underlying owned by `owner`
Initializable
_This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure that all initializers are idempotent. This is not verified automatically as constructors are by Solidity._
_initialized
bool _initialized
Indicates that the contract has been initialized.
_initializing
bool _initializing
Indicates that the contract is in the process of being initialized.
initializer
modifier initializer()
Modifier to protect an initializer function from being invoked twice.
ReentrancyGuard
_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]._
_NOT_ENTERED
uint256 _NOT_ENTERED
_ENTERED
uint256 _ENTERED
_status
uint256 _status
constructor
constructor() internal
nonReentrant
modifier nonReentrant()
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.
MerkleProof
_These functions deal with verification of Merkle Trees proofs.
The proofs can be generated using the JavaScript library https://github.com/miguelmota/merkletreejs[merkletreejs]. Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
See `test/utils/cryptography/MerkleProof.test.js` for some examples._
verify
function verify(bytes32[] proof, bytes32 root, bytes32 leaf) internal pure returns (bool)
Returns true if a `leaf` can be proved to be a part of a Merkle tree defined by `root`. For this, a `proof` must be provided, containing sibling hashes on the branch from the leaf to the root of the tree. Each pair of leaves and each pair of pre-images are assumed to be sorted.
Create2
_Helper to make usage of the `CREATE2` EVM opcode easier and safer. `CREATE2` can be used to compute in advance the address where a smart contract will be deployed, which allows for interesting new mechanisms known as 'counterfactual interactions'.
See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more information._
deploy
function deploy(uint256 amount, bytes32 salt, bytes bytecode) internal returns (address)
_Deploys a contract using `CREATE2`. The address where the contract will be deployed can be known in advance via {computeAddress}.
The bytecode for a contract can be obtained from Solidity with `type(contractName).creationCode`.
Requirements:
`bytecode` must not be empty.
`salt` must have not been used for `bytecode` already.
the factory must have a balance of at least `amount`.
if `amount` is non-zero, `bytecode` must have a `payable` constructor._
computeAddress
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address)
Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecodeHash` or `salt` will result in a new destination address.
computeAddress
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address)
Returns the address where a contract will be stored if deployed via {deploy} from a contract located at `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
IUniswapV2Factory
PairCreated
event PairCreated(address token0, address token1, address pair, uint256)
feeTo
function feeTo() external view returns (address)
feeToSetter
function feeToSetter() external view returns (address)
getPair
function getPair(address tokenA, address tokenB) external view returns (address pair)
allPairs
function allPairs(uint256) external view returns (address pair)
allPairsLength
function allPairsLength() external view returns (uint256)
createPair
function createPair(address tokenA, address tokenB) external returns (address pair)
setFeeTo
function setFeeTo(address) external
setFeeToSetter
function setFeeToSetter(address) external
MerkleProofUpgradeable
_These functions deal with verification of Merkle Trees proofs.
The proofs can be generated using the JavaScript library https://github.com/miguelmota/merkletreejs[merkletreejs]. Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
See `test/utils/cryptography/MerkleProof.test.js` for some examples._
verify
function verify(bytes32[] proof, bytes32 root, bytes32 leaf) internal pure returns (bool)
Returns true if a `leaf` can be proved to be a part of a Merkle tree defined by `root`. For this, a `proof` must be provided, containing sibling hashes on the branch from the leaf to the root of the tree. Each pair of leaves and each pair of pre-images are assumed to be sorted.
ClonesUpgradeable
_https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for deploying minimal proxy contracts, also known as "clones".
> To simply and cheaply clone contract functionality in an immutable way, this standard specifies > a minimal bytecode implementation that delegates all calls to a known, fixed address.
The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the deterministic method.
Available since v3.4._
clone
function clone(address implementation) internal returns (address instance)
_Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
This function uses the create opcode, which should never revert._
cloneDeterministic
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance)
_Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same `implementation` and `salt` multiple time will revert, since the clones cannot be deployed twice at the same address._
predictDeterministicAddress
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted)
Computes the address of a clone deployed using {Clones-cloneDeterministic}.
predictDeterministicAddress
function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted)
Computes the address of a clone deployed using {Clones-cloneDeterministic}.
PrimaryIndexToken
MODERATOR_ROLE
bytes32 MODERATOR_ROLE
name
string name
symbol
string symbol
priceOracle
contract IPriceProviderAggregator priceOracle
projectTokens
address[] projectTokens
projectTokenInfo
mapping(address => struct PrimaryIndexToken.ProjectTokenInfo) projectTokenInfo
lendingTokens
address[] lendingTokens
lendingTokenInfo
mapping(address => struct PrimaryIndexToken.LendingTokenInfo) lendingTokenInfo
totalDepositedProjectToken
mapping(address => uint256) totalDepositedProjectToken
depositPosition
mapping(address => mapping(address => mapping(address => struct PrimaryIndexToken.DepositPosition))) depositPosition
borrowPosition
mapping(address => mapping(address => mapping(address => struct PrimaryIndexToken.BorrowPosition))) borrowPosition
totalBorrow
mapping(address => mapping(address => uint256)) totalBorrow
borrowLimit
mapping(address => mapping(address => uint256)) borrowLimit
Ratio
struct Ratio {
uint8 numerator;
uint8 denominator;
}
ProjectTokenInfo
struct ProjectTokenInfo {
bool isListed;
bool isDepositPaused;
bool isWithdrawPaused;
struct PrimaryIndexToken.Ratio loanToValueRatio;
struct PrimaryIndexToken.Ratio liquidationThresholdFactor;
struct PrimaryIndexToken.Ratio liquidationIncentive;
}
LendingTokenInfo
struct LendingTokenInfo {
bool isListed;
bool isPaused;
contract BLendingToken bLendingToken;
}
DepositPosition
struct DepositPosition {
uint256 depositedProjectTokenAmount;
}
BorrowPosition
struct BorrowPosition {
uint256 loanBody;
uint256 accrual;
}
AddPrjToken
event AddPrjToken(address tokenPrj)
LoanToValueRatioSet
event LoanToValueRatioSet(address tokenPrj, uint8 lvrNumerator, uint8 lvrDenominator)
LiquidationThresholdFactorSet
event LiquidationThresholdFactorSet(address tokenPrj, uint8 ltfNumerator, uint8 ltfDenominator)
LiquidationIncentiveSet
event LiquidationIncentiveSet(address tokenPrj, uint8 ltfNumerator, uint8 ltfDenominator)
Deposit
event Deposit(address who, address tokenPrj, address lendingToken, uint256 prjDepositAmount, address beneficiary)
Withdraw
event Withdraw(address who, address tokenPrj, address lendingToken, uint256 prjWithdrawAmount, address beneficiary)
Supply
event Supply(address who, address supplyToken, uint256 supplyAmount, address supplyBToken, uint256 amountSupplyBTokenReceived)
Redeem
event Redeem(address who, address redeemToken, address redeemBToken, uint256 redeemAmount)
RedeemUnderlying
event RedeemUnderlying(address who, address redeemToken, address redeemBToken, uint256 redeemAmountUnderlying)
Borrow
event Borrow(address who, address borrowToken, uint256 borrowAmount, address prjAddress, uint256 prjAmount)
RepayBorrow
event RepayBorrow(address who, address borrowToken, uint256 borrowAmount, address prjAddress, bool isPositionFullyRepaid)
Liquidate
event Liquidate(address liquidator, address borrower, address lendingToken, address prjAddress, uint256 amountPrjLiquidated)
initialize
function initialize() public
onlyAdmin
modifier onlyAdmin()
onlyModerator
modifier onlyModerator()
isProjectTokenListed
modifier isProjectTokenListed(address projectToken)
isLendingTokenListed
modifier isLendingTokenListed(address lendingToken)
addProjectToken
function addProjectToken(address _projectToken, uint8 _loanToValueRatioNumerator, uint8 _loanToValueRatioDenominator, uint8 _liquidationThresholdFactorNumerator, uint8 _liquidationThresholdFactorDenominator, uint8 _liquidationIncentiveNumerator, uint8 _liquidationIncentiveDenominator) public
removeProjectToken
function removeProjectToken(uint256 _projectTokenId) public
addLendingToken
function addLendingToken(address _lendingToken, address _bLendingToken, bool _isPaused) public
removeLendingToken
function removeLendingToken(uint256 _lendingTokenId) public
setPriceOracle
function setPriceOracle(address _priceOracle) public
grandModerator
function grandModerator(address newModerator) public
revokeModerator
function revokeModerator(address moderator) public
setBorrowLimit
function setBorrowLimit(address projectToken, address lendingToken, uint256 _borrowLimit) public
setProjectTokenInfo
function setProjectTokenInfo(address _projectToken, uint8 _loanToValueRatioNumerator, uint8 _loanToValueRatioDenominator, uint8 _liquidationThresholdFactorNumerator, uint8 _liquidationThresholdFactorDenominator, uint8 _liquidationIncentiveNumerator, uint8 _liquidationIncentiveDenominator) public
setPausedProjectToken
function setPausedProjectToken(address _projectToken, bool _isDepositPaused, bool _isWithdrawPaused) public
setLendingTokenInfo
function setLendingTokenInfo(address _lendingToken, address _bLendingToken, bool _isPaused) public
setPausedLendingToken
function setPausedLendingToken(address _lendingToken, bool _isPaused) public
deposit
function deposit(address projectToken, address lendingToken, uint256 projectTokenAmount) public
withdraw
function withdraw(address projectToken, address lendingToken, uint256 projectTokenAmount) public
supply
function supply(address lendingToken, uint256 lendingTokenAmount) public
redeem
function redeem(address lendingToken, uint256 bLendingTokenAmount) public
redeemUnderlying
function redeemUnderlying(address lendingToken, uint256 lendingTokenAmount) public
borrow
function borrow(address projectToken, address lendingToken, uint256 lendingTokenAmount) public
repay
function repay(address projectToken, address lendingToken, uint256 lendingTokenAmount) public returns (uint256)
repayInternal
function repayInternal(address repairer, address borrower, address projectToken, address lendingToken, uint256 lendingTokenAmount) internal returns (uint256)
liquidate
function liquidate(address account, address projectToken, address lendingToken) public
updateInterestInBorrowPositions
function updateInterestInBorrowPositions(address account, address lendingToken) public
pit
function pit(address account, address projectToken, address lendingToken) public view returns (uint256)
pitRemaining
function pitRemaining(address account, address projectToken, address lendingToken) public view returns (uint256)
liquidationThreshold
function liquidationThreshold(address account, address projectToken, address lendingToken) public view returns (uint256)
totalOutstanding
function totalOutstanding(address account, address projectToken, address lendingToken) public view returns (uint256)
healthFactor
function healthFactor(address account, address projectToken, address lendingToken) public view returns (uint256 numerator, uint256 denominator)
getProjectTokenEvaluation
function getProjectTokenEvaluation(address projectToken, uint256 projectTokenAmount) public view returns (uint256)
lendingTokensLength
function lendingTokensLength() public view returns (uint256)
projectTokensLength
function projectTokensLength() public view returns (uint256)
getPosition
function getPosition(address account, address projectToken, address lendingToken) public view returns (uint256 depositedProjectTokenAmount, uint256 loanBody, uint256 accrual, uint256 healthFactorNumerator, uint256 healthFactorDenominator)
decimals
function decimals() public pure returns (uint8)
PrimaryLendingPlatformProxyAdmin
minimumDelayPeriod
uint256 minimumDelayPeriod
delayPeriod
uint256 delayPeriod
UpgradeData
struct UpgradeData {
uint256 appendTimestamp;
uint256 delayPeriod;
address oldImplementation;
address newImplementation;
}
upgradeData
mapping(address => struct PrimaryLendingPlatformProxyAdmin.UpgradeData) upgradeData
SetDelayPeriod
event SetDelayPeriod(uint256 oldDelayPeriod, uint256 newDelayPeriod)
AppendUpgrade
event AppendUpgrade(address proxy, uint256 appendTimestamp, uint256 delayPeriod, address oldImplementation, address newImplementation)
Upgrade
event Upgrade(address proxy, uint256 upgradeTimestamp, address oldImplementation, address newImplementation)
constructor
constructor() public
setDelayPeriod
function setDelayPeriod(uint256 _delayPeriod) public
changeProxyAdmin
function changeProxyAdmin(contract TransparentUpgradeableProxy proxy, address newAdmin) public
_Changes the admin of `proxy` to `newAdmin`.
Requirements:
This contract must be the current admin of `proxy`._
appendUpgrade
function appendUpgrade(contract TransparentUpgradeableProxy proxy, address newImplementation) public
upgrade
function upgrade(contract TransparentUpgradeableProxy proxy, address implementation) public
_Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
Requirements:
This contract must be the admin of `proxy`._
upgradeAndCall
function upgradeAndCall(contract TransparentUpgradeableProxy proxy, address implementation, bytes data) public payable
_Upgrades `proxy` to `implementation` and calls a function on the new implementation. See {TransparentUpgradeableProxy-upgradeToAndCall}.
Requirements:
This contract must be the admin of `proxy`._
BErc20
CTokens which wrap an EIP-20 underlying
initialize
function initialize(address underlying_, contract Bondtroller comptroller_, contract InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string name_, string symbol_, uint8 decimals_) public
Initialize the new money market
underlying_
address
The address of the underlying asset
comptroller_
contract Bondtroller
The address of the Comptroller
interestRateModel_
contract InterestRateModel
The address of the interest rate model
initialExchangeRateMantissa_
uint256
The initial exchange rate, scaled by 1e18
name_
string
ERC-20 name of this token
symbol_
string
ERC-20 symbol of this token
decimals_
uint8
ERC-20 decimal precision of this token
sweepToken
function sweepToken(contract EIP20NonStandardInterface token) external
A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
token
contract EIP20NonStandardInterface
The address of the ERC-20 token to sweep
_addReserves
function _addReserves(uint256 addAmount) external returns (uint256)
The sender adds to reserves.
addAmount
uint256
The amount fo underlying token to add as reserves
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
getCashPrior
function getCashPrior() internal view returns (uint256)
Gets balance of this contract in terms of the underlying
This excludes the value of the current message, if any
[0]
uint256
The quantity of underlying tokens owned by this contract
doTransferIn
function doTransferIn(address from, uint256 amount) internal returns (uint256)
_Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. This will revert due to insufficient balance or insufficient allowance. This function returns the actual amount received, which may be less than `amount` if there is a fee attached to the transfer.
Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca_
doTransferOut
function doTransferOut(address payable to, uint256 amount) internal
_Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified it is >= amount, this should not revert in normal conditions.
Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca_
BEther
CToken which wraps Ether
constructor
constructor(contract Bondtroller bondtroller_, contract InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string name_, string symbol_, uint8 decimals_, address payable admin_) public
Construct a new CEther money market
bondtroller_
contract Bondtroller
The address of the Comptroller
interestRateModel_
contract InterestRateModel
The address of the interest rate model
initialExchangeRateMantissa_
uint256
The initial exchange rate, scaled by 1e18
name_
string
ERC-20 name of this token
symbol_
string
ERC-20 symbol of this token
decimals_
uint8
ERC-20 decimal precision of this token
admin_
address payable
Address of the administrator of this token
mint
function mint() external payable
Sender supplies assets into the market and receives cTokens in exchange
Reverts upon any failure
redeem
function redeem(uint256 redeemTokens) external returns (uint256)
Sender redeems cTokens in exchange for the underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemTokens
uint256
The number of cTokens to redeem into underlying
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
redeemUnderlying
function redeemUnderlying(uint256 redeemAmount) external returns (uint256)
Sender redeems cTokens in exchange for a specified amount of underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemAmount
uint256
The amount of underlying to redeem
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
borrow
function borrow(uint256 borrowAmount) external returns (uint256)
Sender borrows assets from the protocol to their own address
borrowAmount
uint256
The amount of the underlying asset to borrow
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
repayBorrow
function repayBorrow() external payable
Sender repays their own borrow
Reverts upon any failure
repayBorrowBehalf
function repayBorrowBehalf(address borrower) external payable
Sender repays a borrow belonging to borrower
Reverts upon any failure
borrower
address
the account with the debt being payed off
_addReserves
function _addReserves() external payable returns (uint256)
The sender adds to reserves.
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
fallback
fallback() external payable
Send Ether to CEther to mint
receive
receive() external payable
getCashPrior
function getCashPrior() internal view returns (uint256)
Gets balance of this contract in terms of Ether, before this message
This excludes the value of the current message, if any
[0]
uint256
The quantity of Ether owned by this contract
doTransferIn
function doTransferIn(address from, uint256 amount) internal returns (uint256)
Perform the actual transfer in, which is a no-op
from
address
Address sending the Ether
amount
uint256
Amount of Ether being sent
[0]
uint256
The actual amount of Ether transferred
doTransferOut
function doTransferOut(address payable to, uint256 amount) internal
Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. / f
requireNoError
function requireNoError(uint256 errCode, string message) internal pure
BLendingToken
MODERATOR_ROLE
bytes32 MODERATOR_ROLE
primaryIndexToken
address primaryIndexToken
SetPrimaryIndexToken
event SetPrimaryIndexToken(address oldPrimaryIndexToken, address newPrimaryIndexToken)
init
function init(address underlying_, contract Bondtroller bondtroller_, contract InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string name_, string symbol_, uint8 decimals_, address admin_) public
onlyAdmin
modifier onlyAdmin()
onlyPrimaryIndexToken
modifier onlyPrimaryIndexToken()
onlyModerator
modifier onlyModerator()
setPrimaryIndexToken
function setPrimaryIndexToken(address _primaryIndexToken) public
grandModerator
function grandModerator(address newModerator) public
revokeModerator
function revokeModerator(address moderator) public
setReserveFactor
function setReserveFactor(uint256 reserveFactorMantissa) public
mintTo
function mintTo(address minter, uint256 mintAmount) external returns (uint256 err, uint256 mintedAmount)
redeemTo
function redeemTo(address redeemer, uint256 redeemTokens) external returns (uint256 redeemErr)
redeemUnderlyingTo
function redeemUnderlyingTo(address redeemer, uint256 redeemAmount) external returns (uint256 redeemUnderlyingError)
borrowTo
function borrowTo(address borrower, uint256 borrowAmount) external returns (uint256 borrowError)
repayTo
function repayTo(address payer, address borrower, uint256 repayAmount) external returns (uint256 repayBorrowError, uint256 amountRepayed)
getEstimatedBorrowIndex
function getEstimatedBorrowIndex() public view returns (uint256)
getEstimatedBorrowBalanceStored
function getEstimatedBorrowBalanceStored(address account) public view returns (uint256 accrual)
BToken
Abstract base for CTokens
initialize
function initialize(contract Bondtroller bondtroller_, contract InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string name_, string symbol_, uint8 decimals_) public
Initialize the money market
bondtroller_
contract Bondtroller
The address of the Bondtroller
interestRateModel_
contract InterestRateModel
The address of the interest rate model
initialExchangeRateMantissa_
uint256
The initial exchange rate, scaled by 1e18
name_
string
EIP-20 name of this token
symbol_
string
EIP-20 symbol of this token
decimals_
uint8
EIP-20 decimal precision of this token
transferTokens
function transferTokens(address spender, address src, address dst, uint256 tokens) internal returns (uint256)
Transfer `tokens` tokens from `src` to `dst` by `spender`
Called by both `transfer` and `transferFrom` internally
spender
address
The address of the account performing the transfer
src
address
The address of the source account
dst
address
The address of the destination account
tokens
uint256
The number of tokens to transfer
[0]
uint256
Whether or not the transfer succeeded
transfer
function transfer(address dst, uint256 amount) external returns (bool)
Transfer `amount` tokens from `msg.sender` to `dst`
dst
address
The address of the destination account
amount
uint256
The number of tokens to transfer
[0]
bool
Whether or not the transfer succeeded
transferFrom
function transferFrom(address src, address dst, uint256 amount) external returns (bool)
Transfer `amount` tokens from `src` to `dst`
src
address
The address of the source account
dst
address
The address of the destination account
amount
uint256
The number of tokens to transfer
[0]
bool
Whether or not the transfer succeeded
approve
function approve(address spender, uint256 amount) external returns (bool)
Approve `spender` to transfer up to `amount` from `src`
This will overwrite the approval amount for `spender` and is subject to issues noted here
spender
address
The address of the account which may transfer tokens
amount
uint256
The number of tokens that are approved (-1 means infinite)
[0]
bool
Whether or not the approval succeeded
allowance
function allowance(address owner, address spender) external view returns (uint256)
Get the current allowance from `owner` for `spender`
owner
address
The address of the account which owns the tokens to be spent
spender
address
The address of the account which may transfer tokens
[0]
uint256
The number of tokens allowed to be spent (-1 means infinite)
balanceOf
function balanceOf(address owner) external view returns (uint256)
Get the token balance of the `owner`
owner
address
The address of the account to query
[0]
uint256
The number of tokens owned by `owner`
balanceOfUnderlying
function balanceOfUnderlying(address owner) external returns (uint256)
Get the underlying balance of the `owner`
This also accrues interest in a transaction
owner
address
The address of the account to query
[0]
uint256
The amount of underlying owned by `owner`
balanceOfUnderlyingView
function balanceOfUnderlyingView(address owner) external view returns (uint256)
getAccountSnapshot
function getAccountSnapshot(address account) external view returns (uint256, uint256, uint256, uint256)
Get a snapshot of the account's balances, and the cached exchange rate
This is used by bondtroller to more efficiently perform liquidity checks.
account
address
Address of the account to snapshot
[0]
uint256
(possible error, token balance, borrow balance, exchange rate mantissa)
[1]
uint256
[2]
uint256
[3]
uint256
getBlockNumber
function getBlockNumber() internal view returns (uint256)
Function to simply retrieve block number This exists mainly for inheriting test contracts to stub this result.
borrowRatePerBlock
function borrowRatePerBlock() external view returns (uint256)
Returns the current per-block borrow interest rate for this cToken
[0]
uint256
The borrow interest rate per block, scaled by 1e18
supplyRatePerBlock
function supplyRatePerBlock() external view returns (uint256)
Returns the current per-block supply interest rate for this cToken
[0]
uint256
The supply interest rate per block, scaled by 1e18
totalBorrowsCurrent
function totalBorrowsCurrent() external returns (uint256)
Returns the current total borrows plus accrued interest
[0]
uint256
The total borrows with interest
borrowBalanceCurrent
function borrowBalanceCurrent(address account) external returns (uint256)
Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
account
address
The address whose balance should be calculated after updating borrowIndex
[0]
uint256
The calculated balance
borrowBalanceStored
function borrowBalanceStored(address account) public view returns (uint256)
Return the borrow balance of account based on stored data
account
address
The address whose balance should be calculated
[0]
uint256
The calculated balance
borrowBalanceStoredInternal
function borrowBalanceStoredInternal(address account) internal view returns (enum CarefulMath.MathError, uint256)
Return the borrow balance of account based on stored data
account
address
The address whose balance should be calculated
[0]
enum CarefulMath.MathError
(error code, the calculated balance or 0 if error code is non-zero)
[1]
uint256
exchangeRateCurrent
function exchangeRateCurrent() public returns (uint256)
Accrue interest then return the up-to-date exchange rate
[0]
uint256
Calculated exchange rate scaled by 1e18
exchangeRateStored
function exchangeRateStored() public view returns (uint256)
Calculates the exchange rate from the underlying to the CToken
This function does not accrue interest before calculating the exchange rate
[0]
uint256
Calculated exchange rate scaled by 1e18
exchangeRateStoredInternal
function exchangeRateStoredInternal() internal view returns (enum CarefulMath.MathError, uint256)
Calculates the exchange rate from the underlying to the CToken
This function does not accrue interest before calculating the exchange rate
[0]
enum CarefulMath.MathError
(error code, calculated exchange rate scaled by 1e18)
[1]
uint256
getCash
function getCash() external view returns (uint256)
Get cash balance of this cToken in the underlying asset
[0]
uint256
The quantity of underlying asset owned by this contract
accrueInterest
function accrueInterest() public returns (uint256)
Applies accrued interest to total borrows and reserves
This calculates interest accrued from the last checkpointed block up to the current block and writes new checkpoint to storage.
mintInternal
function mintInternal(uint256 mintAmount) internal returns (uint256, uint256)
Sender supplies assets into the market and receives cTokens in exchange
Accrues interest whether or not the operation succeeds, unless reverted
mintAmount
uint256
The amount of the underlying asset to supply
[0]
uint256
(uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
[1]
uint256
MintLocalVars
struct MintLocalVars {
enum TokenErrorReporter.Error err;
enum CarefulMath.MathError mathErr;
uint256 exchangeRateMantissa;
uint256 mintTokens;
uint256 totalSupplyNew;
uint256 accountTokensNew;
uint256 actualMintAmount;
}
mintFresh
function mintFresh(address minter, uint256 mintAmount) internal returns (uint256, uint256)
User supplies assets into the market and receives cTokens in exchange
Assumes interest has already been accrued up to the current block
minter
address
The address of the account which is supplying the assets
mintAmount
uint256
The amount of the underlying asset to supply
[0]
uint256
(uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
[1]
uint256
redeemInternal
function redeemInternal(uint256 redeemTokens) internal returns (uint256)
Sender redeems cTokens in exchange for the underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemTokens
uint256
The number of cTokens to redeem into underlying
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
redeemUnderlyingInternal
function redeemUnderlyingInternal(uint256 redeemAmount) internal returns (uint256)
Sender redeems cTokens in exchange for a specified amount of underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemAmount
uint256
The amount of underlying to receive from redeeming cTokens
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
RedeemLocalVars
struct RedeemLocalVars {
enum TokenErrorReporter.Error err;
enum CarefulMath.MathError mathErr;
uint256 exchangeRateMantissa;
uint256 redeemTokens;
uint256 redeemAmount;
uint256 totalSupplyNew;
uint256 accountTokensNew;
}
redeemFresh
function redeemFresh(address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn) internal returns (uint256)
User redeems cTokens in exchange for the underlying asset
Assumes interest has already been accrued up to the current block
redeemer
address payable
The address of the account which is redeeming the tokens
redeemTokensIn
uint256
The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
redeemAmountIn
uint256
The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
borrowInternal
function borrowInternal(uint256 borrowAmount) internal returns (uint256)
Sender borrows assets from the protocol to their own address
borrowAmount
uint256
The amount of the underlying asset to borrow
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
BorrowLocalVars
struct BorrowLocalVars {
enum CarefulMath.MathError mathErr;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
}
borrowFresh
function borrowFresh(address payable borrower, uint256 borrowAmount) internal returns (uint256)
Users borrow assets from the protocol to their own address
borrower
address payable
borrowAmount
uint256
The amount of the underlying asset to borrow
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
repayBorrowInternal
function repayBorrowInternal(uint256 repayAmount) internal returns (uint256, uint256)
Sender repays their own borrow
repayAmount
uint256
The amount to repay
[0]
uint256
(uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
[1]
uint256
repayBorrowBehalfInternal
function repayBorrowBehalfInternal(address borrower, uint256 repayAmount) internal returns (uint256, uint256)
Sender repays a borrow belonging to borrower
borrower
address
the account with the debt being payed off
repayAmount
uint256
The amount to repay
[0]
uint256
(uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
[1]
uint256
RepayBorrowLocalVars
struct RepayBorrowLocalVars {
enum TokenErrorReporter.Error err;
enum CarefulMath.MathError mathErr;
uint256 repayAmount;
uint256 borrowerIndex;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
uint256 actualRepayAmount;
}
repayBorrowFresh
function repayBorrowFresh(address payer, address borrower, uint256 repayAmount) internal returns (uint256, uint256)
Borrows are repaid by another user (possibly the borrower).
payer
address
the account paying off the borrow
borrower
address
the account with the debt being payed off
repayAmount
uint256
the amount of undelrying tokens being returned
[0]
uint256
(uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
[1]
uint256
_setPendingAdmin
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256)
Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
_Admin function to begin change of admin. The newPendingAdmin must call `acceptAdmin` to finalize the transfer.
newPendingAdmin
address payable
New pending admin.
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
_acceptAdmin
function _acceptAdmin() external returns (uint256)
Accepts transfer of admin rights. msg.sender must be pendingAdmin
Admin function for pending admin to accept role and update admin
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
_setBondtroller
function _setBondtroller(contract Bondtroller newBondtroller) public returns (uint256)
Sets a new bondtroller for the market
Admin function to set a new bondtroller
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
_setReserveFactor
function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256)
accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
Admin function to accrue interest and set a new reserve factor
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
_setReserveFactorFresh
function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256)
Sets a new reserve factor for the protocol (*requires fresh interest accrual)
Admin function to set a new reserve factor
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
_addReservesInternal
function _addReservesInternal(uint256 addAmount) internal returns (uint256)
Accrues interest and reduces reserves by transferring from msg.sender
addAmount
uint256
Amount of addition to reserves
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
_addReservesFresh
function _addReservesFresh(uint256 addAmount) internal returns (uint256, uint256)
Add reserves by transferring from caller
Requires fresh interest accrual
addAmount
uint256
Amount of addition to reserves
[0]
uint256
(uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees /
[1]
uint256
_reduceReserves
function _reduceReserves(uint256 reduceAmount) external returns (uint256)
Accrues interest and reduces reserves by transferring to admin
reduceAmount
uint256
Amount of reduction to reserves
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
_reduceReservesFresh
function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256)
Reduces reserves by transferring to admin
Requires fresh interest accrual
reduceAmount
uint256
Amount of reduction to reserves
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
_setInterestRateModel
function _setInterestRateModel(contract InterestRateModel newInterestRateModel) public returns (uint256)
accrues interest and updates the interest rate model using _setInterestRateModelFresh
Admin function to accrue interest and update the interest rate model
newInterestRateModel
contract InterestRateModel
the new interest rate model to use
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / f
_setInterestRateModelFresh
function _setInterestRateModelFresh(contract InterestRateModel newInterestRateModel) internal returns (uint256)
updates the interest rate model (*requires fresh interest accrual)
Admin function to update the interest rate model
newInterestRateModel
contract InterestRateModel
the new interest rate model to use
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / f
getCashPrior
function getCashPrior() internal view virtual returns (uint256)
Gets balance of this contract in terms of the underlying
This excludes the value of the current message, if any
[0]
uint256
The quantity of underlying owned by this contract / f
doTransferIn
function doTransferIn(address from, uint256 amount) internal virtual returns (uint256)
Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. This may revert due to insufficient balance or insufficient allowance. / f
doTransferOut
function doTransferOut(address payable to, uint256 amount) internal virtual
Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. / f
nonReentrant
modifier nonReentrant()
Prevents a contract from calling itself, directly or indirectly. / m
BTokenStorage
_notEntered
bool _notEntered
Guard variable for re-entrancy checks
name
string name
EIP-20 token name for this token
symbol
string symbol
EIP-20 token symbol for this token
decimals
uint8 decimals
EIP-20 token decimals for this token
borrowRateMaxMantissa
uint256 borrowRateMaxMantissa
Maximum borrow rate that can ever be applied (.0005% / block)
reserveFactorMaxMantissa
uint256 reserveFactorMaxMantissa
Maximum fraction of interest that can be set aside for reserves
admin
address payable admin
Administrator for this contract
pendingAdmin
address payable pendingAdmin
Pending administrator for this contract
bondtroller
contract Bondtroller bondtroller
Contract which oversees inter-cToken operations
interestRateModel
contract InterestRateModel interestRateModel
Model which tells what the current interest rate should be
initialExchangeRateMantissa
uint256 initialExchangeRateMantissa
Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
reserveFactorMantissa
uint256 reserveFactorMantissa
Fraction of interest currently set aside for reserves
accrualBlockNumber
uint256 accrualBlockNumber
Block number that interest was last accrued at
borrowIndex
uint256 borrowIndex
Accumulator of the total earned interest rate since the opening of the market
totalBorrows
uint256 totalBorrows
Total amount of outstanding borrows of the underlying in this market
totalReserves
uint256 totalReserves
Total amount of reserves of the underlying held in this market
totalSupply
uint256 totalSupply
Total number of tokens in circulation
accountTokens
mapping(address => uint256) accountTokens
Official record of token balances for each account
transferAllowances
mapping(address => mapping(address => uint256)) transferAllowances
Approved token transfer amounts on behalf of others
BorrowSnapshot
struct BorrowSnapshot {
uint256 principal;
uint256 interestIndex;
}
accountBorrows
mapping(address => struct BTokenStorage.BorrowSnapshot) accountBorrows
Mapping of account addresses to outstanding borrow balances
protocolSeizeShareMantissa
uint256 protocolSeizeShareMantissa
Share of seized collateral that is added to reserves
BTokenInterface
isCToken
bool isCToken
Indicator that this is a CToken contract (for inspection)
AccrueInterest
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows)
Event emitted when interest is accrued
Mint
event Mint(address minter, uint256 mintAmount, uint256 mintTokens)
Event emitted when tokens are minted
Redeem
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens)
Event emitted when tokens are redeemed
Borrow
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows)
Event emitted when underlying is borrowed
RepayBorrow
event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows)
Event emitted when a borrow is repaid
LiquidateBorrow
event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens)
Event emitted when a borrow is liquidated
NewPendingAdmin
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin)
Event emitted when pendingAdmin is changed
NewAdmin
event NewAdmin(address oldAdmin, address newAdmin)
Event emitted when pendingAdmin is accepted, which means admin is updated
NewBondtroller
event NewBondtroller(contract Bondtroller oldBondtroller, contract Bondtroller newBondtroller)
Event emitted when bondtroller is changed
NewMarketInterestRateModel
event NewMarketInterestRateModel(contract InterestRateModel oldInterestRateModel, contract InterestRateModel newInterestRateModel)
Event emitted when interestRateModel is changed
NewReserveFactor
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa)
Event emitted when the reserve factor is changed
ReservesAdded
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves)
Event emitted when the reserves are added
ReservesReduced
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves)
Event emitted when the reserves are reduced
Transfer
event Transfer(address from, address to, uint256 amount)
EIP20 Transfer event
Approval
event Approval(address owner, address spender, uint256 amount)
EIP20 Approval event
transfer
function transfer(address dst, uint256 amount) external virtual returns (bool)
Failure event
transferFrom
function transferFrom(address src, address dst, uint256 amount) external virtual returns (bool)
approve
function approve(address spender, uint256 amount) external virtual returns (bool)
allowance
function allowance(address owner, address spender) external view virtual returns (uint256)
balanceOf
function balanceOf(address owner) external view virtual returns (uint256)
balanceOfUnderlying
function balanceOfUnderlying(address owner) external virtual returns (uint256)
getAccountSnapshot
function getAccountSnapshot(address account) external view virtual returns (uint256, uint256, uint256, uint256)
borrowRatePerBlock
function borrowRatePerBlock() external view virtual returns (uint256)
supplyRatePerBlock
function supplyRatePerBlock() external view virtual returns (uint256)
totalBorrowsCurrent
function totalBorrowsCurrent() external virtual returns (uint256)
borrowBalanceCurrent
function borrowBalanceCurrent(address account) external virtual returns (uint256)
borrowBalanceStored
function borrowBalanceStored(address account) public view virtual returns (uint256)
exchangeRateCurrent
function exchangeRateCurrent() public virtual returns (uint256)
exchangeRateStored
function exchangeRateStored() public view virtual returns (uint256)
getCash
function getCash() external view virtual returns (uint256)
accrueInterest
function accrueInterest() public virtual returns (uint256)
_setPendingAdmin
function _setPendingAdmin(address payable newPendingAdmin) external virtual returns (uint256)
_acceptAdmin
function _acceptAdmin() external virtual returns (uint256)
_setBondtroller
function _setBondtroller(contract Bondtroller newBondtroller) public virtual returns (uint256)
_setReserveFactor
function _setReserveFactor(uint256 newReserveFactorMantissa) external virtual returns (uint256)
_reduceReserves
function _reduceReserves(uint256 reduceAmount) external virtual returns (uint256)
_setInterestRateModel
function _setInterestRateModel(contract InterestRateModel newInterestRateModel) public virtual returns (uint256)
BErc20Storage
underlying
address underlying
Underlying asset for this CToken
BErc20Interface
sweepToken
function sweepToken(contract EIP20NonStandardInterface token) external virtual
_addReserves
function _addReserves(uint256 addAmount) external virtual returns (uint256)
Bondtroller
MarketListed
event MarketListed(contract BToken bToken)
Emitted when an admin supports a market
MarketEntered
event MarketEntered(contract BToken bToken, address account)
Emitted when an account enters a market
MarketExited
event MarketExited(contract BToken bToken, address account)
Emitted when an account exits a market
NewPriceOracle
event NewPriceOracle(address oldPriceOracle, address newPriceOracle)
Emitted when price oracle is changed
NewPauseGuardian
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian)
Emitted when pause guardian is changed
ActionPaused
event ActionPaused(string action, bool pauseState)
Emitted when an action is paused globally
ActionPaused
event ActionPaused(contract BToken bToken, string action, bool pauseState)
Emitted when an action is paused on a market
NewBorrowCap
event NewBorrowCap(contract BToken bToken, uint256 newBorrowCap)
Emitted when borrow cap for a bToken is changed
NewBorrowCapGuardian
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian)
Emitted when borrow cap guardian is changed
CompGranted
event CompGranted(address recipient, uint256 amount)
Emitted when COMP is granted by admin
NewPrimaryIndexToken
event NewPrimaryIndexToken(address oldPrimaryIndexToken, address newPrimaryIndexToken)
primaryIndexToken
address primaryIndexToken
the address of primary index token
init
function init() public
onlyPrimaryIndexToken
modifier onlyPrimaryIndexToken()
getPrimaryIndexTokenAddress
function getPrimaryIndexTokenAddress() external view returns (address)
getAssetsIn
function getAssetsIn(address account) external view returns (contract BToken[])
Returns the assets an account has entered
account
address
The address of the account to pull assets for
[0]
contract BToken[]
A dynamic list with the assets the account has entered
checkMembership
function checkMembership(address account, contract BToken bToken) external view returns (bool)
Returns whether the given account is entered in the given asset
account
address
The address of the account to check
bToken
contract BToken
The bToken to check
[0]
bool
True if the account is in the asset, otherwise false.
enterMarkets
function enterMarkets(address[] bTokens) public returns (uint256[])
Add assets to be included in account liquidity calculation
bTokens
address[]
The list of addresses of the bToken markets to be enabled
[0]
uint256[]
Success indicator for whether each corresponding market was entered
enterMarket
function enterMarket(address bToken, address borrower) public returns (enum BondtrollerErrorReporter.Error)
Add asset to be included in account liquidity calculation
bToken
address
The address of the bToken markets to be enabled
borrower
address
The address of user, which enters to market
addToMarketInternal
function addToMarketInternal(contract BToken bToken, address borrower) internal returns (enum BondtrollerErrorReporter.Error)
Add the market to the borrower's "assets in" for liquidity calculations
bToken
contract BToken
The market to enter
borrower
address
The address of the account to modify
[0]
enum BondtrollerErrorReporter.Error
Success indicator for whether the market was entered
exitMarket
function exitMarket(address cTokenAddress) external returns (uint256)
Removes asset from sender's account liquidity calculation
Sender must not have an outstanding borrow balance in the asset, or be providing necessary collateral for an outstanding borrow.
cTokenAddress
address
The address of the asset to be removed
[0]
uint256
Whether or not the account successfully exited the market
mintAllowed
function mintAllowed(address bToken, address minter, uint256 mintAmount) external view returns (uint256)
Checks if the account should be allowed to mint tokens in the given market
bToken
address
The market to verify the mint against
minter
address
The account which would get the minted tokens
mintAmount
uint256
The amount of underlying being supplied to the market in exchange for tokens
[0]
uint256
0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / f
mintVerify
function mintVerify(address bToken, address minter, uint256 actualMintAmount, uint256 mintTokens) external
Validates mint and reverts on rejection. May emit logs.
bToken
address
Asset being minted
minter
address
The address minting the tokens
actualMintAmount
uint256
The amount of the underlying asset being minted
mintTokens
uint256
The number of tokens being minted / f
redeemAllowed
function redeemAllowed(address bToken, address redeemer, uint256 redeemTokens) external view returns (uint256)
Checks if the account should be allowed to redeem tokens in the given market
bToken
address
The market to verify the redeem against
redeemer
address
The account which would redeem the tokens
redeemTokens
uint256
The number of bTokens to exchange for the underlying asset in the market
[0]
uint256
0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / f
redeemAllowedInternal
function redeemAllowedInternal(address bToken, address redeemer, uint256 redeemTokens) internal view returns (uint256)
redeemVerify
function redeemVerify(address bToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens) external pure
Validates redeem and reverts on rejection. May emit logs.
bToken
address
Asset being redeemed
redeemer
address
The address redeeming the tokens
redeemAmount
uint256
The amount of the underlying asset being redeemed
redeemTokens
uint256
The number of tokens being redeemed / f
borrowAllowed
function borrowAllowed(address bToken, address borrower, uint256 borrowAmount) external returns (uint256)
Checks if the account should be allowed to borrow the underlying asset of the given market
bToken
address
The market to verify the borrow against
borrower
address
The account which would borrow the asset
borrowAmount
uint256
The amount of underlying the account would borrow
[0]
uint256
0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / f
borrowVerify
function borrowVerify(address bToken, address borrower, uint256 borrowAmount) external
Validates borrow and reverts on rejection. May emit logs.
bToken
address
Asset whose underlying is being borrowed
borrower
address
The address borrowing the underlying
borrowAmount
uint256
The amount of the underlying asset requested to borrow / f
repayBorrowAllowed
function repayBorrowAllowed(address bToken, address payer, address borrower, uint256 repayAmount) external view returns (uint256)
Checks if the account should be allowed to repay a borrow in the given market
bToken
address
The market to verify the repay against
payer
address
The account which would repay the asset
borrower
address
The account which would borrowed the asset
repayAmount
uint256
The amount of the underlying asset the account would repay
[0]
uint256
0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / f
repayBorrowVerify
function repayBorrowVerify(address bToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex) external
Validates repayBorrow and reverts on rejection. May emit logs.
bToken
address
Asset being repaid
payer
address
The address repaying the borrow
borrower
address
The address of the borrower
actualRepayAmount
uint256
The amount of underlying being repaid / f
borrowerIndex
uint256
transferAllowed
function transferAllowed(address bToken, address src, address dst, uint256 transferTokens) external returns (uint256)
Checks if the account should be allowed to transfer tokens in the given market
bToken
address
The market to verify the transfer against
src
address
The account which sources the tokens
dst
address
The account which receives the tokens
transferTokens
uint256
The number of bTokens to transfer
[0]
uint256
0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / f
transferVerify
function transferVerify(address bToken, address src, address dst, uint256 transferTokens) external
Validates transfer and reverts on rejection. May emit logs.
bToken
address
Asset being transferred
src
address
The account which sources the tokens
dst
address
The account which receives the tokens
transferTokens
uint256
The number of bTokens to transfer / f
setPriceOracle
function setPriceOracle(address newOracle) public returns (uint256)
Sets a new price oracle for the bondtroller
Admin function to set a new price oracle
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / f
setPrimaryIndexTokenAddress
function setPrimaryIndexTokenAddress(address _newPrimaryIndexToken) external returns (uint256)
supportMarket
function supportMarket(contract BToken bToken) external returns (uint256)
Add the market to the markets mapping and set it as listed
Admin function to set isListed and add support for the market
bToken
contract BToken
The address of the market (token) to list
[0]
uint256
uint 0=success, otherwise a failure. (See enum Error for details) / f
_addMarketInternal
function _addMarketInternal(address bToken) internal
setMarketBorrowCaps
function setMarketBorrowCaps(contract BToken[] bTokens, uint256[] newBorrowCaps) external
Set the given borrow caps for the given bToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
bTokens
contract BToken[]
The addresses of the markets (tokens) to change the borrow caps for
newBorrowCaps
uint256[]
The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. / f
setBorrowCapGuardian
function setBorrowCapGuardian(address newBorrowCapGuardian) external
Admin function to change the Borrow Cap Guardian
newBorrowCapGuardian
address
The address of the new Borrow Cap Guardian / f
setPauseGuardian
function setPauseGuardian(address newPauseGuardian) public returns (uint256)
Admin function to change the Pause Guardian
newPauseGuardian
address
The address of the new Pause Guardian
[0]
uint256
uint 0=success, otherwise a failure. (See enum Error for details) / f
setMintPaused
function setMintPaused(contract BToken bToken, bool state) public returns (bool)
setBorrowPaused
function setBorrowPaused(contract BToken bToken, bool state) public returns (bool)
setTransferPaused
function setTransferPaused(bool state) public returns (bool)
setSeizePaused
function setSeizePaused(bool state) public returns (bool)
adminOrInitializing
function adminOrInitializing() internal view returns (bool)
Checks caller is admin, or this contract is becoming the new implementation / f
getAllMarkets
function getAllMarkets() public view returns (contract BToken[])
Return all of the markets
The automatic getter may be used to access an individual market.
[0]
contract BToken[]
The list of market addresses / f
isDeprecated
function isDeprecated(contract BToken bToken) public view returns (bool)
Returns true if the given bToken market has been deprecated
All borrows in a deprecated bToken market can be immediately liquidated
bToken
contract BToken
The market to check if deprecated / f
getBlockNumber
function getBlockNumber() public view returns (uint256)
BondtrollerV1Storage
isBondtroller
bool isBondtroller
watermark that says that this is Bondtroller
admin
address admin
Administrator for this contract
oracle
address oracle
Oracle which gives the price of any given asset
closeFactorMantissa
uint256 closeFactorMantissa
Multiplier used to calculate the maximum repayAmount when liquidating a borrow
liquidationIncentiveMantissa
uint256 liquidationIncentiveMantissa
Multiplier representing the discount on collateral that a liquidator receives
maxAssets
uint256 maxAssets
Max number of assets a single account can participate in (borrow or use as collateral)
accountAssets
mapping(address => contract BToken[]) accountAssets
Per-account mapping of "assets you are in", capped by maxAssets
BondtrollerV2Storage
Market
struct Market {
bool isListed;
uint256 collateralFactorMantissa;
bool isComped;
}
accountMembership
mapping(address => mapping(address => bool)) accountMembership
Per-market mapping of "accounts in this asset"
markets
mapping(address => struct BondtrollerV2Storage.Market) markets
Official mapping of BTokens -> Market metadata
Used e.g. to determine if a market is supported
pauseGuardian
address pauseGuardian
The Pause Guardian can pause certain actions as a safety mechanism. Actions which allow users to remove their own assets cannot be paused. Liquidation / seizing / transfer can only be paused globally, not by market.
_mintGuardianPaused
bool _mintGuardianPaused
_borrowGuardianPaused
bool _borrowGuardianPaused
transferGuardianPaused
bool transferGuardianPaused
seizeGuardianPaused
bool seizeGuardianPaused
mintGuardianPaused
mapping(address => bool) mintGuardianPaused
borrowGuardianPaused
mapping(address => bool) borrowGuardianPaused
BondtrollerV3Storage
CompMarketState
struct CompMarketState {
uint224 index;
uint32 block;
}
allMarkets
contract BToken[] allMarkets
A list of all markets
compRate
uint256 compRate
The rate at which the flywheel distributes COMP, per block
compSpeeds
mapping(address => uint256) compSpeeds
The portion of compRate that each market currently receives
compSupplyState
mapping(address => struct BondtrollerV3Storage.CompMarketState) compSupplyState
The COMP market supply state for each market
compBorrowState
mapping(address => struct BondtrollerV3Storage.CompMarketState) compBorrowState
The COMP market borrow state for each market
compSupplierIndex
mapping(address => mapping(address => uint256)) compSupplierIndex
The COMP borrow index for each market for each supplier as of the last time they accrued COMP
compBorrowerIndex
mapping(address => mapping(address => uint256)) compBorrowerIndex
The COMP borrow index for each market for each borrower as of the last time they accrued COMP
compAccrued
mapping(address => uint256) compAccrued
The COMP accrued but not yet transferred to each user
BondtrollerV4Storage
borrowCapGuardian
address borrowCapGuardian
borrowCaps
mapping(address => uint256) borrowCaps
BondtrollerV5Storage
compContributorSpeeds
mapping(address => uint256) compContributorSpeeds
The portion of COMP that each contributor receives per block
lastContributorBlock
mapping(address => uint256) lastContributorBlock
Last block at which a contributor's COMP rewards have been allocated
BaseJumpRateModelV2
Version 2 modifies Version 1 by enabling updateable parameters.
NewInterestParams
event NewInterestParams(uint256 baseRatePerBlock, uint256 multiplierPerBlock, uint256 jumpMultiplierPerBlock, uint256 kink)
owner
address owner
The address of the owner, i.e. the Timelock contract, which can update parameters directly
blocksPerYear
uint256 blocksPerYear
The approximate number of blocks per year that is assumed by the interest rate model
multiplierPerBlock
uint256 multiplierPerBlock
The multiplier of utilization rate that gives the slope of the interest rate
baseRatePerBlock
uint256 baseRatePerBlock
The base interest rate which is the y-intercept when utilization rate is 0
jumpMultiplierPerBlock
uint256 jumpMultiplierPerBlock
The multiplierPerBlock after hitting a specified utilization point
kink
uint256 kink
The utilization point at which the jump multiplier is applied
constructor
constructor(uint256 baseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_, address owner_) public
Construct an interest rate model
baseRatePerYear
uint256
The approximate target base APR, as a mantissa (scaled by 1e18)
multiplierPerYear
uint256
The rate of increase in interest rate wrt utilization (scaled by 1e18)
jumpMultiplierPerYear
uint256
The multiplierPerBlock after hitting a specified utilization point
kink_
uint256
The utilization point at which the jump multiplier is applied
owner_
address
The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)
updateJumpRateModel
function updateJumpRateModel(uint256 baseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_) external
Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)
baseRatePerYear
uint256
The approximate target base APR, as a mantissa (scaled by 1e18)
multiplierPerYear
uint256
The rate of increase in interest rate wrt utilization (scaled by 1e18)
jumpMultiplierPerYear
uint256
The multiplierPerBlock after hitting a specified utilization point
kink_
uint256
The utilization point at which the jump multiplier is applied
utilizationRate
function utilizationRate(uint256 cash, uint256 borrows, uint256 reserves) public pure returns (uint256)
Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`
cash
uint256
The amount of cash in the market
borrows
uint256
The amount of borrows in the market
reserves
uint256
The amount of reserves in the market (currently unused)
[0]
uint256
The utilization rate as a mantissa between [0, 1e18]
getBorrowRateInternal
function getBorrowRateInternal(uint256 cash, uint256 borrows, uint256 reserves) internal view returns (uint256)
Calculates the current borrow rate per block, with the error code expected by the market
cash
uint256
The amount of cash in the market
borrows
uint256
The amount of borrows in the market
reserves
uint256
The amount of reserves in the market
[0]
uint256
The borrow rate percentage per block as a mantissa (scaled by 1e18)
getSupplyRate
function getSupplyRate(uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa) public view virtual returns (uint256)
Calculates the current supply rate per block
cash
uint256
The amount of cash in the market
borrows
uint256
The amount of borrows in the market
reserves
uint256
The amount of reserves in the market
reserveFactorMantissa
uint256
The current reserve factor for the market
[0]
uint256
The supply rate percentage per block as a mantissa (scaled by 1e18)
updateJumpRateModelInternal
function updateJumpRateModelInternal(uint256 baseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_) internal
Internal function to update the parameters of the interest rate model
baseRatePerYear
uint256
The approximate target base APR, as a mantissa (scaled by 1e18)
multiplierPerYear
uint256
The rate of increase in interest rate wrt utilization (scaled by 1e18)
jumpMultiplierPerYear
uint256
The multiplierPerBlock after hitting a specified utilization point
kink_
uint256
The utilization point at which the jump multiplier is applied
FringeInterestRateModel
MODERATOR_ROLE
bytes32 MODERATOR_ROLE
borrowRate
uint256 borrowRate
supplyRate
uint256 supplyRate
initialize
function initialize() public
onlyAdmin
modifier onlyAdmin()
onlyModerator
modifier onlyModerator()
grandModerator
function grandModerator(address newModerator) public
revokeModerator
function revokeModerator(address moderator) public
setBorrowRate
function setBorrowRate(uint256 newBorrowRate) public
setSupplyRate
function setSupplyRate(uint256 newSupplyRate) public
getBorrowRate
function getBorrowRate(uint256 cash, uint256 borrows, uint256 reserves) external view returns (uint256)
Calculates the current borrow rate per block
cash
uint256
The amount of cash in the market
borrows
uint256
The amount of borrows in the market
reserves
uint256
The amount of reserves in the market
[0]
uint256
The borrow rate percentage per block as a mantissa (scaled by 1e18)
getSupplyRate
function getSupplyRate(uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa) public view returns (uint256)
Calculates the current supply interest rate per block
cash
uint256
The total amount of cash the market has
borrows
uint256
The total amount of borrows the market has outstanding
reserves
uint256
The total amount of reserves the market has
reserveFactorMantissa
uint256
The current reserve factor the market has
[0]
uint256
The supply rate per block (as a percentage, and scaled by 1e18)
InterestRateModel
isInterestRateModel
bool isInterestRateModel
Indicator that this is an InterestRateModel contract (for inspection)
getBorrowRate
function getBorrowRate(uint256 cash, uint256 borrows, uint256 reserves) external view virtual returns (uint256)
Calculates the current borrow interest rate per block
cash
uint256
The total amount of cash the market has
borrows
uint256
The total amount of borrows the market has outstanding
reserves
uint256
The total amount of reserves the market has
[0]
uint256
The borrow rate per block (as a percentage, and scaled by 1e18)
getSupplyRate
function getSupplyRate(uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa) external view virtual returns (uint256)
Calculates the current supply interest rate per block
cash
uint256
The total amount of cash the market has
borrows
uint256
The total amount of borrows the market has outstanding
reserves
uint256
The total amount of reserves the market has
reserveFactorMantissa
uint256
The current reserve factor the market has
[0]
uint256
The supply rate per block (as a percentage, and scaled by 1e18)
JumpRateModelV2
Supports only for V2 cTokens
getBorrowRate
function getBorrowRate(uint256 cash, uint256 borrows, uint256 reserves) external view returns (uint256)
Calculates the current borrow rate per block
cash
uint256
The amount of cash in the market
borrows
uint256
The amount of borrows in the market
reserves
uint256
The amount of reserves in the market
[0]
uint256
The borrow rate percentage per block as a mantissa (scaled by 1e18)
getSupplyRate
function getSupplyRate(uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa) public view returns (uint256)
constructor
constructor(uint256 baseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_, address owner_) public
EIP20Interface
name
function name() external view returns (string)
symbol
function symbol() external view returns (string)
decimals
function decimals() external view returns (uint8)
totalSupply
function totalSupply() external view returns (uint256)
Get the total number of tokens in circulation
[0]
uint256
The supply of tokens
balanceOf
function balanceOf(address owner) external view returns (uint256 balance)
Gets the balance of the specified address
owner
address
The address from which the balance will be retrieved return The `balance`
transfer
function transfer(address dst, uint256 amount) external returns (bool success)
Transfer `amount` tokens from `msg.sender` to `dst`
dst
address
The address of the destination account
amount
uint256
The number of tokens to transfer return Whether or not the transfer succeeded
transferFrom
function transferFrom(address src, address dst, uint256 amount) external returns (bool success)
Transfer `amount` tokens from `src` to `dst`
src
address
The address of the source account
dst
address
The address of the destination account
amount
uint256
The number of tokens to transfer return Whether or not the transfer succeeded
approve
function approve(address spender, uint256 amount) external returns (bool success)
Approve `spender` to transfer up to `amount` from `src`
This will overwrite the approval amount for `spender` and is subject to issues noted here
spender
address
The address of the account which may transfer tokens
amount
uint256
The number of tokens that are approved (-1 means infinite) return Whether or not the approval succeeded
allowance
function allowance(address owner, address spender) external view returns (uint256 remaining)
Get the current allowance from `owner` for `spender`
owner
address
The address of the account which owns the tokens to be spent
spender
address
The address of the account which may transfer tokens return The number of tokens allowed to be spent (-1 means infinite)
Transfer
event Transfer(address from, address to, uint256 amount)
Approval
event Approval(address owner, address spender, uint256 amount)
EIP20NonStandardInterface
Version of ERC20 with no return values for `transfer` and `transferFrom` See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
totalSupply
function totalSupply() external view returns (uint256)
Get the total number of tokens in circulation
[0]
uint256
The supply of tokens
balanceOf
function balanceOf(address owner) external view returns (uint256 balance)
Gets the balance of the specified address
owner
address
The address from which the balance will be retrieved
transfer
function transfer(address dst, uint256 amount) external
Transfer `amount` tokens from `msg.sender` to `dst`
dst
address
The address of the destination account
amount
uint256
The number of tokens to transfer
transferFrom
function transferFrom(address src, address dst, uint256 amount) external
Transfer `amount` tokens from `src` to `dst`
src
address
The address of the source account
dst
address
The address of the destination account
amount
uint256
The number of tokens to transfer
approve
function approve(address spender, uint256 amount) external returns (bool success)
Approve `spender` to transfer up to `amount` from `src`
This will overwrite the approval amount for `spender` and is subject to issues noted here
spender
address
The address of the account which may transfer tokens
amount
uint256
The number of tokens that are approved return Whether or not the approval succeeded
allowance
function allowance(address owner, address spender) external view returns (uint256 remaining)
Get the current allowance from `owner` for `spender`
owner
address
The address of the account which owns the tokens to be spent
spender
address
The address of the account which may transfer tokens return The number of tokens allowed to be spent
Transfer
event Transfer(address from, address to, uint256 amount)
Approval
event Approval(address owner, address spender, uint256 amount)
IPriceProviderAggregator
MODERATOR_ROLE
function MODERATOR_ROLE() external view returns (bytes32)
usdDecimals
function usdDecimals() external view returns (uint8)
tokenPriceProvider
function tokenPriceProvider(address projectToken) external view returns (address priceProvider, bool hasSignedFunction)
GrandModeratorRole
event GrandModeratorRole(address who, address newModerator)
RevokeModeratorRole
event RevokeModeratorRole(address who, address moderator)
SetTokenAndPriceProvider
event SetTokenAndPriceProvider(address who, address token, address priceProvider)
ChangeActive
event ChangeActive(address who, address priceProvider, address token, bool active)
initialize
function initialize() external
grandModerator
function grandModerator(address newModerator) external
revokeModerator
function revokeModerator(address moderator) external
setTokenAndPriceProvider
function setTokenAndPriceProvider(address token, address priceProvider, bool hasFunctionWithSign) external
changeActive
function changeActive(address priceProvider, address token, bool active) external
getPrice
function getPrice(address token) external view returns (uint256 priceMantissa, uint8 priceDecimals)
price = priceMantissa / (10 ** priceDecimals)
returns tuple (priceMantissa, priceDecimals)
token
address
the address of token wich price is to return
getPriceSigned
function getPriceSigned(address token, uint256 _priceMantissa, uint8 _priceDecimals, uint256 validTo, bytes signature) external view returns (uint256 priceMantissa, uint8 priceDecimals)
returns the price of token multiplied by 10 ** priceDecimals given by price provider. price can be calculated as priceMantissa / (10 ** priceDecimals) i.e. price = priceMantissa / (10 ** priceDecimals)
token
address
the address of token
_priceMantissa
uint256
- the price of token (used in verifying the signature)
_priceDecimals
uint8
- the price decimals (used in verifying the signature)
validTo
uint256
- the timestamp in seconds (used in verifying the signature)
signature
bytes
- the backend signature of secp256k1. length is 65 bytes
getEvaluation
function getEvaluation(address token, uint256 tokenAmount) external view returns (uint256 evaluation)
returns the USD evaluation of token by its `tokenAmount`
token
address
the address of token to evaluate
tokenAmount
uint256
the amount of token to evaluate
getEvaluationSigned
function getEvaluationSigned(address token, uint256 tokenAmount, uint256 priceMantissa, uint8 priceDecimals, uint256 validTo, bytes signature) external view returns (uint256 evaluation)
returns the USD evaluation of token by its `tokenAmount`
token
address
the address of token
tokenAmount
uint256
the amount of token including decimals
priceMantissa
uint256
- the price of token (used in verifying the signature)
priceDecimals
uint8
- the price decimals (used in verifying the signature)
validTo
uint256
- the timestamp in seconds (used in verifying the signature)
signature
bytes
- the backend signature of secp256k1. length is 65 bytes
PRJ
init
function init(string name, string symbol) public
mint
function mint(uint256 amount) public
mintTo
function mintTo(address to, uint256 amount) public
AccessControlEnumerableUpgradeable
Extension of {AccessControl} that allows enumerating the members of each role.
__AccessControlEnumerable_init
function __AccessControlEnumerable_init() internal
__AccessControlEnumerable_init_unchained
function __AccessControlEnumerable_init_unchained() internal
_roleMembers
mapping(bytes32 => struct EnumerableSetUpgradeable.AddressSet) _roleMembers
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
getRoleMember
function getRoleMember(bytes32 role, uint256 index) public view returns (address)
_Returns one of the accounts that have `role`. `index` must be a value between 0 and {getRoleMemberCount}, non-inclusive.
Role bearers are not sorted in any particular way, and their ordering may change at any point.
WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure you perform all queries on the same block. See the following https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] for more information._
getRoleMemberCount
function getRoleMemberCount(bytes32 role) public view returns (uint256)
Returns the number of accounts that have `role`. Can be used together with {getRoleMember} to enumerate all bearers of a role.
grantRole
function grantRole(bytes32 role, address account) public virtual
Overload {grantRole} to track enumerable memberships
revokeRole
function revokeRole(bytes32 role, address account) public virtual
Overload {revokeRole} to track enumerable memberships
renounceRole
function renounceRole(bytes32 role, address account) public virtual
Overload {renounceRole} to track enumerable memberships
_setupRole
function _setupRole(bytes32 role, address account) internal virtual
_Overload {setupRole} to track enumerable memberships
__gap
uint256[49] __gap
AccessControlUpgradeable
_Contract module that allows children to implement role-based access control mechanisms. This is a lightweight version that doesn't allow enumerating role members except through off-chain means by accessing the contract event logs. Some applications may benefit from on-chain enumerability, for those cases see {AccessControlEnumerable}.
Roles are referred to by their `bytes32` identifier. These should be exposed in the external API and be unique. The best way to achieve this is by using `public constant` hash digests:
``` bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); ```
Roles can be used to represent a set of permissions. To restrict access to a function call, use {hasRole}:
``` function foo() public { require(hasRole(MY_ROLE, msg.sender)); ... } ```
Roles can be granted and revoked dynamically via the {grantRole} and {revokeRole} functions. Each role has an associated admin role, and only accounts that have a role's admin role can call {grantRole} and {revokeRole}.
By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means that only accounts with this role will be able to grant or revoke other roles. More complex role relationships can be created by using {_setRoleAdmin}.
WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to grant and revoke this role. Extra precautions should be taken to secure accounts that have been granted it._
__AccessControl_init
function __AccessControl_init() internal
__AccessControl_init_unchained
function __AccessControl_init_unchained() internal
RoleData
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
_roles
mapping(bytes32 => struct AccessControlUpgradeable.RoleData) _roles
DEFAULT_ADMIN_ROLE
bytes32 DEFAULT_ADMIN_ROLE
onlyRole
modifier onlyRole(bytes32 role)
_Modifier that checks that an account has a specific role. Reverts with a standardized message including the required role.
The format of the revert reason is given by the following regular expression:
/^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
Available since v4.1._
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
hasRole
function hasRole(bytes32 role, address account) public view returns (bool)
Returns `true` if `account` has been granted `role`.
_checkRole
function _checkRole(bytes32 role, address account) internal view
_Revert with a standard message if `account` is missing `role`.
The format of the revert reason is given by the following regular expression:
/^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/_
getRoleAdmin
function getRoleAdmin(bytes32 role) public view returns (bytes32)
_Returns the admin role that controls `role`. See {grantRole} and {revokeRole}.
To change a role's admin, use {setRoleAdmin}.
grantRole
function grantRole(bytes32 role, address account) public virtual
_Grants `role` to `account`.
If `account` had not been already granted `role`, emits a {RoleGranted} event.
Requirements:
the caller must have ``role``'s admin role._
revokeRole
function revokeRole(bytes32 role, address account) public virtual
_Revokes `role` from `account`.
If `account` had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must have ``role``'s admin role._
renounceRole
function renounceRole(bytes32 role, address account) public virtual
_Revokes `role` from the calling account.
Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced).
If the calling account had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must be `account`._
_setupRole
function _setupRole(bytes32 role, address account) internal virtual
_Grants `role` to `account`.
If `account` had not been already granted `role`, emits a {RoleGranted} event. Note that unlike {grantRole}, this function doesn't perform any checks on the calling account.
[WARNING] ==== This function should only be called from the constructor when setting up the initial roles for the system.
Using this function in any other way is effectively circumventing the admin system imposed by {AccessControl}. ====_
_setRoleAdmin
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual
_Sets `adminRole` as ``role``'s admin role.
Emits a {RoleAdminChanged} event._
_grantRole
function _grantRole(bytes32 role, address account) private
_revokeRole
function _revokeRole(bytes32 role, address account) private
__gap
uint256[49] __gap
IAccessControlEnumerableUpgradeable
External interface of AccessControlEnumerable declared to support ERC165 detection.
getRoleMember
function getRoleMember(bytes32 role, uint256 index) external view returns (address)
_Returns one of the accounts that have `role`. `index` must be a value between 0 and {getRoleMemberCount}, non-inclusive.
Role bearers are not sorted in any particular way, and their ordering may change at any point.
WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure you perform all queries on the same block. See the following https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] for more information._
getRoleMemberCount
function getRoleMemberCount(bytes32 role) external view returns (uint256)
Returns the number of accounts that have `role`. Can be used together with {getRoleMember} to enumerate all bearers of a role.
IAccessControlUpgradeable
External interface of AccessControl declared to support ERC165 detection.
RoleAdminChanged
event RoleAdminChanged(bytes32 role, bytes32 previousAdminRole, bytes32 newAdminRole)
_Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
`DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite {RoleAdminChanged} not being emitted signaling this.
Available since v3.1._
RoleGranted
event RoleGranted(bytes32 role, address account, address sender)
_Emitted when `account` is granted `role`.
`sender` is the account that originated the contract call, an admin role bearer except when using {AccessControl-setupRole}.
RoleRevoked
event RoleRevoked(bytes32 role, address account, address sender)
_Emitted when `account` is revoked `role`.
`sender` is the account that originated the contract call:
if using `revokeRole`, it is the admin role bearer
if using `renounceRole`, it is the role bearer (i.e. `account`)_
hasRole
function hasRole(bytes32 role, address account) external view returns (bool)
Returns `true` if `account` has been granted `role`.
getRoleAdmin
function getRoleAdmin(bytes32 role) external view returns (bytes32)
_Returns the admin role that controls `role`. See {grantRole} and {revokeRole}.
To change a role's admin, use {AccessControl-setRoleAdmin}.
grantRole
function grantRole(bytes32 role, address account) external
_Grants `role` to `account`.
If `account` had not been already granted `role`, emits a {RoleGranted} event.
Requirements:
the caller must have ``role``'s admin role._
revokeRole
function revokeRole(bytes32 role, address account) external
_Revokes `role` from `account`.
If `account` had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must have ``role``'s admin role._
renounceRole
function renounceRole(bytes32 role, address account) external
_Revokes `role` from the calling account.
Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced).
If the calling account had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must be `account`._
OwnableUpgradeable
_Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions.
By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}.
This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner._
_owner
address _owner
OwnershipTransferred
event OwnershipTransferred(address previousOwner, address newOwner)
__Ownable_init
function __Ownable_init() internal
Initializes the contract setting the deployer as the initial owner.
__Ownable_init_unchained
function __Ownable_init_unchained() internal
owner
function owner() public view virtual returns (address)
Returns the address of the current owner.
onlyOwner
modifier onlyOwner()
Throws if called by any account other than the owner.
renounceOwnership
function renounceOwnership() public virtual
_Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner.
NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner._
transferOwnership
function transferOwnership(address newOwner) public virtual
Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.
_setOwner
function _setOwner(address newOwner) private
__gap
uint256[49] __gap
PaymentSplitterUpgradeable
_This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware that the Ether will be split in this way, since it is handled transparently by the contract.
The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim an amount proportional to the percentage of total shares they were assigned.
`PaymentSplitter` follows a pull payment model. This means that payments are not automatically forwarded to the accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} function._
PayeeAdded
event PayeeAdded(address account, uint256 shares)
PaymentReleased
event PaymentReleased(address to, uint256 amount)
PaymentReceived
event PaymentReceived(address from, uint256 amount)
_totalShares
uint256 _totalShares
_totalReleased
uint256 _totalReleased
_shares
mapping(address => uint256) _shares
_released
mapping(address => uint256) _released
_payees
address[] _payees
__PaymentSplitter_init
function __PaymentSplitter_init(address[] payees, uint256[] shares_) internal
_Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at the matching position in the `shares` array.
All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no duplicates in `payees`._
__PaymentSplitter_init_unchained
function __PaymentSplitter_init_unchained(address[] payees, uint256[] shares_) internal
receive
receive() external payable virtual
_The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the reliability of the events, and not the actual splitting of Ether.
To learn more about this see the Solidity documentation for https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback functions]._
totalShares
function totalShares() public view returns (uint256)
Getter for the total shares held by payees.
totalReleased
function totalReleased() public view returns (uint256)
Getter for the total amount of Ether already released.
shares
function shares(address account) public view returns (uint256)
Getter for the amount of shares held by an account.
released
function released(address account) public view returns (uint256)
Getter for the amount of Ether already released to a payee.
payee
function payee(uint256 index) public view returns (address)
Getter for the address of the payee number `index`.
release
function release(address payable account) public virtual
Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the total shares and their previous withdrawals.
_addPayee
function _addPayee(address account, uint256 shares_) private
Add a new payee to the contract.
account
address
The address of the payee to add.
shares_
uint256
The number of shares owned by the payee.
__gap
uint256[45] __gap
GovernorUpgradeable
_Core of the governance system, designed to be extended though various modules.
This contract is abstract and requires several function to be implemented in various modules:
A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
A voting module must implement {getVotes}
Additionanly, the {votingPeriod} must also be implemented
Available since v4.3._
BALLOT_TYPEHASH
bytes32 BALLOT_TYPEHASH
ProposalCore
struct ProposalCore {
struct TimersUpgradeable.BlockNumber voteStart;
struct TimersUpgradeable.BlockNumber voteEnd;
bool executed;
bool canceled;
}
_name
string _name
_proposals
mapping(uint256 => struct GovernorUpgradeable.ProposalCore) _proposals
onlyGovernance
modifier onlyGovernance()
_Restrict access to governor executing address. Some module might override the executor function to make sure this modifier is consistant with the execution model.
__Governor_init
function __Governor_init(string name_) internal
Sets the value for {name} and {version}
__Governor_init_unchained
function __Governor_init_unchained(string name_) internal
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
name
function name() public view virtual returns (string)
See {IGovernor-name}.
version
function version() public view virtual returns (string)
See {IGovernor-version}.
hashProposal
function hashProposal(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public pure virtual returns (uint256)
_See {IGovernor-hashProposal}.
The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in advance, before the proposal is submitted.
Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the same proposal (with same operation and same description) will have the same id if submitted on multiple governors accross multiple networks. This also means that in order to execute the same operation twice (on the same governor) the proposer will have to change the description in order to avoid proposal id conflicts._
state
function state(uint256 proposalId) public view virtual returns (enum IGovernorUpgradeable.ProposalState)
See {IGovernor-state}.
proposalSnapshot
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256)
See {IGovernor-proposalSnapshot}.
proposalDeadline
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256)
See {IGovernor-proposalDeadline}.
_quorumReached
function _quorumReached(uint256 proposalId) internal view virtual returns (bool)
Amount of votes already cast passes the threshold limit.
_voteSucceeded
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool)
Is the proposal successful or not.
_countVote
function _countVote(uint256 proposalId, address account, uint8 support, uint256 weight) internal virtual
_Register a vote with a given support and voting weight.
Note: Support is generic and can represent various things depending on the voting system used._
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernor-propose}.
execute
function execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public payable virtual returns (uint256)
See {IGovernor-execute}.
_execute
function _execute(uint256, address[] targets, uint256[] values, bytes[] calldatas, bytes32) internal virtual
Internal execution mechanism. Can be overriden to implement different execution mechanism
_cancel
function _cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual returns (uint256)
_Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as canceled to allow distinguishing it from executed proposals.
Emits a {IGovernor-ProposalCanceled} event._
castVote
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256)
See {IGovernor-castVote}.
castVoteWithReason
function castVoteWithReason(uint256 proposalId, uint8 support, string reason) public virtual returns (uint256)
See {IGovernor-castVoteWithReason}.
castVoteBySig
function castVoteBySig(uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public virtual returns (uint256)
See {IGovernor-castVoteBySig}.
_castVote
function _castVote(uint256 proposalId, address account, uint8 support, string reason) internal virtual returns (uint256)
_Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
Emits a {IGovernor-VoteCast} event._
_executor
function _executor() internal view virtual returns (address)
Address through which the governor executes action. Will be overloaded by module that execute actions through another contract such as a timelock.
__gap
uint256[48] __gap
IGovernorUpgradeable
_Interface of the {Governor} core.
Available since v4.3._
__IGovernor_init
function __IGovernor_init() internal
__IGovernor_init_unchained
function __IGovernor_init_unchained() internal
ProposalState
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
ProposalCreated
event ProposalCreated(uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description)
Emitted when a proposal is created.
ProposalCanceled
event ProposalCanceled(uint256 proposalId)
Emitted when a proposal is canceled.
ProposalExecuted
event ProposalExecuted(uint256 proposalId)
Emitted when a proposal is executed.
VoteCast
event VoteCast(address voter, uint256 proposalId, uint8 support, uint256 weight, string reason)
_Emitted when a vote is cast.
Note: `support` values should be seen as buckets. There interpretation depends on the voting module used._
name
function name() public view virtual returns (string)
module:core
Name of the governor instance (used in building the ERC712 domain separator).
version
function version() public view virtual returns (string)
module:core
Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
COUNTING_MODE
function COUNTING_MODE() public pure virtual returns (string)
module:voting
_A description of the possible `support` values for {castVote} and the way these votes are counted, meant to be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
There are 2 standard keys: `support` and `quorum`.
`support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
`quorum=bravo` means that only For votes are counted towards quorum.
`quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
NOTE: The string can be decoded by the standard https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] JavaScript class._
hashProposal
function hashProposal(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public pure virtual returns (uint256)
module:core
Hashing function used to (re)build the proposal id from the proposal details..
state
function state(uint256 proposalId) public view virtual returns (enum IGovernorUpgradeable.ProposalState)
module:core
Current state of a proposal, following Compound's convention
proposalSnapshot
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256)
module:core
block number used to retrieve user's votes and quorum.
proposalDeadline
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256)
module:core
timestamp at which votes close.
votingDelay
function votingDelay() public view virtual returns (uint256)
module:user-config
delay, in number of block, between the proposal is created and the vote starts. This can be increassed to leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
votingPeriod
function votingPeriod() public view virtual returns (uint256)
module:user-config
_delay, in number of blocks, between the vote start and vote ends.
Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting duration compared to the voting delay._
quorum
function quorum(uint256 blockNumber) public view virtual returns (uint256)
module:user-config
_Minimum number of cast voted required for a proposal to be successful.
Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes})._
getVotes
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256)
module:reputation
_Voting power of an `account` at a specific `blockNumber`.
Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or multiple), {ERC20Votes} tokens._
hasVoted
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool)
module:voting
Returns weither `account` has cast a vote on `proposalId`.
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256 proposalId)
_Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends {IGovernor-votingPeriod} blocks after the voting starts.
Emits a {ProposalCreated} event._
execute
function execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public payable virtual returns (uint256 proposalId)
_Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the deadline to be reached.
Emits a {ProposalExecuted} event.
Note: some module can modify the requirements for execution, for example by adding an additional timelock._
castVote
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance)
_Cast a vote
Emits a {VoteCast} event._
castVoteWithReason
function castVoteWithReason(uint256 proposalId, uint8 support, string reason) public virtual returns (uint256 balance)
_Cast a with a reason
Emits a {VoteCast} event._
castVoteBySig
function castVoteBySig(uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public virtual returns (uint256 balance)
_Cast a vote using the user cryptographic signature.
Emits a {VoteCast} event._
__gap
uint256[50] __gap
TimelockControllerUpgradeable
_Contract module which acts as a timelocked controller. When set as the owner of an `Ownable` smart contract, it enforces a timelock on all `onlyOwner` maintenance operations. This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied.
By default, this contract is self administered, meaning administration tasks have to go through the timelock process. The proposer (resp executor) role is in charge of proposing (resp executing) operations. A common use case is to position this {TimelockController} as the owner of a smart contract, with a multisig or a DAO as the sole proposer.
Available since v3.3._
TIMELOCK_ADMIN_ROLE
bytes32 TIMELOCK_ADMIN_ROLE
PROPOSER_ROLE
bytes32 PROPOSER_ROLE
EXECUTOR_ROLE
bytes32 EXECUTOR_ROLE
_DONE_TIMESTAMP
uint256 _DONE_TIMESTAMP
_timestamps
mapping(bytes32 => uint256) _timestamps
_minDelay
uint256 _minDelay
CallScheduled
event CallScheduled(bytes32 id, uint256 index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay)
Emitted when a call is scheduled as part of operation `id`.
CallExecuted
event CallExecuted(bytes32 id, uint256 index, address target, uint256 value, bytes data)
Emitted when a call is performed as part of operation `id`.
Cancelled
event Cancelled(bytes32 id)
Emitted when operation `id` is cancelled.
MinDelayChange
event MinDelayChange(uint256 oldDuration, uint256 newDuration)
Emitted when the minimum delay for future operations is modified.
__TimelockController_init
function __TimelockController_init(uint256 minDelay, address[] proposers, address[] executors) internal
Initializes the contract with a given `minDelay`.
__TimelockController_init_unchained
function __TimelockController_init_unchained(uint256 minDelay, address[] proposers, address[] executors) internal
onlyRoleOrOpenRole
modifier onlyRoleOrOpenRole(bytes32 role)
Modifier to make a function callable only by a certain role. In addition to checking the sender's role, `address(0)` 's role is also considered. Granting a role to `address(0)` is equivalent to enabling this role for everyone.
receive
receive() external payable
Contract might receive/hold ETH as part of the maintenance process.
isOperation
function isOperation(bytes32 id) public view virtual returns (bool pending)
Returns whether an id correspond to a registered operation. This includes both Pending, Ready and Done operations.
isOperationPending
function isOperationPending(bytes32 id) public view virtual returns (bool pending)
Returns whether an operation is pending or not.
isOperationReady
function isOperationReady(bytes32 id) public view virtual returns (bool ready)
Returns whether an operation is ready or not.
isOperationDone
function isOperationDone(bytes32 id) public view virtual returns (bool done)
Returns whether an operation is done or not.
getTimestamp
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp)
Returns the timestamp at with an operation becomes ready (0 for unset operations, 1 for done operations).
getMinDelay
function getMinDelay() public view virtual returns (uint256 duration)
_Returns the minimum delay for an operation to become valid.
This value can be changed by executing an operation that calls `updateDelay`._
hashOperation
function hashOperation(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash)
Returns the identifier of an operation containing a single transaction.
hashOperationBatch
function hashOperationBatch(address[] targets, uint256[] values, bytes[] datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash)
Returns the identifier of an operation containing a batch of transactions.
schedule
function schedule(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual
_Schedule an operation containing a single transaction.
Emits a {CallScheduled} event.
Requirements:
the caller must have the 'proposer' role._
scheduleBatch
function scheduleBatch(address[] targets, uint256[] values, bytes[] datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual
_Schedule an operation containing a batch of transactions.
Emits one {CallScheduled} event per transaction in the batch.
Requirements:
the caller must have the 'proposer' role._
_schedule
function _schedule(bytes32 id, uint256 delay) private
Schedule an operation that is to becomes valid after a given delay.
cancel
function cancel(bytes32 id) public virtual
_Cancel an operation.
Requirements:
the caller must have the 'proposer' role._
execute
function execute(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt) public payable virtual
_Execute an (ready) operation containing a single transaction.
Emits a {CallExecuted} event.
Requirements:
the caller must have the 'executor' role._
executeBatch
function executeBatch(address[] targets, uint256[] values, bytes[] datas, bytes32 predecessor, bytes32 salt) public payable virtual
_Execute an (ready) operation containing a batch of transactions.
Emits one {CallExecuted} event per transaction in the batch.
Requirements:
the caller must have the 'executor' role._
_beforeCall
function _beforeCall(bytes32 id, bytes32 predecessor) private view
Checks before execution of an operation's calls.
_afterCall
function _afterCall(bytes32 id) private
Checks after execution of an operation's calls.
_call
function _call(bytes32 id, uint256 index, address target, uint256 value, bytes data) private
_Execute an operation's call.
Emits a {CallExecuted} event._
updateDelay
function updateDelay(uint256 newDelay) external virtual
_Changes the minimum timelock duration for future operations.
Emits a {MinDelayChange} event.
Requirements:
the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function._
__gap
uint256[48] __gap
GovernorCompatibilityBravoUpgradeable
_Compatibility layer that implements GovernorBravo compatibility on to of {Governor}.
This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added through inheritance. It does not include token bindings, not does it include any variable upgrade patterns.
Available since v4.3._
__GovernorCompatibilityBravo_init
function __GovernorCompatibilityBravo_init() internal
__GovernorCompatibilityBravo_init_unchained
function __GovernorCompatibilityBravo_init_unchained() internal
VoteType
enum VoteType {
Against,
For,
Abstain
}
ProposalDetails
struct ProposalDetails {
address proposer;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
mapping(address => struct IGovernorCompatibilityBravoUpgradeable.Receipt) receipts;
bytes32 descriptionHash;
}
_proposalDetails
mapping(uint256 => struct GovernorCompatibilityBravoUpgradeable.ProposalDetails) _proposalDetails
COUNTING_MODE
function COUNTING_MODE() public pure virtual returns (string)
module:voting
_A description of the possible `support` values for {castVote} and the way these votes are counted, meant to be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
There are 2 standard keys: `support` and `quorum`.
`support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
`quorum=bravo` means that only For votes are counted towards quorum.
`quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
NOTE: The string can be decoded by the standard https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] JavaScript class._
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernor-propose}.
propose
function propose(address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernorCompatibilityBravo-propose}.
queue
function queue(uint256 proposalId) public virtual
See {IGovernorCompatibilityBravo-queue}.
execute
function execute(uint256 proposalId) public payable virtual
See {IGovernorCompatibilityBravo-execute}.
cancel
function cancel(uint256 proposalId) public virtual
Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
_encodeCalldata
function _encodeCalldata(string[] signatures, bytes[] calldatas) private pure returns (bytes[])
Encodes calldatas with optional function signature.
_storeProposal
function _storeProposal(address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, string description) private
Store proposal metadata for later lookup
proposalThreshold
function proposalThreshold() public view virtual returns (uint256)
Part of the Governor Bravo's interface: "The number of votes required in order for a voter to become a proposer".
proposals
function proposals(uint256 proposalId) public view virtual returns (uint256 id, address proposer, uint256 eta, uint256 startBlock, uint256 endBlock, uint256 forVotes, uint256 againstVotes, uint256 abstainVotes, bool canceled, bool executed)
See {IGovernorCompatibilityBravo-proposals}.
getActions
function getActions(uint256 proposalId) public view virtual returns (address[] targets, uint256[] values, string[] signatures, bytes[] calldatas)
See {IGovernorCompatibilityBravo-getActions}.
getReceipt
function getReceipt(uint256 proposalId, address voter) public view virtual returns (struct IGovernorCompatibilityBravoUpgradeable.Receipt)
See {IGovernorCompatibilityBravo-getReceipt}.
quorumVotes
function quorumVotes() public view virtual returns (uint256)
See {IGovernorCompatibilityBravo-quorumVotes}.
hasVoted
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool)
See {IGovernor-hasVoted}.
_quorumReached
function _quorumReached(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-quorumReached}. In this module, only forVotes count toward the quorum.
_voteSucceeded
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
_countVote
function _countVote(uint256 proposalId, address account, uint8 support, uint256 weight) internal virtual
_See {Governor-countVote}. In this module, the support follows Governor Bravo.
__gap
uint256[49] __gap
IGovernorCompatibilityBravoUpgradeable
_Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility.
Available since v4.3._
__IGovernorCompatibilityBravo_init
function __IGovernorCompatibilityBravo_init() internal
__IGovernorCompatibilityBravo_init_unchained
function __IGovernorCompatibilityBravo_init_unchained() internal
Proposal
struct Proposal {
uint256 id;
address proposer;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
bool canceled;
bool executed;
mapping(address => struct IGovernorCompatibilityBravoUpgradeable.Receipt) receipts;
}
Receipt
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
quorumVotes
function quorumVotes() public view virtual returns (uint256)
Part of the Governor Bravo's interface.
proposals
function proposals(uint256) public view virtual returns (uint256 id, address proposer, uint256 eta, uint256 startBlock, uint256 endBlock, uint256 forVotes, uint256 againstVotes, uint256 abstainVotes, bool canceled, bool executed)
Part of the Governor Bravo's interface: "The official record of all proposals ever proposed".
propose
function propose(address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, string description) public virtual returns (uint256)
Part of the Governor Bravo's interface: "Function used to propose a new proposal".
queue
function queue(uint256 proposalId) public virtual
Part of the Governor Bravo's interface: "Queues a proposal of state succeeded".
execute
function execute(uint256 proposalId) public payable virtual
Part of the Governor Bravo's interface: "Executes a queued proposal if eta has passed".
cancel
function cancel(uint256 proposalId) public virtual
Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
getActions
function getActions(uint256 proposalId) public view virtual returns (address[] targets, uint256[] values, string[] signatures, bytes[] calldatas)
Part of the Governor Bravo's interface: "Gets actions of a proposal".
getReceipt
function getReceipt(uint256 proposalId, address voter) public view virtual returns (struct IGovernorCompatibilityBravoUpgradeable.Receipt)
Part of the Governor Bravo's interface: "Gets the receipt for a voter on a given proposal".
proposalThreshold
function proposalThreshold() public view virtual returns (uint256)
Part of the Governor Bravo's interface: "The number of votes required in order for a voter to become a proposer".
__gap
uint256[50] __gap
GovernorCountingSimpleUpgradeable
_Extension of {Governor} for simple, 3 options, vote counting.
Available since v4.3._
__GovernorCountingSimple_init
function __GovernorCountingSimple_init() internal
__GovernorCountingSimple_init_unchained
function __GovernorCountingSimple_init_unchained() internal
VoteType
enum VoteType {
Against,
For,
Abstain
}
ProposalVote
struct ProposalVote {
uint256 againstVotes;
uint256 forVotes;
uint256 abstainVotes;
mapping(address => bool) hasVoted;
}
_proposalVotes
mapping(uint256 => struct GovernorCountingSimpleUpgradeable.ProposalVote) _proposalVotes
COUNTING_MODE
function COUNTING_MODE() public pure virtual returns (string)
See {IGovernor-COUNTING_MODE}.
hasVoted
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool)
See {IGovernor-hasVoted}.
proposalVotes
function proposalVotes(uint256 proposalId) public view virtual returns (uint256 againstVotes, uint256 forVotes, uint256 abstainVotes)
Accessor to the internal vote counts.
_quorumReached
function _quorumReached(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-quorumReached}.
_voteSucceeded
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
_countVote
function _countVote(uint256 proposalId, address account, uint8 support, uint256 weight) internal virtual
_See {Governor-countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
__gap
uint256[49] __gap
GovernorProposalThresholdUpgradeable
_Extension of {Governor} for proposal restriction to token holders with a minimum balance.
Available since v4.3._
__GovernorProposalThreshold_init
function __GovernorProposalThreshold_init() internal
__GovernorProposalThreshold_init_unchained
function __GovernorProposalThreshold_init_unchained() internal
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernor-propose}.
proposalThreshold
function proposalThreshold() public view virtual returns (uint256)
Part of the Governor Bravo's interface: "The number of votes required in order for a voter to become a proposer".
__gap
uint256[50] __gap
ICompoundTimelockUpgradeable
https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[Compound's timelock] interface
receive
receive() external payable
GRACE_PERIOD
function GRACE_PERIOD() external view returns (uint256)
MINIMUM_DELAY
function MINIMUM_DELAY() external view returns (uint256)
MAXIMUM_DELAY
function MAXIMUM_DELAY() external view returns (uint256)
admin
function admin() external view returns (address)
pendingAdmin
function pendingAdmin() external view returns (address)
delay
function delay() external view returns (uint256)
queuedTransactions
function queuedTransactions(bytes32) external view returns (bool)
setDelay
function setDelay(uint256) external
acceptAdmin
function acceptAdmin() external
setPendingAdmin
function setPendingAdmin(address) external
queueTransaction
function queueTransaction(address target, uint256 value, string signature, bytes data, uint256 eta) external returns (bytes32)
cancelTransaction
function cancelTransaction(address target, uint256 value, string signature, bytes data, uint256 eta) external
executeTransaction
function executeTransaction(address target, uint256 value, string signature, bytes data, uint256 eta) external payable returns (bytes)
GovernorTimelockCompoundUpgradeable
_Extension of {Governor} that binds the execution process to a Compound Timelock. This adds a delay, enforced by the external timelock to all successful proposal (in addition to the voting duration). The {Governor} needs to be the admin of the timelock for any operation to be performed. A public, unrestricted, {GovernorTimelockCompound-__acceptAdmin} is available to accept ownership of the timelock.
Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be inaccessible.
Available since v4.3._
ProposalTimelock
struct ProposalTimelock {
struct TimersUpgradeable.Timestamp timer;
}
_timelock
contract ICompoundTimelockUpgradeable _timelock
_proposalTimelocks
mapping(uint256 => struct GovernorTimelockCompoundUpgradeable.ProposalTimelock) _proposalTimelocks
TimelockChange
event TimelockChange(address oldTimelock, address newTimelock)
Emitted when the timelock controller used for proposal execution is modified.
__GovernorTimelockCompound_init
function __GovernorTimelockCompound_init(contract ICompoundTimelockUpgradeable timelockAddress) internal
Set the timelock.
__GovernorTimelockCompound_init_unchained
function __GovernorTimelockCompound_init_unchained(contract ICompoundTimelockUpgradeable timelockAddress) internal
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
state
function state(uint256 proposalId) public view virtual returns (enum IGovernorUpgradeable.ProposalState)
Overriden version of the {Governor-state} function with added support for the `Queued` and `Expired` status.
timelock
function timelock() public view virtual returns (address)
Public accessor to check the address of the timelock
proposalEta
function proposalEta(uint256 proposalId) public view virtual returns (uint256)
Public accessor to check the eta of a queued proposal
queue
function queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public virtual returns (uint256)
Function to queue a proposal to the timelock.
_execute
function _execute(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32) internal virtual
Overriden execute function that run the already queued proposal through the timelock.
_cancel
function _cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual returns (uint256)
_Overriden version of the {Governor-cancel} function to cancel the timelocked proposal if it as already been queued.
_executor
function _executor() internal view virtual returns (address)
Address through which the governor executes action. In this case, the timelock.
__acceptAdmin
function __acceptAdmin() public
Accept admin right over the timelock.
updateTimelock
function updateTimelock(contract ICompoundTimelockUpgradeable newTimelock) external virtual
_Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates must be proposed, scheduled and executed using the {Governor} workflow.
For security reason, the timelock must be handed over to another admin before setting up a new one. The two operations (hand over the timelock) and do the update can be batched in a single proposal.
Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of governance._
_updateTimelock
function _updateTimelock(contract ICompoundTimelockUpgradeable newTimelock) private
__gap
uint256[48] __gap
GovernorTimelockControlUpgradeable
_Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The {Governor} needs the proposer (an ideally the executor) roles for the {Governor} to work properly.
Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be inaccessible.
Available since v4.3._
_timelock
contract TimelockControllerUpgradeable _timelock
_timelockIds
mapping(uint256 => bytes32) _timelockIds
TimelockChange
event TimelockChange(address oldTimelock, address newTimelock)
Emitted when the timelock controller used for proposal execution is modified.
__GovernorTimelockControl_init
function __GovernorTimelockControl_init(contract TimelockControllerUpgradeable timelockAddress) internal
Set the timelock.
__GovernorTimelockControl_init_unchained
function __GovernorTimelockControl_init_unchained(contract TimelockControllerUpgradeable timelockAddress) internal
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
state
function state(uint256 proposalId) public view virtual returns (enum IGovernorUpgradeable.ProposalState)
Overriden version of the {Governor-state} function with added support for the `Queued` status.
timelock
function timelock() public view virtual returns (address)
Public accessor to check the address of the timelock
proposalEta
function proposalEta(uint256 proposalId) public view virtual returns (uint256)
Public accessor to check the eta of a queued proposal
queue
function queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public virtual returns (uint256)
Function to queue a proposal to the timelock.
_execute
function _execute(uint256, address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual
Overriden execute function that run the already queued proposal through the timelock.
_cancel
function _cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual returns (uint256)
_Overriden version of the {Governor-cancel} function to cancel the timelocked proposal if it as already been queued.
_executor
function _executor() internal view virtual returns (address)
Address through which the governor executes action. In this case, the timelock.
updateTimelock
function updateTimelock(contract TimelockControllerUpgradeable newTimelock) external virtual
Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates must be proposed, scheduled and executed using the {Governor} workflow.
_updateTimelock
function _updateTimelock(contract TimelockControllerUpgradeable newTimelock) private
__gap
uint256[48] __gap
GovernorVotesCompUpgradeable
_Extension of {Governor} for voting weight extraction from a Comp token.
Available since v4.3._
token
contract ERC20VotesCompUpgradeable token
__GovernorVotesComp_init
function __GovernorVotesComp_init(contract ERC20VotesCompUpgradeable token_) internal
__GovernorVotesComp_init_unchained
function __GovernorVotesComp_init_unchained(contract ERC20VotesCompUpgradeable token_) internal
getVotes
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256)
Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
__gap
uint256[50] __gap
GovernorVotesQuorumFractionUpgradeable
_Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a fraction of the total supply.
Available since v4.3._
_quorumNumerator
uint256 _quorumNumerator
QuorumNumeratorUpdated
event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator)
__GovernorVotesQuorumFraction_init
function __GovernorVotesQuorumFraction_init(uint256 quorumNumeratorValue) internal
__GovernorVotesQuorumFraction_init_unchained
function __GovernorVotesQuorumFraction_init_unchained(uint256 quorumNumeratorValue) internal
quorumNumerator
function quorumNumerator() public view virtual returns (uint256)
quorumDenominator
function quorumDenominator() public view virtual returns (uint256)
quorum
function quorum(uint256 blockNumber) public view virtual returns (uint256)
module:user-config
_Minimum number of cast voted required for a proposal to be successful.
Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes})._
updateQuorumNumerator
function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual
_updateQuorumNumerator
function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual
__gap
uint256[49] __gap
GovernorVotesUpgradeable
_Extension of {Governor} for voting weight extraction from an {ERC20Votes} token.
Available since v4.3._
token
contract ERC20VotesUpgradeable token
__GovernorVotes_init
function __GovernorVotes_init(contract ERC20VotesUpgradeable tokenAddress) internal
__GovernorVotes_init_unchained
function __GovernorVotes_init_unchained(contract ERC20VotesUpgradeable tokenAddress) internal
getVotes
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256)
Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
__gap
uint256[50] __gap
IGovernorTimelockUpgradeable
_Extension of the {IGovernor} for timelock supporting modules.
Available since v4.3._
__IGovernorTimelock_init
function __IGovernorTimelock_init() internal
__IGovernorTimelock_init_unchained
function __IGovernorTimelock_init_unchained() internal
ProposalQueued
event ProposalQueued(uint256 proposalId, uint256 eta)
timelock
function timelock() public view virtual returns (address)
proposalEta
function proposalEta(uint256 proposalId) public view virtual returns (uint256)
queue
function queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public virtual returns (uint256 proposalId)
__gap
uint256[50] __gap
IERC1271Upgradeable
_Interface of the ERC1271 standard signature validation method for contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
Available since v4.1._
isValidSignature
function isValidSignature(bytes32 hash, bytes signature) external view returns (bytes4 magicValue)
Should return whether the signature provided is valid for the provided data
hash
bytes32
Hash of the data to be signed
signature
bytes
Signature byte array associated with _data
IERC1363Upgradeable
transferAndCall
function transferAndCall(address to, uint256 value) external returns (bool)
Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
[0]
bool
true unless throwing
transferAndCall
function transferAndCall(address to, uint256 value, bytes data) external returns (bool)
Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
data
bytes
bytes Additional data with no specified format, sent in call to `to`
[0]
bool
true unless throwing
transferFromAndCall
function transferFromAndCall(address from, address to, uint256 value) external returns (bool)
Transfer tokens from one address to another and then call `onTransferReceived` on receiver
from
address
address The address which you want to send tokens from
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
[0]
bool
true unless throwing
transferFromAndCall
function transferFromAndCall(address from, address to, uint256 value, bytes data) external returns (bool)
Transfer tokens from one address to another and then call `onTransferReceived` on receiver
from
address
address The address which you want to send tokens from
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
data
bytes
bytes Additional data with no specified format, sent in call to `to`
[0]
bool
true unless throwing
approveAndCall
function approveAndCall(address spender, uint256 value) external returns (bool)
Approve the passed address to spend the specified amount of tokens on behalf of msg.sender and then call `onApprovalReceived` on spender.
spender
address
address The address which will spend the funds
value
uint256
uint256 The amount of tokens to be spent
approveAndCall
function approveAndCall(address spender, uint256 value, bytes data) external returns (bool)
Approve the passed address to spend the specified amount of tokens on behalf of msg.sender and then call `onApprovalReceived` on spender.
spender
address
address The address which will spend the funds
value
uint256
uint256 The amount of tokens to be spent
data
bytes
bytes Additional data with no specified format, sent in call to `spender`
IERC2981Upgradeable
Interface for the NFT Royalty Standard
royaltyInfo
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount)
Called with the sale price to determine how much royalty is owed and to whom.
tokenId
uint256
- the NFT asset queried for royalty information
salePrice
uint256
- the sale price of the NFT asset specified by `tokenId`
receiver
address
- address of who should be sent the royalty payment
royaltyAmount
uint256
- the royalty payment amount for `salePrice`
IERC3156FlashBorrowerUpgradeable
_Interface of the ERC3156 FlashBorrower, as defined in https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
Available since v4.1._
onFlashLoan
function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes data) external returns (bytes32)
Receive a flash loan.
initiator
address
The initiator of the loan.
token
address
The loan currency.
amount
uint256
The amount of tokens lent.
fee
uint256
The additional amount of tokens to repay.
data
bytes
Arbitrary data structure, intended to contain user-defined parameters.
[0]
bytes32
The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
IERC3156FlashLenderUpgradeable
_Interface of the ERC3156 FlashLender, as defined in https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
Available since v4.1._
maxFlashLoan
function maxFlashLoan(address token) external view returns (uint256)
The amount of currency available to be lended.
token
address
The loan currency.
[0]
uint256
The amount of `token` that can be borrowed.
flashFee
function flashFee(address token, uint256 amount) external view returns (uint256)
The fee to be charged for a given loan.
token
address
The loan currency.
amount
uint256
The amount of tokens lent.
[0]
uint256
The amount of `token` to be charged for the loan, on top of the returned principal.
flashLoan
function flashLoan(contract IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes data) external returns (bool)
Initiate a flash loan.
receiver
contract IERC3156FlashBorrowerUpgradeable
The receiver of the tokens in the loan, and the receiver of the callback.
token
address
The loan currency.
amount
uint256
The amount of tokens lent.
data
bytes
Arbitrary data structure, intended to contain user-defined parameters.
IERC2612Upgradeable
ERC2771ContextUpgradeable
Context variant with ERC2771 support.
_trustedForwarder
address _trustedForwarder
__ERC2771Context_init
function __ERC2771Context_init(address trustedForwarder) internal
__ERC2771Context_init_unchained
function __ERC2771Context_init_unchained(address trustedForwarder) internal
isTrustedForwarder
function isTrustedForwarder(address forwarder) public view virtual returns (bool)
_msgSender
function _msgSender() internal view virtual returns (address sender)
_msgData
function _msgData() internal view virtual returns (bytes)
__gap
uint256[49] __gap
MinimalForwarderUpgradeable
Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.
ForwardRequest
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
_TYPEHASH
bytes32 _TYPEHASH
_nonces
mapping(address => uint256) _nonces
__MinimalForwarder_init
function __MinimalForwarder_init() internal
__MinimalForwarder_init_unchained
function __MinimalForwarder_init_unchained() internal
getNonce
function getNonce(address from) public view returns (uint256)
verify
function verify(struct MinimalForwarderUpgradeable.ForwardRequest req, bytes signature) public view returns (bool)
execute
function execute(struct MinimalForwarderUpgradeable.ForwardRequest req, bytes signature) public payable returns (bool, bytes)
__gap
uint256[49] __gap
ERC1967UpgradeUpgradeable
_This abstract contract provides getters and event emitting update functions for https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
Available since v4.1._
__ERC1967Upgrade_init
function __ERC1967Upgrade_init() internal
__ERC1967Upgrade_init_unchained
function __ERC1967Upgrade_init_unchained() internal
_ROLLBACK_SLOT
bytes32 _ROLLBACK_SLOT
_IMPLEMENTATION_SLOT
bytes32 _IMPLEMENTATION_SLOT
Storage slot with the address of the current implementation. This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is validated in the constructor.
Upgraded
event Upgraded(address implementation)
Emitted when the implementation is upgraded.
_getImplementation
function _getImplementation() internal view returns (address)
Returns the current implementation address.
_setImplementation
function _setImplementation(address newImplementation) private
Stores a new address in the EIP1967 implementation slot.
_upgradeTo
function _upgradeTo(address newImplementation) internal
_Perform implementation upgrade
Emits an {Upgraded} event._
_upgradeToAndCall
function _upgradeToAndCall(address newImplementation, bytes data, bool forceCall) internal
_Perform implementation upgrade with additional setup call.
Emits an {Upgraded} event._
_upgradeToAndCallSecure
function _upgradeToAndCallSecure(address newImplementation, bytes data, bool forceCall) internal
_Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
Emits an {Upgraded} event._
_ADMIN_SLOT
bytes32 _ADMIN_SLOT
Storage slot with the admin of the contract. This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is validated in the constructor.
AdminChanged
event AdminChanged(address previousAdmin, address newAdmin)
Emitted when the admin account has changed.
_getAdmin
function _getAdmin() internal view returns (address)
Returns the current admin.
_setAdmin
function _setAdmin(address newAdmin) private
Stores a new address in the EIP1967 admin slot.
_changeAdmin
function _changeAdmin(address newAdmin) internal
_Changes the admin of the proxy.
Emits an {AdminChanged} event._
_BEACON_SLOT
bytes32 _BEACON_SLOT
The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
BeaconUpgraded
event BeaconUpgraded(address beacon)
Emitted when the beacon is upgraded.
_getBeacon
function _getBeacon() internal view returns (address)
Returns the current beacon.
_setBeacon
function _setBeacon(address newBeacon) private
Stores a new beacon in the EIP1967 beacon slot.
_upgradeBeaconToAndCall
function _upgradeBeaconToAndCall(address newBeacon, bytes data, bool forceCall) internal
_Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
Emits a {BeaconUpgraded} event._
_functionDelegateCall
function _functionDelegateCall(address target, bytes data) private returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a delegate call.
Available since v3.4._
__gap
uint256[50] __gap
IBeaconUpgradeable
This is the interface that {BeaconProxy} expects of its beacon.
implementation
function implementation() external view returns (address)
_Must return an address that can be used as a delegate call target.
{BeaconProxy} will check that this address is a contract._
Initializable
_This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure that all initializers are idempotent. This is not verified automatically as constructors are by Solidity._
_initialized
bool _initialized
Indicates that the contract has been initialized.
_initializing
bool _initializing
Indicates that the contract is in the process of being initialized.
initializer
modifier initializer()
Modifier to protect an initializer function from being invoked twice.
UUPSUpgradeable
_An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing `UUPSUpgradeable` with a custom implementation of upgrades.
The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
Available since v4.1._
__UUPSUpgradeable_init
function __UUPSUpgradeable_init() internal
__UUPSUpgradeable_init_unchained
function __UUPSUpgradeable_init_unchained() internal
upgradeTo
function upgradeTo(address newImplementation) external virtual
_Upgrade the implementation of the proxy to `newImplementation`.
Calls {_authorizeUpgrade}.
Emits an {Upgraded} event._
upgradeToAndCall
function upgradeToAndCall(address newImplementation, bytes data) external payable virtual
_Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call encoded in `data`.
Calls {_authorizeUpgrade}.
Emits an {Upgraded} event._
_authorizeUpgrade
function _authorizeUpgrade(address newImplementation) internal virtual
_Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by {upgradeTo} and {upgradeToAndCall}.
Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
```solidity function authorizeUpgrade(address) internal override onlyOwner {} ```
__gap
uint256[50] __gap
PausableUpgradeable
_Contract module which allows children to implement an emergency stop mechanism that can be triggered by an authorized account.
This module is used through inheritance. It will make available the modifiers `whenNotPaused` and `whenPaused`, which can be applied to the functions of your contract. Note that they will not be pausable by simply including this module, only once the modifiers are put in place._
Paused
event Paused(address account)
Emitted when the pause is triggered by `account`.
Unpaused
event Unpaused(address account)
Emitted when the pause is lifted by `account`.
_paused
bool _paused
__Pausable_init
function __Pausable_init() internal
Initializes the contract in unpaused state.
__Pausable_init_unchained
function __Pausable_init_unchained() internal
paused
function paused() public view virtual returns (bool)
Returns true if the contract is paused, and false otherwise.
whenNotPaused
modifier whenNotPaused()
_Modifier to make a function callable only when the contract is not paused.
Requirements:
The contract must not be paused._
whenPaused
modifier whenPaused()
_Modifier to make a function callable only when the contract is paused.
Requirements:
The contract must be paused._
_pause
function _pause() internal virtual
_Triggers stopped state.
Requirements:
The contract must not be paused._
_unpause
function _unpause() internal virtual
_Returns to normal state.
Requirements:
The contract must be paused._
__gap
uint256[49] __gap
PullPaymentUpgradeable
_Simple implementation of a https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] strategy, where the paying contract doesn't interact directly with the receiver account, which must withdraw its payments itself.
Pull-payments are often considered the best practice when it comes to sending Ether, security-wise. It prevents recipients from blocking execution, and eliminates reentrancy concerns.
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].
To use, derive from the `PullPayment` contract, and use {asyncTransfer} instead of Solidity's `transfer` function. Payees can query their due payments with {payments}, and retrieve them with {withdrawPayments}.
_escrow
contract EscrowUpgradeable _escrow
__PullPayment_init
function __PullPayment_init() internal
__PullPayment_init_unchained
function __PullPayment_init_unchained() internal
withdrawPayments
function withdrawPayments(address payable payee) public virtual
_Withdraw accumulated payments, forwarding all gas to the recipient.
Note that any account can call this function, not just the `payee`. This means that contracts unaware of the `PullPayment` protocol can still receive funds this way, by having a separate account call {withdrawPayments}.
WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. Make sure you trust the recipient, or are either following the checks-effects-interactions pattern or using {ReentrancyGuard}._
payee
address payable
Whose payments will be withdrawn.
payments
function payments(address dest) public view returns (uint256)
Returns the payments owed to an address.
dest
address
The creditor's address.
_asyncTransfer
function _asyncTransfer(address dest, uint256 amount) internal virtual
Called by the payer to store the sent amount as credit to be pulled. Funds sent in this way are stored in an intermediate {Escrow} contract, so there is no danger of them being spent before withdrawal.
dest
address
The destination address of the funds.
amount
uint256
The amount to transfer.
__gap
uint256[50] __gap
ReentrancyGuardUpgradeable
_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]._
_NOT_ENTERED
uint256 _NOT_ENTERED
_ENTERED
uint256 _ENTERED
_status
uint256 _status
__ReentrancyGuard_init
function __ReentrancyGuard_init() internal
__ReentrancyGuard_init_unchained
function __ReentrancyGuard_init_unchained() internal
nonReentrant
modifier nonReentrant()
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.
__gap
uint256[49] __gap
ERC1155Upgradeable
_Implementation of the basic standard multi-token. See https://eips.ethereum.org/EIPS/eip-1155 Originally based on code by Enjin: https://github.com/enjin/erc-1155
Available since v3.1._
_balances
mapping(uint256 => mapping(address => uint256)) _balances
_operatorApprovals
mapping(address => mapping(address => bool)) _operatorApprovals
_uri
string _uri
__ERC1155_init
function __ERC1155_init(string uri_) internal
_See {setURI}.
__ERC1155_init_unchained
function __ERC1155_init_unchained(string uri_) internal
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
uri
function uri(uint256) public view virtual returns (string)
_See {IERC1155MetadataURI-uri}.
This implementation returns the same URI for all token types. It relies on the token type ID substitution mechanism https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
Clients calling this function must replace the `{id}` substring with the actual token type ID._
balanceOf
function balanceOf(address account, uint256 id) public view virtual returns (uint256)
_See {IERC1155-balanceOf}.
Requirements:
`account` cannot be the zero address._
balanceOfBatch
function balanceOfBatch(address[] accounts, uint256[] ids) public view virtual returns (uint256[])
_See {IERC1155-balanceOfBatch}.
Requirements:
`accounts` and `ids` must have the same length._
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public virtual
See {IERC1155-setApprovalForAll}.
isApprovedForAll
function isApprovedForAll(address account, address operator) public view virtual returns (bool)
See {IERC1155-isApprovedForAll}.
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) public virtual
See {IERC1155-safeTransferFrom}.
safeBatchTransferFrom
function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data) public virtual
See {IERC1155-safeBatchTransferFrom}.
_safeTransferFrom
function _safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) internal virtual
_Transfers `amount` tokens of token type `id` from `from` to `to`.
Emits a {TransferSingle} event.
Requirements:
`to` cannot be the zero address.
`from` must have a balance of tokens of type `id` of at least `amount`.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value._
_safeBatchTransferFrom
function _safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
Emits a {TransferBatch} event.
Requirements:
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value._
_setURI
function _setURI(string newuri) internal virtual
_Sets a new URI for all token types, by relying on the token type ID substitution mechanism https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
By this mechanism, any occurrence of the `{id}` substring in either the URI or any of the amounts in the JSON file at said URI will be replaced by clients with the token type ID.
For example, the `https://token-cdn-domain/{id}.json` URI would be interpreted by clients as `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` for token type ID 0x4cce0.
See {uri}.
Because these URIs cannot be meaningfully represented by the {URI} event, this function emits no events._
_mint
function _mint(address account, uint256 id, uint256 amount, bytes data) internal virtual
_Creates `amount` tokens of token type `id`, and assigns them to `account`.
Emits a {TransferSingle} event.
Requirements:
`account` cannot be the zero address.
If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value._
_mintBatch
function _mintBatch(address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
Requirements:
`ids` and `amounts` must have the same length.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value._
_burn
function _burn(address account, uint256 id, uint256 amount) internal virtual
_Destroys `amount` tokens of token type `id` from `account`
Requirements:
`account` cannot be the zero address.
`account` must have at least `amount` tokens of token type `id`._
_burnBatch
function _burnBatch(address account, uint256[] ids, uint256[] amounts) internal virtual
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
Requirements:
`ids` and `amounts` must have the same length._
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_Hook that is called before any token transfer. This includes minting and burning, as well as batched variants.
The same hook is called on both single and batched variants. For single transfers, the length of the `id` and `amount` arrays will be 1.
Calling conditions (for each `id` and `amount` pair):
When `from` and `to` are both non-zero, `amount` of ``from``'s tokens of token type `id` will be transferred to `to`.
When `from` is zero, `amount` tokens of token type `id` will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens of token type `id` will be burned.
`from` and `to` are never both zero.
`ids` and `amounts` have the same, non-zero length.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_doSafeTransferAcceptanceCheck
function _doSafeTransferAcceptanceCheck(address operator, address from, address to, uint256 id, uint256 amount, bytes data) private
_doSafeBatchTransferAcceptanceCheck
function _doSafeBatchTransferAcceptanceCheck(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) private
_asSingletonArray
function _asSingletonArray(uint256 element) private pure returns (uint256[])
__gap
uint256[47] __gap
IERC1155ReceiverUpgradeable
Available since v3.1.
onERC1155Received
function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes data) external returns (bytes4)
Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
onERC1155BatchReceived
function onERC1155BatchReceived(address operator, address from, uint256[] ids, uint256[] values, bytes data) external returns (bytes4)
Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
IERC1155Upgradeable
_Required interface of an ERC1155 compliant contract, as defined in the https://eips.ethereum.org/EIPS/eip-1155[EIP].
Available since v3.1._
TransferSingle
event TransferSingle(address operator, address from, address to, uint256 id, uint256 value)
Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
TransferBatch
event TransferBatch(address operator, address from, address to, uint256[] ids, uint256[] values)
Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all transfers.
ApprovalForAll
event ApprovalForAll(address account, address operator, bool approved)
Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to `approved`.
URI
event URI(string value, uint256 id)
_Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
If an {URI} event was emitted for `id`, the standard https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value returned by {IERC1155MetadataURI-uri}._
balanceOf
function balanceOf(address account, uint256 id) external view returns (uint256)
_Returns the amount of tokens of token type `id` owned by `account`.
Requirements:
`account` cannot be the zero address._
balanceOfBatch
function balanceOfBatch(address[] accounts, uint256[] ids) external view returns (uint256[])
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
Requirements:
`accounts` and `ids` must have the same length._
setApprovalForAll
function setApprovalForAll(address operator, bool approved) external
_Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
Emits an {ApprovalForAll} event.
Requirements:
`operator` cannot be the caller._
isApprovedForAll
function isApprovedForAll(address account, address operator) external view returns (bool)
_Returns true if `operator` is approved to transfer ``account``'s tokens.
See {setApprovalForAll}._
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) external
_Transfers `amount` tokens of token type `id` from `from` to `to`.
Emits a {TransferSingle} event.
Requirements:
`to` cannot be the zero address.
If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
`from` must have a balance of tokens of type `id` of at least `amount`.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value._
safeBatchTransferFrom
function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data) external
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
Emits a {TransferBatch} event.
Requirements:
`ids` and `amounts` must have the same length.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value._
ERC1155BurnableUpgradeable
_Extension of {ERC1155} that allows token holders to destroy both their own tokens and those that they have been approved to use.
Available since v3.1._
__ERC1155Burnable_init
function __ERC1155Burnable_init() internal
__ERC1155Burnable_init_unchained
function __ERC1155Burnable_init_unchained() internal
burn
function burn(address account, uint256 id, uint256 value) public virtual
burnBatch
function burnBatch(address account, uint256[] ids, uint256[] values) public virtual
__gap
uint256[50] __gap
ERC1155PausableUpgradeable
_ERC1155 token with pausable token transfers, minting and burning.
Useful for scenarios such as preventing trades until the end of an evaluation period, or having an emergency switch for freezing all token transfers in the event of a large bug.
Available since v3.1._
__ERC1155Pausable_init
function __ERC1155Pausable_init() internal
__ERC1155Pausable_init_unchained
function __ERC1155Pausable_init_unchained() internal
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_See {ERC1155-_beforeTokenTransfer}.
Requirements:
the contract must not be paused._
__gap
uint256[50] __gap
ERC1155SupplyUpgradeable
_Extension of ERC1155 that adds tracking of total supply per id.
Useful for scenarios where Fungible and Non-fungible tokens have to be clearly identified. Note: While a totalSupply of 1 might mean the corresponding is an NFT, there is no guarantees that no other token with the same id are not going to be minted._
__ERC1155Supply_init
function __ERC1155Supply_init() internal
__ERC1155Supply_init_unchained
function __ERC1155Supply_init_unchained() internal
_totalSupply
mapping(uint256 => uint256) _totalSupply
totalSupply
function totalSupply(uint256 id) public view virtual returns (uint256)
Total amount of tokens in with a given id.
exists
function exists(uint256 id) public view virtual returns (bool)
Indicates weither any token exist with a given id, or not.
_mint
function _mint(address account, uint256 id, uint256 amount, bytes data) internal virtual
_See {ERC1155-mint}.
_mintBatch
function _mintBatch(address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_See {ERC1155-mintBatch}.
_burn
function _burn(address account, uint256 id, uint256 amount) internal virtual
_See {ERC1155-burn}.
_burnBatch
function _burnBatch(address account, uint256[] ids, uint256[] amounts) internal virtual
_See {ERC1155-burnBatch}.
__gap
uint256[49] __gap
IERC1155MetadataURIUpgradeable
_Interface of the optional ERC1155MetadataExtension interface, as defined in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
Available since v3.1._
uri
function uri(uint256 id) external view returns (string)
_Returns the URI for token type `id`.
If the `{id}` substring is present in the URI, it must be replaced by clients with the actual token type ID._
ERC1155PresetMinterPauserUpgradeable
_{ERC1155} token, including:
ability for holders to burn (destroy) their tokens
a minter role that allows for token minting (creation)
a pauser role that allows to stop all token transfers
This contract uses {AccessControl} to lock permissioned functions using the different roles - head to its documentation for details.
The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role, which will let it grant both minter and pauser roles to other accounts._
initialize
function initialize(string uri) public virtual
MINTER_ROLE
bytes32 MINTER_ROLE
PAUSER_ROLE
bytes32 PAUSER_ROLE
__ERC1155PresetMinterPauser_init
function __ERC1155PresetMinterPauser_init(string uri) internal
Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that deploys the contract.
__ERC1155PresetMinterPauser_init_unchained
function __ERC1155PresetMinterPauser_init_unchained(string uri) internal
mint
function mint(address to, uint256 id, uint256 amount, bytes data) public virtual
_Creates `amount` new tokens for `to`, of token type `id`.
See {ERC1155-_mint}.
Requirements:
the caller must have the `MINTER_ROLE`._
mintBatch
function mintBatch(address to, uint256[] ids, uint256[] amounts, bytes data) public virtual
xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
pause
function pause() public virtual
_Pauses all token transfers.
See {ERC1155Pausable} and {Pausable-_pause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
unpause
function unpause() public virtual
_Unpauses all token transfers.
See {ERC1155Pausable} and {Pausable-_unpause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
__gap
uint256[50] __gap
ERC1155HolderUpgradeable
Available since v3.1.
__ERC1155Holder_init
function __ERC1155Holder_init() internal
__ERC1155Holder_init_unchained
function __ERC1155Holder_init_unchained() internal
onERC1155Received
function onERC1155Received(address, address, uint256, uint256, bytes) public virtual returns (bytes4)
onERC1155BatchReceived
function onERC1155BatchReceived(address, address, uint256[], uint256[], bytes) public virtual returns (bytes4)
__gap
uint256[50] __gap
ERC1155ReceiverUpgradeable
Available since v3.1.
__ERC1155Receiver_init
function __ERC1155Receiver_init() internal
__ERC1155Receiver_init_unchained
function __ERC1155Receiver_init_unchained() internal
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
__gap
uint256[50] __gap
ERC20Upgradeable
_Implementation of the {IERC20} interface.
This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}.
TIP: For a detailed writeup see our guide https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How to implement supply mechanisms].
We have followed general OpenZeppelin Contracts guidelines: functions revert instead returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications.
Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification.
Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}._
_balances
mapping(address => uint256) _balances
_allowances
mapping(address => mapping(address => uint256)) _allowances
_totalSupply
uint256 _totalSupply
_name
string _name
_symbol
string _symbol
__ERC20_init
function __ERC20_init(string name_, string symbol_) internal
_Sets the values for {name} and {symbol}.
The default value of {decimals} is 18. To select a different value for {decimals} you should overload it.
All two of these values are immutable: they can only be set once during construction._
__ERC20_init_unchained
function __ERC20_init_unchained(string name_, string symbol_) internal
name
function name() public view virtual returns (string)
Returns the name of the token.
symbol
function symbol() public view virtual returns (string)
Returns the symbol of the token, usually a shorter version of the name.
decimals
function decimals() public view virtual returns (uint8)
_Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5.05` (`505 / 10 ** 2`).
Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless this function is overridden;
NOTE: This information is only used for display purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}._
totalSupply
function totalSupply() public view virtual returns (uint256)
See {IERC20-totalSupply}.
balanceOf
function balanceOf(address account) public view virtual returns (uint256)
See {IERC20-balanceOf}.
transfer
function transfer(address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transfer}.
Requirements:
`recipient` cannot be the zero address.
the caller must have a balance of at least `amount`._
allowance
function allowance(address owner, address spender) public view virtual returns (uint256)
See {IERC20-allowance}.
approve
function approve(address spender, uint256 amount) public virtual returns (bool)
_See {IERC20-approve}.
Requirements:
`spender` cannot be the zero address._
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transferFrom}.
Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}.
Requirements:
`sender` and `recipient` cannot be the zero address.
`sender` must have a balance of at least `amount`.
the caller must have allowance for ``sender``'s tokens of at least `amount`._
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool)
_Atomically increases the allowance granted to `spender` by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
`spender` cannot be the zero address._
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool)
_Atomically decreases the allowance granted to `spender` by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
`spender` cannot be the zero address.
`spender` must have allowance for the caller of at least `subtractedValue`._
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal virtual
_Moves `amount` of tokens from `sender` to `recipient`.
This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc.
Emits a {Transfer} event.
Requirements:
`sender` cannot be the zero address.
`recipient` cannot be the zero address.
`sender` must have a balance of at least `amount`._
_mint
function _mint(address account, uint256 amount) internal virtual
_Creates `amount` tokens and assigns them to `account`, increasing the total supply.
Emits a {Transfer} event with `from` set to the zero address.
Requirements:
`account` cannot be the zero address._
_burn
function _burn(address account, uint256 amount) internal virtual
_Destroys `amount` tokens from `account`, reducing the total supply.
Emits a {Transfer} event with `to` set to the zero address.
Requirements:
`account` cannot be the zero address.
`account` must have at least `amount` tokens._
_approve
function _approve(address owner, address spender, uint256 amount) internal virtual
_Sets `amount` as the allowance of `spender` over the `owner` s tokens.
This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc.
Emits an {Approval} event.
Requirements:
`owner` cannot be the zero address.
`spender` cannot be the zero address._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
_Hook that is called before any transfer of tokens. This includes minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens will be transferred to `to`.
when `from` is zero, `amount` tokens will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens will be burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_afterTokenTransfer
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual
_Hook that is called after any transfer of tokens. This includes minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens has been transferred to `to`.
when `from` is zero, `amount` tokens have been minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens have been burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
__gap
uint256[45] __gap
IERC20Upgradeable
Interface of the ERC20 standard as defined in the EIP.
totalSupply
function totalSupply() external view returns (uint256)
Returns the amount of tokens in existence.
balanceOf
function balanceOf(address account) external view returns (uint256)
Returns the amount of tokens owned by `account`.
transfer
function transfer(address recipient, uint256 amount) external returns (bool)
_Moves `amount` tokens from the caller's account to `recipient`.
Returns a boolean value indicating whether the operation succeeded.
Emits a {Transfer} event._
allowance
function allowance(address owner, address spender) external view returns (uint256)
_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._
approve
function approve(address spender, uint256 amount) external returns (bool)
_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._
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)
_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._
Transfer
event Transfer(address from, address to, uint256 value)
_Emitted when `value` tokens are moved from one account (`from`) to another (`to`).
Note that `value` may be zero._
Approval
event Approval(address owner, address spender, uint256 value)
Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance.
ERC20BurnableUpgradeable
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).
__ERC20Burnable_init
function __ERC20Burnable_init() internal
__ERC20Burnable_init_unchained
function __ERC20Burnable_init_unchained() internal
burn
function burn(uint256 amount) public virtual
_Destroys `amount` tokens from the caller.
See {ERC20-burn}.
burnFrom
function burnFrom(address account, uint256 amount) public virtual
_Destroys `amount` tokens from `account`, deducting from the caller's allowance.
See {ERC20-_burn} and {ERC20-allowance}.
Requirements:
the caller must have allowance for ``accounts``'s tokens of at least `amount`._
__gap
uint256[50] __gap
ERC20CappedUpgradeable
Extension of {ERC20} that adds a cap to the supply of tokens.
_cap
uint256 _cap
__ERC20Capped_init
function __ERC20Capped_init(uint256 cap_) internal
Sets the value of the `cap`. This value is immutable, it can only be set once during construction.
__ERC20Capped_init_unchained
function __ERC20Capped_init_unchained(uint256 cap_) internal
cap
function cap() public view virtual returns (uint256)
Returns the cap on the token's total supply.
_mint
function _mint(address account, uint256 amount) internal virtual
_See {ERC20-mint}.
__gap
uint256[50] __gap
ERC20FlashMintUpgradeable
_Implementation of the ERC3156 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}.
Available since v4.1._
__ERC20FlashMint_init
function __ERC20FlashMint_init() internal
__ERC20FlashMint_init_unchained
function __ERC20FlashMint_init_unchained() internal
_RETURN_VALUE
bytes32 _RETURN_VALUE
maxFlashLoan
function maxFlashLoan(address token) public view returns (uint256)
Returns the maximum amount of tokens available for loan.
token
address
The address of the token that is requested.
[0]
uint256
The amont of token that can be loaned.
flashFee
function flashFee(address token, uint256 amount) public view virtual returns (uint256)
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.
token
address
The token to be flash loaned.
amount
uint256
The amount of tokens to be loaned.
[0]
uint256
The fees applied to the corresponding flash loan.
flashLoan
function flashLoan(contract IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes data) public virtual returns (bool)
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 amount + fee tokens and have them approved back to the token contract itself so they can be burned.
receiver
contract IERC3156FlashBorrowerUpgradeable
The receiver of the flash loan. Should implement the {IERC3156FlashBorrower.onFlashLoan} interface.
token
address
The token to be flash loaned. Only `address(this)` is supported.
amount
uint256
The amount of tokens to be loaned.
data
bytes
An arbitrary datafield that is passed to the receiver.
[0]
bool
`true` is the flash loan was successful.
__gap
uint256[50] __gap
ERC20PausableUpgradeable
_ERC20 token with pausable token transfers, minting and burning.
Useful for scenarios such as preventing trades until the end of an evaluation period, or having an emergency switch for freezing all token transfers in the event of a large bug._
__ERC20Pausable_init
function __ERC20Pausable_init() internal
__ERC20Pausable_init_unchained
function __ERC20Pausable_init_unchained() internal
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
_See {ERC20-_beforeTokenTransfer}.
Requirements:
the contract must not be paused._
__gap
uint256[50] __gap
ERC20SnapshotUpgradeable
_This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and total supply at the time are recorded for later access.
This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be used to create an efficient ERC20 forking mechanism.
Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id and the account address.
NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient alternative consider {ERC20Votes}.
==== Gas Costs
Snapshots are efficient. Snapshot creation is O(1). Retrieval of balances or total supply from a snapshot is O(log n) in the number of snapshots that have been created, although n for a specific account will generally be much smaller since identical balances in subsequent snapshots are stored as a single entry.
There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent transfers will have normal cost until the next snapshot, and so on._
__ERC20Snapshot_init
function __ERC20Snapshot_init() internal
__ERC20Snapshot_init_unchained
function __ERC20Snapshot_init_unchained() internal
Snapshots
struct Snapshots {
uint256[] ids;
uint256[] values;
}
_accountBalanceSnapshots
mapping(address => struct ERC20SnapshotUpgradeable.Snapshots) _accountBalanceSnapshots
_totalSupplySnapshots
struct ERC20SnapshotUpgradeable.Snapshots _totalSupplySnapshots
_currentSnapshotId
struct CountersUpgradeable.Counter _currentSnapshotId
Snapshot
event Snapshot(uint256 id)
_Emitted by {snapshot} when a snapshot identified by `id` is created.
_snapshot
function _snapshot() internal virtual returns (uint256)
_Creates a new snapshot and returns its snapshot id.
Emits a {Snapshot} event that contains the same id.
{_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a set of accounts, for example using {AccessControl}, or it may be open to the public.
[WARNING] ==== While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, you must consider that it can potentially be used by attackers in two ways.
First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs section above.
We haven't measured the actual numbers; if this is something you're interested in please reach out to us. ====_
_getCurrentSnapshotId
function _getCurrentSnapshotId() internal view virtual returns (uint256)
Get the current snapshotId
balanceOfAt
function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256)
Retrieves the balance of `account` at the time `snapshotId` was created.
totalSupplyAt
function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256)
Retrieves the total supply at the time `snapshotId` was created.
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
_Hook that is called before any transfer of tokens. This includes minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens will be transferred to `to`.
when `from` is zero, `amount` tokens will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens will be burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_valueAt
function _valueAt(uint256 snapshotId, struct ERC20SnapshotUpgradeable.Snapshots snapshots) private view returns (bool, uint256)
_updateAccountSnapshot
function _updateAccountSnapshot(address account) private
_updateTotalSupplySnapshot
function _updateTotalSupplySnapshot() private
_updateSnapshot
function _updateSnapshot(struct ERC20SnapshotUpgradeable.Snapshots snapshots, uint256 currentValue) private
_lastSnapshotId
function _lastSnapshotId(uint256[] ids) private view returns (uint256)
__gap
uint256[46] __gap
ERC20VotesCompUpgradeable
_Extension of ERC20 to support Compound's voting and delegation. This version exactly matches Compound's interface, with the drawback of only supporting supply up to (2^96^ - 1).
NOTE: You should use this contract if you need exact compatibility with COMP (for example in order to use your token with Governor Alpha or Bravo) and if you are sure the supply cap of 2^96^ is enough for you. Otherwise, use the {ERC20Votes} variant of this module.
This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting power can be queried through the public accessors {getCurrentVotes} and {getPriorVotes}.
By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this will significantly increase the base gas cost of transfers.
Available since v4.2._
__ERC20VotesComp_init_unchained
function __ERC20VotesComp_init_unchained() internal
getCurrentVotes
function getCurrentVotes(address account) external view returns (uint96)
Comp version of the {getVotes} accessor, with `uint96` return type.
getPriorVotes
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96)
Comp version of the {getPastVotes} accessor, with `uint96` return type.
_maxSupply
function _maxSupply() internal view virtual returns (uint224)
Maximum token supply. Reduced to `type(uint96).max` (2^96^ - 1) to fit COMP interface.
__gap
uint256[50] __gap
ERC20VotesUpgradeable
_Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting power can be queried through the public accessors {getVotes} and {getPastVotes}.
By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this will significantly increase the base gas cost of transfers.
Available since v4.2._
__ERC20Votes_init_unchained
function __ERC20Votes_init_unchained() internal
Checkpoint
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
_DELEGATION_TYPEHASH
bytes32 _DELEGATION_TYPEHASH
_delegates
mapping(address => address) _delegates
_checkpoints
mapping(address => struct ERC20VotesUpgradeable.Checkpoint[]) _checkpoints
_totalSupplyCheckpoints
struct ERC20VotesUpgradeable.Checkpoint[] _totalSupplyCheckpoints
DelegateChanged
event DelegateChanged(address delegator, address fromDelegate, address toDelegate)
Emitted when an account changes their delegate.
DelegateVotesChanged
event DelegateVotesChanged(address delegate, uint256 previousBalance, uint256 newBalance)
Emitted when a token transfer or delegate change results in changes to an account's voting power.
checkpoints
function checkpoints(address account, uint32 pos) public view virtual returns (struct ERC20VotesUpgradeable.Checkpoint)
Get the `pos`-th checkpoint for `account`.
numCheckpoints
function numCheckpoints(address account) public view virtual returns (uint32)
Get number of checkpoints for `account`.
delegates
function delegates(address account) public view virtual returns (address)
Get the address `account` is currently delegating to.
getVotes
function getVotes(address account) public view returns (uint256)
Gets the current votes balance for `account`
getPastVotes
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256)
_Retrieve the number of votes for `account` at the end of `blockNumber`.
Requirements:
`blockNumber` must have been already mined_
getPastTotalSupply
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256)
_Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. It is but NOT the sum of all the delegated votes!
Requirements:
`blockNumber` must have been already mined_
_checkpointsLookup
function _checkpointsLookup(struct ERC20VotesUpgradeable.Checkpoint[] ckpts, uint256 blockNumber) private view returns (uint256)
Lookup a value in a list of (sorted) checkpoints.
delegate
function delegate(address delegatee) public virtual
Delegate votes from the sender to `delegatee`.
delegateBySig
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) public virtual
Delegates votes from signer to `delegatee`
_maxSupply
function _maxSupply() internal view virtual returns (uint224)
Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
_mint
function _mint(address account, uint256 amount) internal virtual
Snapshots the totalSupply after it has been increased.
_burn
function _burn(address account, uint256 amount) internal virtual
Snapshots the totalSupply after it has been decreased.
_afterTokenTransfer
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual
_Move voting power when tokens are transferred.
Emits a {DelegateVotesChanged} event._
_delegate
function _delegate(address delegator, address delegatee) internal virtual
_Change delegation for `delegator` to `delegatee`.
Emits events {DelegateChanged} and {DelegateVotesChanged}._
_moveVotingPower
function _moveVotingPower(address src, address dst, uint256 amount) private
_writeCheckpoint
function _writeCheckpoint(struct ERC20VotesUpgradeable.Checkpoint[] ckpts, function (uint256,uint256) view returns (uint256) op, uint256 delta) private returns (uint256 oldWeight, uint256 newWeight)
_add
function _add(uint256 a, uint256 b) private pure returns (uint256)
_subtract
function _subtract(uint256 a, uint256 b) private pure returns (uint256)
__gap
uint256[47] __gap
ERC20WrapperUpgradeable
_Extension of the ERC20 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" ERC20 into a governance token.
Available since v4.2._
underlying
contract IERC20Upgradeable underlying
__ERC20Wrapper_init
function __ERC20Wrapper_init(contract IERC20Upgradeable underlyingToken) internal
__ERC20Wrapper_init_unchained
function __ERC20Wrapper_init_unchained(contract IERC20Upgradeable underlyingToken) internal
depositFor
function depositFor(address account, uint256 amount) public virtual returns (bool)
Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
withdrawTo
function withdrawTo(address account, uint256 amount) public virtual returns (bool)
Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
_recover
function _recover(address account) internal virtual returns (uint256)
Mint wrapped token to cover any underlyingTokens that would have been transfered by mistake. Internal function that can be exposed with access control if desired.
__gap
uint256[50] __gap
IERC20MetadataUpgradeable
_Interface for the optional metadata functions from the ERC20 standard.
Available since v4.1._
name
function name() external view returns (string)
Returns the name of the token.
symbol
function symbol() external view returns (string)
Returns the symbol of the token.
decimals
function decimals() external view returns (uint8)
Returns the decimals places of the token.
ERC20PermitUpgradeable
_Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all.
Available since v3.4._
_nonces
mapping(address => struct CountersUpgradeable.Counter) _nonces
_PERMIT_TYPEHASH
bytes32 _PERMIT_TYPEHASH
__ERC20Permit_init
function __ERC20Permit_init(string name) internal
_Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
It's a good idea to use the same `name` that is defined as the ERC20 token name._
__ERC20Permit_init_unchained
function __ERC20Permit_init_unchained(string name) internal
permit
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual
See {IERC20Permit-permit}.
nonces
function nonces(address owner) public view virtual returns (uint256)
See {IERC20Permit-nonces}.
DOMAIN_SEPARATOR
function DOMAIN_SEPARATOR() external view returns (bytes32)
See {IERC20Permit-DOMAIN_SEPARATOR}.
_useNonce
function _useNonce(address owner) internal virtual returns (uint256 current)
_"Consume a nonce": return the current value and increment.
Available since v4.1._
__gap
uint256[49] __gap
IERC20PermitUpgradeable
_Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all._
permit
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external
_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]._
nonces
function nonces(address owner) external view returns (uint256)
_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._
DOMAIN_SEPARATOR
function DOMAIN_SEPARATOR() external view returns (bytes32)
Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
ERC20PresetFixedSupplyUpgradeable
_{ERC20} token, including:
Preminted initial supply
Ability for holders to burn (destroy) their tokens
No access control mechanism (for minting/pausing) and hence no governance
This contract uses {ERC20Burnable} to include burn capabilities - head to its documentation for details.
Available since v3.4._
initialize
function initialize(string name, string symbol, uint256 initialSupply, address owner) public virtual
__ERC20PresetFixedSupply_init
function __ERC20PresetFixedSupply_init(string name, string symbol, uint256 initialSupply, address owner) internal
_Mints `initialSupply` amount of token and transfers them to `owner`.
See {ERC20-constructor}._
__ERC20PresetFixedSupply_init_unchained
function __ERC20PresetFixedSupply_init_unchained(string name, string symbol, uint256 initialSupply, address owner) internal
__gap
uint256[50] __gap
ERC20PresetMinterPauserUpgradeable
_{ERC20} token, including:
ability for holders to burn (destroy) their tokens
a minter role that allows for token minting (creation)
a pauser role that allows to stop all token transfers
This contract uses {AccessControl} to lock permissioned functions using the different roles - head to its documentation for details.
The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role, which will let it grant both minter and pauser roles to other accounts._
initialize
function initialize(string name, string symbol) public virtual
MINTER_ROLE
bytes32 MINTER_ROLE
PAUSER_ROLE
bytes32 PAUSER_ROLE
__ERC20PresetMinterPauser_init
function __ERC20PresetMinterPauser_init(string name, string symbol) internal
_Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the account that deploys the contract.
See {ERC20-constructor}._
__ERC20PresetMinterPauser_init_unchained
function __ERC20PresetMinterPauser_init_unchained(string name, string symbol) internal
mint
function mint(address to, uint256 amount) public virtual
_Creates `amount` new tokens for `to`.
See {ERC20-_mint}.
Requirements:
the caller must have the `MINTER_ROLE`._
pause
function pause() public virtual
_Pauses all token transfers.
See {ERC20Pausable} and {Pausable-_pause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
unpause
function unpause() public virtual
_Unpauses all token transfers.
See {ERC20Pausable} and {Pausable-_unpause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
__gap
uint256[50] __gap
SafeERC20Upgradeable
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.
safeTransfer
function safeTransfer(contract IERC20Upgradeable token, address to, uint256 value) internal
safeTransferFrom
function safeTransferFrom(contract IERC20Upgradeable token, address from, address to, uint256 value) internal
safeApprove
function safeApprove(contract IERC20Upgradeable token, address spender, uint256 value) internal
_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._
safeIncreaseAllowance
function safeIncreaseAllowance(contract IERC20Upgradeable token, address spender, uint256 value) internal
safeDecreaseAllowance
function safeDecreaseAllowance(contract IERC20Upgradeable token, address spender, uint256 value) internal
_callOptionalReturn
function _callOptionalReturn(contract IERC20Upgradeable token, bytes data) private
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).
token
contract IERC20Upgradeable
The token targeted by the call.
data
bytes
The call data (encoded using abi.encode or one of its variants).
TokenTimelockUpgradeable
_A token holder contract that will allow a beneficiary to extract the tokens after a given release time.
Useful for simple vesting schedules like "advisors get all of their tokens after 1 year"._
_token
contract IERC20Upgradeable _token
_beneficiary
address _beneficiary
_releaseTime
uint256 _releaseTime
__TokenTimelock_init
function __TokenTimelock_init(contract IERC20Upgradeable token_, address beneficiary_, uint256 releaseTime_) internal
__TokenTimelock_init_unchained
function __TokenTimelock_init_unchained(contract IERC20Upgradeable token_, address beneficiary_, uint256 releaseTime_) internal
token
function token() public view virtual returns (contract IERC20Upgradeable)
[0]
contract IERC20Upgradeable
the token being held.
beneficiary
function beneficiary() public view virtual returns (address)
[0]
address
the beneficiary of the tokens.
releaseTime
function releaseTime() public view virtual returns (uint256)
[0]
uint256
the time when the tokens are released.
release
function release() public virtual
Transfers tokens held by timelock to beneficiary.
__gap
uint256[50] __gap
ERC721Upgradeable
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}.
_name
string _name
_symbol
string _symbol
_owners
mapping(uint256 => address) _owners
_balances
mapping(address => uint256) _balances
_tokenApprovals
mapping(uint256 => address) _tokenApprovals
_operatorApprovals
mapping(address => mapping(address => bool)) _operatorApprovals
__ERC721_init
function __ERC721_init(string name_, string symbol_) internal
Initializes the contract by setting a `name` and a `symbol` to the token collection.
__ERC721_init_unchained
function __ERC721_init_unchained(string name_, string symbol_) internal
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
balanceOf
function balanceOf(address owner) public view virtual returns (uint256)
See {IERC721-balanceOf}.
ownerOf
function ownerOf(uint256 tokenId) public view virtual returns (address)
See {IERC721-ownerOf}.
name
function name() public view virtual returns (string)
See {IERC721Metadata-name}.
symbol
function symbol() public view virtual returns (string)
See {IERC721Metadata-symbol}.
tokenURI
function tokenURI(uint256 tokenId) public view virtual returns (string)
See {IERC721Metadata-tokenURI}.
_baseURI
function _baseURI() internal view virtual returns (string)
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.
approve
function approve(address to, uint256 tokenId) public virtual
See {IERC721-approve}.
getApproved
function getApproved(uint256 tokenId) public view virtual returns (address)
See {IERC721-getApproved}.
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public virtual
See {IERC721-setApprovalForAll}.
isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual returns (bool)
See {IERC721-isApprovedForAll}.
transferFrom
function transferFrom(address from, address to, uint256 tokenId) public virtual
See {IERC721-transferFrom}.
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual
See {IERC721-safeTransferFrom}.
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) public virtual
See {IERC721-safeTransferFrom}.
_safeTransfer
function _safeTransfer(address from, address to, uint256 tokenId, bytes _data) internal virtual
_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._
_exists
function _exists(uint256 tokenId) internal view virtual returns (bool)
_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`).
_isApprovedOrOwner
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool)
_Returns whether `spender` is allowed to manage `tokenId`.
Requirements:
`tokenId` must exist._
_safeMint
function _safeMint(address to, uint256 tokenId) internal virtual
_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._
_safeMint
function _safeMint(address to, uint256 tokenId, bytes _data) internal virtual
_Same as {xref-ERC721-_safeMint-address-uint256-}[`safeMint`], with an additional `data` parameter which is forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
_mint
function _mint(address to, uint256 tokenId) internal virtual
_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._
_burn
function _burn(uint256 tokenId) internal virtual
_Destroys `tokenId`. The approval is cleared when the token is burned.
Requirements:
`tokenId` must exist.
Emits a {Transfer} event._
_transfer
function _transfer(address from, address to, uint256 tokenId) internal virtual
_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._
_approve
function _approve(address to, uint256 tokenId) internal virtual
_Approve `to` to operate on `tokenId`
Emits a {Approval} event._
_checkOnERC721Received
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes _data) private returns (bool)
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract.
from
address
address representing the previous owner of the given token ID
to
address
target address that will receive the tokens
tokenId
uint256
uint256 ID of the token to be transferred
_data
bytes
bytes optional data to send along with the call
[0]
bool
bool whether the call correctly returned the expected magic value
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
_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]._
__gap
uint256[44] __gap
IERC721ReceiverUpgradeable
Interface for any contract that wants to support safeTransfers from ERC721 asset contracts.
onERC721Received
function onERC721Received(address operator, address from, uint256 tokenId, bytes data) external returns (bytes4)
_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`._
IERC721Upgradeable
Required interface of an ERC721 compliant contract.
Transfer
event Transfer(address from, address to, uint256 tokenId)
Emitted when `tokenId` token is transferred from `from` to `to`.
Approval
event Approval(address owner, address approved, uint256 tokenId)
Emitted when `owner` enables `approved` to manage the `tokenId` token.
ApprovalForAll
event ApprovalForAll(address owner, address operator, bool approved)
Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
balanceOf
function balanceOf(address owner) external view returns (uint256 balance)
Returns the number of tokens in ``owner``'s account.
ownerOf
function ownerOf(uint256 tokenId) external view returns (address owner)
_Returns the owner of the `tokenId` token.
Requirements:
`tokenId` must exist._
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId) external
_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._
transferFrom
function transferFrom(address from, address to, uint256 tokenId) external
_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._
approve
function approve(address to, uint256 tokenId) external
_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._
getApproved
function getApproved(uint256 tokenId) external view returns (address operator)
_Returns the account approved for `tokenId` token.
Requirements:
`tokenId` must exist._
setApprovalForAll
function setApprovalForAll(address operator, bool _approved) external
_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._
isApprovedForAll
function isApprovedForAll(address owner, address operator) external view returns (bool)
_Returns if the `operator` is allowed to manage all of the assets of `owner`.
See {setApprovalForAll}_
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) external
_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._
ERC721BurnableUpgradeable
ERC721 Token that can be irreversibly burned (destroyed).
__ERC721Burnable_init
function __ERC721Burnable_init() internal
__ERC721Burnable_init_unchained
function __ERC721Burnable_init_unchained() internal
burn
function burn(uint256 tokenId) public virtual
_Burns `tokenId`. See {ERC721-_burn}.
Requirements:
The caller must own `tokenId` or be an approved operator._
__gap
uint256[50] __gap
ERC721EnumerableUpgradeable
This implements an optional extension of {ERC721} defined in the EIP that adds enumerability of all the token ids in the contract as well as all token ids owned by each account.
__ERC721Enumerable_init
function __ERC721Enumerable_init() internal
__ERC721Enumerable_init_unchained
function __ERC721Enumerable_init_unchained() internal
_ownedTokens
mapping(address => mapping(uint256 => uint256)) _ownedTokens
_ownedTokensIndex
mapping(uint256 => uint256) _ownedTokensIndex
_allTokens
uint256[] _allTokens
_allTokensIndex
mapping(uint256 => uint256) _allTokensIndex
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256)
See {IERC721Enumerable-tokenOfOwnerByIndex}.
totalSupply
function totalSupply() public view virtual returns (uint256)
See {IERC721Enumerable-totalSupply}.
tokenByIndex
function tokenByIndex(uint256 index) public view virtual returns (uint256)
See {IERC721Enumerable-tokenByIndex}.
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
_Hook that is called before any token transfer. This includes minting and burning.
Calling conditions:
When `from` and `to` are both non-zero, ``from``'s `tokenId` will be transferred to `to`.
When `from` is zero, `tokenId` will be minted for `to`.
When `to` is zero, ``from``'s `tokenId` will be burned.
`from` cannot be the zero address.
`to` cannot be the zero address.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_addTokenToOwnerEnumeration
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private
Private function to add a token to this extension's ownership-tracking data structures.
to
address
address representing the new owner of the given token ID
tokenId
uint256
uint256 ID of the token to be added to the tokens list of the given address
_addTokenToAllTokensEnumeration
function _addTokenToAllTokensEnumeration(uint256 tokenId) private
Private function to add a token to this extension's token tracking data structures.
tokenId
uint256
uint256 ID of the token to be added to the tokens list
_removeTokenFromOwnerEnumeration
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private
_Private function to remove a token from this extension's ownership-tracking data structures. Note that while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is not updated: this allows for gas optimizations e.g. when performing a transfer operation (avoiding double writes). This has O(1) time complexity, but alters the order of the ownedTokens array.
from
address
address representing the previous owner of the given token ID
tokenId
uint256
uint256 ID of the token to be removed from the tokens list of the given address
_removeTokenFromAllTokensEnumeration
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private
_Private function to remove a token from this extension's token tracking data structures. This has O(1) time complexity, but alters the order of the allTokens array.
tokenId
uint256
uint256 ID of the token to be removed from the tokens list
__gap
uint256[46] __gap
ERC721PausableUpgradeable
_ERC721 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._
__ERC721Pausable_init
function __ERC721Pausable_init() internal
__ERC721Pausable_init_unchained
function __ERC721Pausable_init_unchained() internal
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
_See {ERC721-_beforeTokenTransfer}.
Requirements:
the contract must not be paused._
__gap
uint256[50] __gap
ERC721URIStorageUpgradeable
ERC721 token with storage based token URI management.
__ERC721URIStorage_init
function __ERC721URIStorage_init() internal
__ERC721URIStorage_init_unchained
function __ERC721URIStorage_init_unchained() internal
_tokenURIs
mapping(uint256 => string) _tokenURIs
tokenURI
function tokenURI(uint256 tokenId) public view virtual returns (string)
See {IERC721Metadata-tokenURI}.
_setTokenURI
function _setTokenURI(uint256 tokenId, string _tokenURI) internal virtual
_Sets `_tokenURI` as the tokenURI of `tokenId`.
Requirements:
`tokenId` must exist._
_burn
function _burn(uint256 tokenId) internal virtual
_Destroys `tokenId`. The approval is cleared when the token is burned.
Requirements:
`tokenId` must exist.
Emits a {Transfer} event._
__gap
uint256[49] __gap
IERC721EnumerableUpgradeable
See https://eips.ethereum.org/EIPS/eip-721
totalSupply
function totalSupply() external view returns (uint256)
Returns the total amount of tokens stored by the contract.
tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId)
Returns a token ID owned by `owner` at a given `index` of its token list. Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
tokenByIndex
function tokenByIndex(uint256 index) external view returns (uint256)
Returns a token ID at a given `index` of all the tokens stored by the contract. Use along with {totalSupply} to enumerate all tokens.
IERC721MetadataUpgradeable
See https://eips.ethereum.org/EIPS/eip-721
name
function name() external view returns (string)
Returns the token collection name.
symbol
function symbol() external view returns (string)
Returns the token collection symbol.
tokenURI
function tokenURI(uint256 tokenId) external view returns (string)
Returns the Uniform Resource Identifier (URI) for `tokenId` token.
ERC721PresetMinterPauserAutoIdUpgradeable
_{ERC721} token, including:
ability for holders to burn (destroy) their tokens
a minter role that allows for token minting (creation)
a pauser role that allows to stop all token transfers
token ID and URI autogeneration
This contract uses {AccessControl} to lock permissioned functions using the different roles - head to its documentation for details.
The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role, which will let it grant both minter and pauser roles to other accounts._
initialize
function initialize(string name, string symbol, string baseTokenURI) public virtual
MINTER_ROLE
bytes32 MINTER_ROLE
PAUSER_ROLE
bytes32 PAUSER_ROLE
_tokenIdTracker
struct CountersUpgradeable.Counter _tokenIdTracker
_baseTokenURI
string _baseTokenURI
__ERC721PresetMinterPauserAutoId_init
function __ERC721PresetMinterPauserAutoId_init(string name, string symbol, string baseTokenURI) internal
_Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the account that deploys the contract.
Token URIs will be autogenerated based on `baseURI` and their token IDs. See {ERC721-tokenURI}._
__ERC721PresetMinterPauserAutoId_init_unchained
function __ERC721PresetMinterPauserAutoId_init_unchained(string name, string symbol, string baseTokenURI) internal
_baseURI
function _baseURI() internal view virtual returns (string)
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.
mint
function mint(address to) public virtual
_Creates a new token for `to`. Its token ID will be automatically assigned (and available on the emitted {IERC721-Transfer} event), and the token URI autogenerated based on the base URI passed at construction.
See {ERC721-_mint}.
Requirements:
the caller must have the `MINTER_ROLE`._
pause
function pause() public virtual
_Pauses all token transfers.
See {ERC721Pausable} and {Pausable-_pause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
unpause
function unpause() public virtual
_Unpauses all token transfers.
See {ERC721Pausable} and {Pausable-_unpause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
__gap
uint256[48] __gap
ERC721HolderUpgradeable
_Implementation of the {IERC721Receiver} interface.
Accepts all token transfers. Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}._
__ERC721Holder_init
function __ERC721Holder_init() internal
__ERC721Holder_init_unchained
function __ERC721Holder_init_unchained() internal
onERC721Received
function onERC721Received(address, address, uint256, bytes) public virtual returns (bytes4)
_See {IERC721Receiver-onERC721Received}.
Always returns `IERC721Receiver.onERC721Received.selector`._
__gap
uint256[50] __gap
ERC777Upgradeable
_Implementation of the {IERC777} 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}.
Support for ERC20 is included in this contract, as specified by the EIP: both the ERC777 and ERC20 interfaces can be safely used when interacting with it. Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token movements.
Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there are no special restrictions in the amount of tokens that created, moved, or destroyed. This makes integration with ERC20 applications seamless._
_ERC1820_REGISTRY
contract IERC1820RegistryUpgradeable _ERC1820_REGISTRY
_balances
mapping(address => uint256) _balances
_totalSupply
uint256 _totalSupply
_name
string _name
_symbol
string _symbol
_TOKENS_SENDER_INTERFACE_HASH
bytes32 _TOKENS_SENDER_INTERFACE_HASH
_TOKENS_RECIPIENT_INTERFACE_HASH
bytes32 _TOKENS_RECIPIENT_INTERFACE_HASH
_defaultOperatorsArray
address[] _defaultOperatorsArray
_defaultOperators
mapping(address => bool) _defaultOperators
_operators
mapping(address => mapping(address => bool)) _operators
_revokedDefaultOperators
mapping(address => mapping(address => bool)) _revokedDefaultOperators
_allowances
mapping(address => mapping(address => uint256)) _allowances
__ERC777_init
function __ERC777_init(string name_, string symbol_, address[] defaultOperators_) internal
`defaultOperators` may be an empty array.
__ERC777_init_unchained
function __ERC777_init_unchained(string name_, string symbol_, address[] defaultOperators_) internal
name
function name() public view virtual returns (string)
See {IERC777-name}.
symbol
function symbol() public view virtual returns (string)
See {IERC777-symbol}.
decimals
function decimals() public pure virtual returns (uint8)
_See {ERC20-decimals}.
Always returns 18, as per the ERC777 EIP._
granularity
function granularity() public view virtual returns (uint256)
_See {IERC777-granularity}.
This implementation always returns `1`._
totalSupply
function totalSupply() public view virtual returns (uint256)
See {IERC777-totalSupply}.
balanceOf
function balanceOf(address tokenHolder) public view virtual returns (uint256)
Returns the amount of tokens owned by an account (`tokenHolder`).
send
function send(address recipient, uint256 amount, bytes data) public virtual
_See {IERC777-send}.
Also emits a {IERC20-Transfer} event for ERC20 compatibility._
transfer
function transfer(address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transfer}.
Unlike `send`, `recipient` is not required to implement the {IERC777Recipient} interface if it is a contract.
Also emits a {Sent} event._
burn
function burn(uint256 amount, bytes data) public virtual
_See {IERC777-burn}.
Also emits a {IERC20-Transfer} event for ERC20 compatibility._
isOperatorFor
function isOperatorFor(address operator, address tokenHolder) public view virtual returns (bool)
See {IERC777-isOperatorFor}.
authorizeOperator
function authorizeOperator(address operator) public virtual
See {IERC777-authorizeOperator}.
revokeOperator
function revokeOperator(address operator) public virtual
See {IERC777-revokeOperator}.
defaultOperators
function defaultOperators() public view virtual returns (address[])
See {IERC777-defaultOperators}.
operatorSend
function operatorSend(address sender, address recipient, uint256 amount, bytes data, bytes operatorData) public virtual
_See {IERC777-operatorSend}.
Emits {Sent} and {IERC20-Transfer} events._
operatorBurn
function operatorBurn(address account, uint256 amount, bytes data, bytes operatorData) public virtual
_See {IERC777-operatorBurn}.
Emits {Burned} and {IERC20-Transfer} events._
allowance
function allowance(address holder, address spender) public view virtual returns (uint256)
_See {IERC20-allowance}.
Note that operator and allowance concepts are orthogonal: operators may not have allowance, and accounts with allowance may not be operators themselves._
approve
function approve(address spender, uint256 value) public virtual returns (bool)
_See {IERC20-approve}.
Note that accounts cannot have allowance issued by their operators._
transferFrom
function transferFrom(address holder, address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transferFrom}.
Note that operator and allowance concepts are orthogonal: operators cannot call `transferFrom` (unless they have allowance), and accounts with allowance cannot call `operatorSend` (unless they are operators).
Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events._
_mint
function _mint(address account, uint256 amount, bytes userData, bytes operatorData) internal virtual
_Creates `amount` tokens and assigns them to `account`, increasing the total supply.
If a send hook is registered for `account`, the corresponding function will be called with `operator`, `data` and `operatorData`.
See {IERC777Sender} and {IERC777Recipient}.
Emits {Minted} and {IERC20-Transfer} events.
Requirements
`account` cannot be the zero address.
if `account` is a contract, it must implement the {IERC777Recipient} interface._
_mint
function _mint(address account, uint256 amount, bytes userData, bytes operatorData, bool requireReceptionAck) internal virtual
_Creates `amount` tokens and assigns them to `account`, increasing the total supply.
If `requireReceptionAck` is set to true, and if a send hook is registered for `account`, the corresponding function will be called with `operator`, `data` and `operatorData`.
See {IERC777Sender} and {IERC777Recipient}.
Emits {Minted} and {IERC20-Transfer} events.
Requirements
`account` cannot be the zero address.
if `account` is a contract, it must implement the {IERC777Recipient} interface._
_send
function _send(address from, address to, uint256 amount, bytes userData, bytes operatorData, bool requireReceptionAck) internal virtual
Send tokens
from
address
address token holder address
to
address
address recipient address
amount
uint256
uint256 amount of tokens to transfer
userData
bytes
bytes extra information provided by the token holder (if any)
operatorData
bytes
bytes extra information provided by the operator (if any)
requireReceptionAck
bool
if true, contract recipients are required to implement ERC777TokensRecipient
_burn
function _burn(address from, uint256 amount, bytes data, bytes operatorData) internal virtual
Burn tokens
from
address
address token holder address
amount
uint256
uint256 amount of tokens to burn
data
bytes
bytes extra information provided by the token holder
operatorData
bytes
bytes extra information provided by the operator (if any)
_move
function _move(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) private
_approve
function _approve(address holder, address spender, uint256 value) internal
_See {ERC20-_approve}.
Note that accounts cannot have allowance issued by their operators._
_callTokensToSend
function _callTokensToSend(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) private
Call from.tokensToSend() if the interface is registered
operator
address
address operator requesting the transfer
from
address
address token holder address
to
address
address recipient address
amount
uint256
uint256 amount of tokens to transfer
userData
bytes
bytes extra information provided by the token holder (if any)
operatorData
bytes
bytes extra information provided by the operator (if any)
_callTokensReceived
function _callTokensReceived(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData, bool requireReceptionAck) private
Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but tokensReceived() was not registered for the recipient
operator
address
address operator requesting the transfer
from
address
address token holder address
to
address
address recipient address
amount
uint256
uint256 amount of tokens to transfer
userData
bytes
bytes extra information provided by the token holder (if any)
operatorData
bytes
bytes extra information provided by the operator (if any)
requireReceptionAck
bool
if true, contract recipients are required to implement ERC777TokensRecipient
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual
_Hook that is called before any token transfer. This includes calls to {send}, {transfer}, {operatorSend}, minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens will be to transferred to `to`.
when `from` is zero, `amount` tokens will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens will be burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
__gap
uint256[41] __gap
IERC777RecipientUpgradeable
_Interface of the ERC777TokensRecipient standard as defined in the EIP.
Accounts can be notified of {IERC777} tokens being sent to them by having a contract implement this interface (contract holders can be their own implementer) and registering it on the https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
See {IERC1820Registry} and {ERC1820Implementer}._
tokensReceived
function tokensReceived(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) external
_Called by an {IERC777} token contract whenever tokens are being moved or created into a registered account (`to`). The type of operation is conveyed by `from` being the zero address or not.
This call occurs after the token contract's state is updated, so {IERC777-balanceOf}, etc., can be used to query the post-operation state.
This function may revert to prevent the operation from being executed._
IERC777SenderUpgradeable
_Interface of the ERC777TokensSender standard as defined in the EIP.
{IERC777} Token holders can be notified of operations performed on their tokens by having a contract implement this interface (contract holders can be their own implementer) and registering it on the https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
See {IERC1820Registry} and {ERC1820Implementer}._
tokensToSend
function tokensToSend(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) external
_Called by an {IERC777} token contract whenever a registered holder's (`from`) tokens are about to be moved or destroyed. The type of operation is conveyed by `to` being the zero address or not.
This call occurs before the token contract's state is updated, so {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
This function may revert to prevent the operation from being executed._
IERC777Upgradeable
_Interface of the ERC777Token standard as defined in the EIP.
This contract uses the https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let token holders and recipients react to token movements by using setting implementers for the associated interfaces in said registry. See {IERC1820Registry} and {ERC1820Implementer}._
name
function name() external view returns (string)
Returns the name of the token.
symbol
function symbol() external view returns (string)
Returns the symbol of the token, usually a shorter version of the name.
granularity
function granularity() external view returns (uint256)
_Returns the smallest part of the token that is not divisible. This means all token operations (creation, movement and destruction) must have amounts that are a multiple of this number.
For most token contracts, this value will equal 1._
totalSupply
function totalSupply() external view returns (uint256)
Returns the amount of tokens in existence.
balanceOf
function balanceOf(address owner) external view returns (uint256)
Returns the amount of tokens owned by an account (`owner`).
send
function send(address recipient, uint256 amount, bytes data) external
_Moves `amount` tokens from the caller's account to `recipient`.
If send or receive hooks are registered for the caller and `recipient`, the corresponding functions will be called with `data` and empty `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
Emits a {Sent} event.
Requirements
the caller must have at least `amount` tokens.
`recipient` cannot be the zero address.
if `recipient` is a contract, it must implement the {IERC777Recipient} interface._
burn
function burn(uint256 amount, bytes data) external
_Destroys `amount` tokens from the caller's account, reducing the total supply.
If a send hook is registered for the caller, the corresponding function will be called with `data` and empty `operatorData`. See {IERC777Sender}.
Emits a {Burned} event.
Requirements
the caller must have at least `amount` tokens._
isOperatorFor
function isOperatorFor(address operator, address tokenHolder) external view returns (bool)
_Returns true if an account is an operator of `tokenHolder`. Operators can send and burn tokens on behalf of their owners. All accounts are their own operator.
See {operatorSend} and {operatorBurn}._
authorizeOperator
function authorizeOperator(address operator) external
_Make an account an operator of the caller.
See {isOperatorFor}.
Emits an {AuthorizedOperator} event.
Requirements
`operator` cannot be calling address._
revokeOperator
function revokeOperator(address operator) external
_Revoke an account's operator status for the caller.
See {isOperatorFor} and {defaultOperators}.
Emits a {RevokedOperator} event.
Requirements
`operator` cannot be calling address._
defaultOperators
function defaultOperators() external view returns (address[])
_Returns the list of default operators. These accounts are operators for all token holders, even if {authorizeOperator} was never called on them.
This list is immutable, but individual holders may revoke these via {revokeOperator}, in which case {isOperatorFor} will return false._
operatorSend
function operatorSend(address sender, address recipient, uint256 amount, bytes data, bytes operatorData) external
_Moves `amount` tokens from `sender` to `recipient`. The caller must be an operator of `sender`.
If send or receive hooks are registered for `sender` and `recipient`, the corresponding functions will be called with `data` and `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
Emits a {Sent} event.
Requirements
`sender` cannot be the zero address.
`sender` must have at least `amount` tokens.
the caller must be an operator for `sender`.
`recipient` cannot be the zero address.
if `recipient` is a contract, it must implement the {IERC777Recipient} interface._
operatorBurn
function operatorBurn(address account, uint256 amount, bytes data, bytes operatorData) external
_Destroys `amount` tokens from `account`, reducing the total supply. The caller must be an operator of `account`.
If a send hook is registered for `account`, the corresponding function will be called with `data` and `operatorData`. See {IERC777Sender}.
Emits a {Burned} event.
Requirements
`account` cannot be the zero address.
`account` must have at least `amount` tokens.
the caller must be an operator for `account`._
Sent
event Sent(address operator, address from, address to, uint256 amount, bytes data, bytes operatorData)
Minted
event Minted(address operator, address to, uint256 amount, bytes data, bytes operatorData)
Burned
event Burned(address operator, address from, uint256 amount, bytes data, bytes operatorData)
AuthorizedOperator
event AuthorizedOperator(address operator, address tokenHolder)
RevokedOperator
event RevokedOperator(address operator, address tokenHolder)
ERC777PresetFixedSupplyUpgradeable
_{ERC777} token, including:
Preminted initial supply
No access control mechanism (for minting/pausing) and hence no governance
Available since v3.4._
initialize
function initialize(string name, string symbol, address[] defaultOperators, uint256 initialSupply, address owner) public virtual
__ERC777PresetFixedSupply_init
function __ERC777PresetFixedSupply_init(string name, string symbol, address[] defaultOperators, uint256 initialSupply, address owner) internal
_Mints `initialSupply` amount of token and transfers them to `owner`.
See {ERC777-constructor}._
__ERC777PresetFixedSupply_init_unchained
function __ERC777PresetFixedSupply_init_unchained(string name, string symbol, address[] defaultOperators, uint256 initialSupply, address owner) internal
__gap
uint256[50] __gap
AddressUpgradeable
Collection of functions related to the address type
isContract
function isContract(address account) internal view returns (bool)
_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 ====_
sendValue
function sendValue(address payable recipient, uint256 amount) internal
_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]._
functionCall
function functionCall(address target, bytes data) internal returns (bytes)
_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._
functionCall
function functionCall(address target, bytes data, string errorMessage) internal returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with `errorMessage` as a fallback revert reason when `target` reverts.
Available since v3.1._
functionCallWithValue
function functionCallWithValue(address target, bytes data, uint256 value) internal returns (bytes)
_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._
functionCallWithValue
function functionCallWithValue(address target, bytes data, uint256 value, string errorMessage) internal returns (bytes)
_Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but with `errorMessage` as a fallback revert reason when `target` reverts.
Available since v3.1._
functionStaticCall
function functionStaticCall(address target, bytes data) internal view returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but performing a static call.
Available since v3.3._
functionStaticCall
function functionStaticCall(address target, bytes data, string errorMessage) internal view returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a static call.
Available since v3.3._
verifyCallResult
function verifyCallResult(bool success, bytes returndata, string errorMessage) internal pure returns (bytes)
_Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the revert reason using the provided one.
Available since v4.3._
ArraysUpgradeable
Collection of functions related to array types.
findUpperBound
function findUpperBound(uint256[] array, uint256 element) internal view returns (uint256)
_Searches a sorted `array` and returns the first index that contains a value greater or equal to `element`. If no such index exists (i.e. all values in the array are strictly less than `element`), the array length is returned. Time complexity O(log n).
`array` is expected to be sorted in ascending order, and to contain no repeated elements._
ContextUpgradeable
_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._
__Context_init
function __Context_init() internal
__Context_init_unchained
function __Context_init_unchained() internal
_msgSender
function _msgSender() internal view virtual returns (address)
_msgData
function _msgData() internal view virtual returns (bytes)
__gap
uint256[50] __gap
CountersUpgradeable
_Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number of elements in a mapping, issuing ERC721 ids, or counting request ids.
Include with `using Counters for Counters.Counter;`_
Counter
struct Counter {
uint256 _value;
}
current
function current(struct CountersUpgradeable.Counter counter) internal view returns (uint256)
increment
function increment(struct CountersUpgradeable.Counter counter) internal
decrement
function decrement(struct CountersUpgradeable.Counter counter) internal
reset
function reset(struct CountersUpgradeable.Counter counter) internal
MulticallUpgradeable
_Provides a function to batch together multiple calls in a single external call.
Available since v4.1._
__Multicall_init
function __Multicall_init() internal
__Multicall_init_unchained
function __Multicall_init_unchained() internal
multicall
function multicall(bytes[] data) external returns (bytes[] results)
Receives and executes a batch of function calls on this contract.
_functionDelegateCall
function _functionDelegateCall(address target, bytes data) private returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a delegate call.
Available since v3.4._
__gap
uint256[50] __gap
StorageSlotUpgradeable
_Library for reading and writing primitive types to specific storage slots.
Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. This library helps with reading and writing to such slots without the need for inline assembly.
The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
Example usage to set ERC1967 implementation slot: ``` contract ERC1967 { bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
} ```
Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
AddressSlot
struct AddressSlot {
address value;
}
BooleanSlot
struct BooleanSlot {
bool value;
}
Bytes32Slot
struct Bytes32Slot {
bytes32 value;
}
Uint256Slot
struct Uint256Slot {
uint256 value;
}
getAddressSlot
function getAddressSlot(bytes32 slot) internal pure returns (struct StorageSlotUpgradeable.AddressSlot r)
Returns an `AddressSlot` with member `value` located at `slot`.
getBooleanSlot
function getBooleanSlot(bytes32 slot) internal pure returns (struct StorageSlotUpgradeable.BooleanSlot r)
Returns an `BooleanSlot` with member `value` located at `slot`.
getBytes32Slot
function getBytes32Slot(bytes32 slot) internal pure returns (struct StorageSlotUpgradeable.Bytes32Slot r)
Returns an `Bytes32Slot` with member `value` located at `slot`.
getUint256Slot
function getUint256Slot(bytes32 slot) internal pure returns (struct StorageSlotUpgradeable.Uint256Slot r)
Returns an `Uint256Slot` with member `value` located at `slot`.
StringsUpgradeable
String operations.
_HEX_SYMBOLS
bytes16 _HEX_SYMBOLS
toString
function toString(uint256 value) internal pure returns (string)
Converts a `uint256` to its ASCII `string` decimal representation.
toHexString
function toHexString(uint256 value) internal pure returns (string)
Converts a `uint256` to its ASCII `string` hexadecimal representation.
toHexString
function toHexString(uint256 value, uint256 length) internal pure returns (string)
Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
TimersUpgradeable
Tooling for timepoints, timers and delays
Timestamp
struct Timestamp {
uint64 _deadline;
}
getDeadline
function getDeadline(struct TimersUpgradeable.Timestamp timer) internal pure returns (uint64)
setDeadline
function setDeadline(struct TimersUpgradeable.Timestamp timer, uint64 timestamp) internal
reset
function reset(struct TimersUpgradeable.Timestamp timer) internal
isUnset
function isUnset(struct TimersUpgradeable.Timestamp timer) internal pure returns (bool)
isStarted
function isStarted(struct TimersUpgradeable.Timestamp timer) internal pure returns (bool)
isPending
function isPending(struct TimersUpgradeable.Timestamp timer) internal view returns (bool)
isExpired
function isExpired(struct TimersUpgradeable.Timestamp timer) internal view returns (bool)
BlockNumber
struct BlockNumber {
uint64 _deadline;
}
getDeadline
function getDeadline(struct TimersUpgradeable.BlockNumber timer) internal pure returns (uint64)
setDeadline
function setDeadline(struct TimersUpgradeable.BlockNumber timer, uint64 timestamp) internal
reset
function reset(struct TimersUpgradeable.BlockNumber timer) internal
isUnset
function isUnset(struct TimersUpgradeable.BlockNumber timer) internal pure returns (bool)
isStarted
function isStarted(struct TimersUpgradeable.BlockNumber timer) internal pure returns (bool)
isPending
function isPending(struct TimersUpgradeable.BlockNumber timer) internal view returns (bool)
isExpired
function isExpired(struct TimersUpgradeable.BlockNumber timer) internal view returns (bool)
ECDSAUpgradeable
_Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
These functions can be used to verify that a message was signed by the holder of the private keys of a given address._
RecoverError
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
_throwError
function _throwError(enum ECDSAUpgradeable.RecoverError error) private pure
tryRecover
function tryRecover(bytes32 hash, bytes signature) internal pure returns (address, enum ECDSAUpgradeable.RecoverError)
_Returns the address that signed a hashed message (`hash`) with `signature` or error string. This address can then be used for verification purposes.
The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: this function rejects them by requiring the `s` value to be in the lower half order, and the `v` value to be either 27 or 28.
IMPORTANT: `hash` must be the result of a hash operation for the verification to be secure: it is possible to craft signatures that recover to arbitrary addresses for non-hashed data. A safe way to ensure this is by receiving a hash of the original message (which may otherwise be too long), and then calling {toEthSignedMessageHash} on it.
Documentation for signature generation:
with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
Available since v4.3._
recover
function recover(bytes32 hash, bytes signature) internal pure returns (address)
_Returns the address that signed a hashed message (`hash`) with `signature`. This address can then be used for verification purposes.
The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: this function rejects them by requiring the `s` value to be in the lower half order, and the `v` value to be either 27 or 28.
IMPORTANT: `hash` must be the result of a hash operation for the verification to be secure: it is possible to craft signatures that recover to arbitrary addresses for non-hashed data. A safe way to ensure this is by receiving a hash of the original message (which may otherwise be too long), and then calling {toEthSignedMessageHash} on it._
tryRecover
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, enum ECDSAUpgradeable.RecoverError)
_Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
Available since v4.3._
recover
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address)
_Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
Available since v4.2._
tryRecover
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, enum ECDSAUpgradeable.RecoverError)
_Overload of {ECDSA-tryRecover} that receives the `v`, `r` and `s` signature fields separately.
Available since v4.3._
recover
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address)
Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. /
toEthSignedMessageHash
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32)
_Returns an Ethereum Signed Message, created from a `hash`. This produces hash corresponding to the one signed with the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method as part of EIP-191.
See {recover}. /_
toTypedDataHash
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32)
_Returns an Ethereum Signed Typed Data, created from a `domainSeparator` and a `structHash`. This produces hash corresponding to the one signed with the https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
See {recover}. /_
SignatureCheckerUpgradeable
_Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with smart contract wallets such as Argent and Gnosis.
Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change through time. It could return true at block N and false at block N+1 (or the opposite).
Available since v4.1._
isValidSignatureNow
function isValidSignatureNow(address signer, bytes32 hash, bytes signature) internal view returns (bool)
EIP712Upgradeable
_https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in their contracts using a combination of `abi.encode` and `keccak256`.
This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA ({_hashTypedDataV4}).
The implementation of the domain separator was designed to be as efficient as possible while still properly updating the chain id to protect against replay attacks on an eventual fork of the chain.
NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
Available since v3.4._
_HASHED_NAME
bytes32 _HASHED_NAME
_HASHED_VERSION
bytes32 _HASHED_VERSION
_TYPE_HASH
bytes32 _TYPE_HASH
__EIP712_init
function __EIP712_init(string name, string version) internal
_Initializes the domain separator and parameter caches.
The meaning of `name` and `version` is specified in https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
`name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
`version`: the current major version of the signing domain.
NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart contract upgrade]._
__EIP712_init_unchained
function __EIP712_init_unchained(string name, string version) internal
_domainSeparatorV4
function _domainSeparatorV4() internal view returns (bytes32)
Returns the domain separator for the current chain.
_buildDomainSeparator
function _buildDomainSeparator(bytes32 typeHash, bytes32 nameHash, bytes32 versionHash) private view returns (bytes32)
_hashTypedDataV4
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32)
_Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this function returns the hash of the fully encoded EIP712 message for this domain.
This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
```solidity bytes32 digest = hashTypedDataV4(keccak256(abi.encode( keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents)) ))); address signer = ECDSA.recover(digest, signature); ```
_EIP712NameHash
function _EIP712NameHash() internal view virtual returns (bytes32)
_The hash of the name parameter for the EIP712 domain.
NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs are a concern._
_EIP712VersionHash
function _EIP712VersionHash() internal view virtual returns (bytes32)
_The hash of the version parameter for the EIP712 domain.
NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs are a concern._
__gap
uint256[50] __gap
ConditionalEscrowUpgradeable
Base abstract escrow to only allow withdrawal if a condition is met. Intended usage: See {Escrow}. Same usage guidelines apply here.
__ConditionalEscrow_init
function __ConditionalEscrow_init() internal
__ConditionalEscrow_init_unchained
function __ConditionalEscrow_init_unchained() internal
withdrawalAllowed
function withdrawalAllowed(address payee) public view virtual returns (bool)
Returns whether an address is allowed to withdraw their funds. To be implemented by derived contracts.
payee
address
The destination address of the funds.
withdraw
function withdraw(address payable payee) public virtual
_Withdraw accumulated balance for a payee, forwarding all gas to the recipient.
WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. Make sure you trust the recipient, or are either following the checks-effects-interactions pattern or using {ReentrancyGuard}._
payee
address payable
The address whose funds will be withdrawn and transferred to.
__gap
uint256[50] __gap
EscrowUpgradeable
_Base escrow contract, holds funds designated for a payee until they withdraw them.
Intended usage: This contract (and derived escrow contracts) should be a standalone contract, that only interacts with the contract that instantiated it. That way, it is guaranteed that all Ether will be handled according to the `Escrow` rules, and there is no need to check for payable functions or transfers in the inheritance tree. The contract that uses the escrow as its payment method should be its owner, and provide public methods redirecting to the escrow's deposit and withdraw._
initialize
function initialize() public virtual
__Escrow_init
function __Escrow_init() internal
__Escrow_init_unchained
function __Escrow_init_unchained() internal
Deposited
event Deposited(address payee, uint256 weiAmount)
Withdrawn
event Withdrawn(address payee, uint256 weiAmount)
_deposits
mapping(address => uint256) _deposits
depositsOf
function depositsOf(address payee) public view returns (uint256)
deposit
function deposit(address payee) public payable virtual
Stores the sent amount as credit to be withdrawn.
payee
address
The destination address of the funds.
withdraw
function withdraw(address payable payee) public virtual
_Withdraw accumulated balance for a payee, forwarding all gas to the recipient.
WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. Make sure you trust the recipient, or are either following the checks-effects-interactions pattern or using {ReentrancyGuard}._
payee
address payable
The address whose funds will be withdrawn and transferred to.
__gap
uint256[49] __gap
RefundEscrowUpgradeable
Escrow that holds funds for a beneficiary, deposited from multiple parties. Intended usage: See {Escrow}. Same usage guidelines apply here. The owner account (that is, the contract that instantiates this contract) may deposit, close the deposit period, and allow for either withdrawal by the beneficiary, or refunds to the depositors. All interactions with `RefundEscrow` will be made through the owner contract.
State
enum State {
Active,
Refunding,
Closed
}
RefundsClosed
event RefundsClosed()
RefundsEnabled
event RefundsEnabled()
_state
enum RefundEscrowUpgradeable.State _state
_beneficiary
address payable _beneficiary
__RefundEscrow_init
function __RefundEscrow_init(address payable beneficiary_) internal
Constructor.
beneficiary_
address payable
The beneficiary of the deposits.
__RefundEscrow_init_unchained
function __RefundEscrow_init_unchained(address payable beneficiary_) internal
state
function state() public view virtual returns (enum RefundEscrowUpgradeable.State)
[0]
enum RefundEscrowUpgradeable.State
The current state of the escrow.
beneficiary
function beneficiary() public view virtual returns (address payable)
[0]
address payable
The beneficiary of the escrow.
deposit
function deposit(address refundee) public payable virtual
Stores funds that may later be refunded.
refundee
address
The address funds will be sent to if a refund occurs.
close
function close() public virtual
Allows for the beneficiary to withdraw their funds, rejecting further deposits.
enableRefunds
function enableRefunds() public virtual
Allows for refunds to take place, rejecting further deposits.
beneficiaryWithdraw
function beneficiaryWithdraw() public virtual
Withdraws the beneficiary's funds.
withdrawalAllowed
function withdrawalAllowed(address) public view returns (bool)
Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a 'payee' argument, but we ignore it here since the condition is global, not per-payee.
__gap
uint256[49] __gap
ERC165CheckerUpgradeable
_Library used to query support of an interface declared via {IERC165}.
Note that these functions return the actual result of the query: they do not `revert` if an interface is not supported. It is up to the caller to decide what to do in these cases._
_INTERFACE_ID_INVALID
bytes4 _INTERFACE_ID_INVALID
supportsERC165
function supportsERC165(address account) internal view returns (bool)
Returns true if `account` supports the {IERC165} interface,
supportsInterface
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool)
_Returns true if `account` supports the interface defined by `interfaceId`. Support for {IERC165} itself is queried automatically.
See {IERC165-supportsInterface}._
getSupportedInterfaces
function getSupportedInterfaces(address account, bytes4[] interfaceIds) internal view returns (bool[])
_Returns a boolean array where each value corresponds to the interfaces passed in and whether they're supported or not. This allows you to batch check interfaces for a contract where your expectation is that some interfaces may not be supported.
See {IERC165-supportsInterface}.
Available since v3.4._
supportsAllInterfaces
function supportsAllInterfaces(address account, bytes4[] interfaceIds) internal view returns (bool)
_Returns true if `account` supports all the interfaces defined in `interfaceIds`. Support for {IERC165} itself is queried automatically.
Batch-querying can lead to gas savings by skipping repeated checks for {IERC165} support.
See {IERC165-supportsInterface}._
_supportsERC165Interface
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool)
Query if a contract implements an interface, does not check ERC165 support
Assumes that account contains a contract that supports ERC165, otherwise the behavior of this method is undefined. This precondition can be checked with {supportsERC165}. Interface identification is specified in ERC-165.
account
address
The address of the contract to query for support of an interface
interfaceId
bytes4
The interface identifier, as specified in ERC-165
[0]
bool
true if the contract at account indicates support of the interface with identifier interfaceId, false otherwise
ERC165StorageUpgradeable
_Storage based implementation of the {IERC165} interface.
Contracts may inherit from this and call {registerInterface} to declare their support of an interface.
__ERC165Storage_init
function __ERC165Storage_init() internal
__ERC165Storage_init_unchained
function __ERC165Storage_init_unchained() internal
_supportedInterfaces
mapping(bytes4 => bool) _supportedInterfaces
Mapping of interface ids to whether or not it's supported.
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
_registerInterface
function _registerInterface(bytes4 interfaceId) internal virtual
_Registers the contract as an implementer of the interface defined by `interfaceId`. Support of the actual ERC165 interface is automatic and registering its interface id is not required.
See {IERC165-supportsInterface}.
Requirements:
`interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`)._
__gap
uint256[49] __gap
ERC165Upgradeable
_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._
__ERC165_init
function __ERC165_init() internal
__ERC165_init_unchained
function __ERC165_init_unchained() internal
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
__gap
uint256[50] __gap
ERC1820ImplementerUpgradeable
_Implementation of the {IERC1820Implementer} interface.
Contracts may inherit from this and call {registerInterfaceForAddress} to declare their willingness to be implementers. {IERC1820Registry-setInterfaceImplementer} should then be called for the registration to be complete.
__ERC1820Implementer_init
function __ERC1820Implementer_init() internal
__ERC1820Implementer_init_unchained
function __ERC1820Implementer_init_unchained() internal
_ERC1820_ACCEPT_MAGIC
bytes32 _ERC1820_ACCEPT_MAGIC
_supportedInterfaces
mapping(bytes32 => mapping(address => bool)) _supportedInterfaces
canImplementInterfaceForAddress
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) public view virtual returns (bytes32)
See {IERC1820Implementer-canImplementInterfaceForAddress}.
_registerInterfaceForAddress
function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual
_Declares the contract as willing to be an implementer of `interfaceHash` for `account`.
See {IERC1820Registry-setInterfaceImplementer} and {IERC1820Registry-interfaceHash}._
__gap
uint256[49] __gap
IERC165Upgradeable
_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}._
supportsInterface
function supportsInterface(bytes4 interfaceId) external view returns (bool)
_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._
IERC1820ImplementerUpgradeable
Interface for an ERC1820 implementer, as defined in the https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. Used by contracts that will be registered as implementers in the {IERC1820Registry}.
canImplementInterfaceForAddress
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32)
_Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract implements `interfaceHash` for `account`.
See {IERC1820Registry-setInterfaceImplementer}._
IERC1820RegistryUpgradeable
_Interface of the global ERC1820 Registry, as defined in the https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register implementers for interfaces in this registry, as well as query support.
Implementers may be shared by multiple accounts, and can also implement more than a single interface for each account. Contracts can implement interfaces for themselves, but externally-owned accounts (EOA) must delegate this to a contract.
{IERC165} interfaces can also be queried via the registry.
For an in-depth explanation and source code analysis, see the EIP text._
setManager
function setManager(address account, address newManager) external
_Sets `newManager` as the manager for `account`. A manager of an account is able to set interface implementers for it.
By default, each account is its own manager. Passing a value of `0x0` in `newManager` will reset the manager to this initial state.
Emits a {ManagerChanged} event.
Requirements:
the caller must be the current manager for `account`._
getManager
function getManager(address account) external view returns (address)
_Returns the manager for `account`.
See {setManager}._
setInterfaceImplementer
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external
_Sets the `implementer` contract as ``account``'s implementer for `interfaceHash`.
`account` being the zero address is an alias for the caller's address. The zero address can also be used in `implementer` to remove an old one.
See {interfaceHash} to learn how these are created.
Emits an {InterfaceImplementerSet} event.
Requirements:
the caller must be the current manager for `account`.
`interfaceHash` must not be an {IERC165} interface id (i.e. it must not end in 28 zeroes).
`implementer` must implement {IERC1820Implementer} and return true when queried for support, unless `implementer` is the caller. See {IERC1820Implementer-canImplementInterfaceForAddress}._
getInterfaceImplementer
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address)
_Returns the implementer of `interfaceHash` for `account`. If no such implementer is registered, returns the zero address.
If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 zeroes), `account` will be queried for support of it.
`account` being the zero address is an alias for the caller's address._
interfaceHash
function interfaceHash(string interfaceName) external pure returns (bytes32)
Returns the interface hash for an `interfaceName`, as defined in the corresponding https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
updateERC165Cache
function updateERC165Cache(address account, bytes4 interfaceId) external
Updates the cache with whether the contract implements an ERC165 interface or not.
account
address
Address of the contract for which to update the cache.
interfaceId
bytes4
ERC165 interface for which to update the cache.
implementsERC165Interface
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool)
Checks whether a contract implements an ERC165 interface or not. If the result is not cached a direct lookup on the contract address is performed. If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling {updateERC165Cache} with the contract address.
account
address
Address of the contract to check.
interfaceId
bytes4
ERC165 interface to check.
[0]
bool
True if `account` implements `interfaceId`, false otherwise.
implementsERC165InterfaceNoCache
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool)
Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
account
address
Address of the contract to check.
interfaceId
bytes4
ERC165 interface to check.
[0]
bool
True if `account` implements `interfaceId`, false otherwise.
InterfaceImplementerSet
event InterfaceImplementerSet(address account, bytes32 interfaceHash, address implementer)
ManagerChanged
event ManagerChanged(address account, address newManager)
MathUpgradeable
Standard math utilities missing in the Solidity language.
max
function max(uint256 a, uint256 b) internal pure returns (uint256)
Returns the largest of two numbers.
min
function min(uint256 a, uint256 b) internal pure returns (uint256)
Returns the smallest of two numbers.
average
function average(uint256 a, uint256 b) internal pure returns (uint256)
Returns the average of two numbers. The result is rounded towards zero.
ceilDiv
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the ceiling of the division of two numbers.
This differs from standard division with `/` in that it rounds up instead of rounding down._
SafeCastUpgradeable
_Wrappers over Solidity's uintXX/intXX casting operators with added overflow checks.
Downcasting from uint256/int256 in Solidity does not revert on overflow. This can easily result in undesired exploitation or bugs, since developers usually assume that overflows raise errors. `SafeCast` restores this intuition by reverting the transaction when such an operation overflows.
Using this library instead of the unchecked operations eliminates an entire class of bugs, so it's recommended to use it always.
Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing all math on `uint256` and `int256` and then downcasting._
toUint224
function toUint224(uint256 value) internal pure returns (uint224)
_Returns the downcasted uint224 from uint256, reverting on overflow (when the input is greater than largest uint224).
Counterpart to Solidity's `uint224` operator.
Requirements:
input must fit into 224 bits_
toUint128
function toUint128(uint256 value) internal pure returns (uint128)
_Returns the downcasted uint128 from uint256, reverting on overflow (when the input is greater than largest uint128).
Counterpart to Solidity's `uint128` operator.
Requirements:
input must fit into 128 bits_
toUint96
function toUint96(uint256 value) internal pure returns (uint96)
_Returns the downcasted uint96 from uint256, reverting on overflow (when the input is greater than largest uint96).
Counterpart to Solidity's `uint96` operator.
Requirements:
input must fit into 96 bits_
toUint64
function toUint64(uint256 value) internal pure returns (uint64)
_Returns the downcasted uint64 from uint256, reverting on overflow (when the input is greater than largest uint64).
Counterpart to Solidity's `uint64` operator.
Requirements:
input must fit into 64 bits_
toUint32
function toUint32(uint256 value) internal pure returns (uint32)
_Returns the downcasted uint32 from uint256, reverting on overflow (when the input is greater than largest uint32).
Counterpart to Solidity's `uint32` operator.
Requirements:
input must fit into 32 bits_
toUint16
function toUint16(uint256 value) internal pure returns (uint16)
_Returns the downcasted uint16 from uint256, reverting on overflow (when the input is greater than largest uint16).
Counterpart to Solidity's `uint16` operator.
Requirements:
input must fit into 16 bits_
toUint8
function toUint8(uint256 value) internal pure returns (uint8)
_Returns the downcasted uint8 from uint256, reverting on overflow (when the input is greater than largest uint8).
Counterpart to Solidity's `uint8` operator.
Requirements:
input must fit into 8 bits._
toUint256
function toUint256(int256 value) internal pure returns (uint256)
_Converts a signed int256 into an unsigned uint256.
Requirements:
input must be greater than or equal to 0._
toInt128
function toInt128(int256 value) internal pure returns (int128)
_Returns the downcasted int128 from int256, reverting on overflow (when the input is less than smallest int128 or greater than largest int128).
Counterpart to Solidity's `int128` operator.
Requirements:
input must fit into 128 bits
Available since v3.1._
toInt64
function toInt64(int256 value) internal pure returns (int64)
_Returns the downcasted int64 from int256, reverting on overflow (when the input is less than smallest int64 or greater than largest int64).
Counterpart to Solidity's `int64` operator.
Requirements:
input must fit into 64 bits
Available since v3.1._
toInt32
function toInt32(int256 value) internal pure returns (int32)
_Returns the downcasted int32 from int256, reverting on overflow (when the input is less than smallest int32 or greater than largest int32).
Counterpart to Solidity's `int32` operator.
Requirements:
input must fit into 32 bits
Available since v3.1._
toInt16
function toInt16(int256 value) internal pure returns (int16)
_Returns the downcasted int16 from int256, reverting on overflow (when the input is less than smallest int16 or greater than largest int16).
Counterpart to Solidity's `int16` operator.
Requirements:
input must fit into 16 bits
Available since v3.1._
toInt8
function toInt8(int256 value) internal pure returns (int8)
_Returns the downcasted int8 from int256, reverting on overflow (when the input is less than smallest int8 or greater than largest int8).
Counterpart to Solidity's `int8` operator.
Requirements:
input must fit into 8 bits.
Available since v3.1._
toInt256
function toInt256(uint256 value) internal pure returns (int256)
_Converts an unsigned uint256 into a signed int256.
Requirements:
input must be less than or equal to maxInt256._
SafeMathUpgradeable
_Wrappers over Solidity's arithmetic operations.
NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler now has built in overflow checking._
tryAdd
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the addition of two unsigned integers, with an overflow flag.
Available since v3.4._
trySub
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the substraction of two unsigned integers, with an overflow flag.
Available since v3.4._
tryMul
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the multiplication of two unsigned integers, with an overflow flag.
Available since v3.4._
tryDiv
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the division of two unsigned integers, with a division by zero flag.
Available since v3.4._
tryMod
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the remainder of dividing two unsigned integers, with a division by zero flag.
Available since v3.4._
add
function add(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the addition of two unsigned integers, reverting on overflow.
Counterpart to Solidity's `+` operator.
Requirements:
Addition cannot overflow._
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the subtraction of two unsigned integers, reverting on overflow (when the result is negative).
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the multiplication of two unsigned integers, reverting on overflow.
Counterpart to Solidity's `*` operator.
Requirements:
Multiplication cannot overflow._
div
function div(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the integer division of two unsigned integers, reverting on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator.
Requirements:
The divisor cannot be zero._
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting when dividing by zero.
Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
sub
function sub(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the subtraction of two unsigned integers, reverting with custom message on overflow (when the result is negative).
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {trySub}.
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
div
function div(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the integer division of two unsigned integers, reverting with custom message on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator. Note: this function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
mod
function mod(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting with custom message when dividing by zero.
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryMod}.
Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
EnumerableMapUpgradeable
_Library for managing an enumerable variant of Solidity's https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] type.
Maps have the following properties:
Entries are added, removed, and checked for existence in constant time (O(1)).
Entries are enumerated in O(n). No guarantees are made on the ordering.
``` contract Example { // Add the library methods using EnumerableMap for EnumerableMap.UintToAddressMap;
// Declare a set state variable
EnumerableMap.UintToAddressMap private myMap;
} ```
As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are supported._
Map
struct Map {
struct EnumerableSetUpgradeable.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
_set
function _set(struct EnumerableMapUpgradeable.Map map, bytes32 key, bytes32 value) private returns (bool)
_Adds a key-value pair to a map, or updates the value for an existing key. O(1).
Returns true if the key was added to the map, that is if it was not already present._
_remove
function _remove(struct EnumerableMapUpgradeable.Map map, bytes32 key) private returns (bool)
_Removes a key-value pair from a map. O(1).
Returns true if the key was removed from the map, that is if it was present._
_contains
function _contains(struct EnumerableMapUpgradeable.Map map, bytes32 key) private view returns (bool)
Returns true if the key is in the map. O(1).
_length
function _length(struct EnumerableMapUpgradeable.Map map) private view returns (uint256)
Returns the number of key-value pairs in the map. O(1).
_at
function _at(struct EnumerableMapUpgradeable.Map map, uint256 index) private view returns (bytes32, bytes32)
_Returns the key-value pair stored at position `index` in the map. O(1).
Note that there are no guarantees on the ordering of entries inside the array, and it may change when more entries are added or removed.
Requirements:
`index` must be strictly less than {length}._
_tryGet
function _tryGet(struct EnumerableMapUpgradeable.Map map, bytes32 key) private view returns (bool, bytes32)
Tries to returns the value associated with `key`. O(1). Does not revert if `key` is not in the map.
_get
function _get(struct EnumerableMapUpgradeable.Map map, bytes32 key) private view returns (bytes32)
_Returns the value associated with `key`. O(1).
Requirements:
`key` must be in the map._
_get
function _get(struct EnumerableMapUpgradeable.Map map, bytes32 key, string errorMessage) private view returns (bytes32)
_Same as {_get}, with a custom error message when `key` is not in the map.
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryGet}.
UintToAddressMap
struct UintToAddressMap {
struct EnumerableMapUpgradeable.Map _inner;
}
set
function set(struct EnumerableMapUpgradeable.UintToAddressMap map, uint256 key, address value) internal returns (bool)
_Adds a key-value pair to a map, or updates the value for an existing key. O(1).
Returns true if the key was added to the map, that is if it was not already present._
remove
function remove(struct EnumerableMapUpgradeable.UintToAddressMap map, uint256 key) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the key was removed from the map, that is if it was present._
contains
function contains(struct EnumerableMapUpgradeable.UintToAddressMap map, uint256 key) internal view returns (bool)
Returns true if the key is in the map. O(1).
length
function length(struct EnumerableMapUpgradeable.UintToAddressMap map) internal view returns (uint256)
Returns the number of elements in the map. O(1).
at
function at(struct EnumerableMapUpgradeable.UintToAddressMap map, uint256 index) internal view returns (uint256, address)
_Returns the element stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed.
Requirements:
`index` must be strictly less than {length}._
tryGet
function tryGet(struct EnumerableMapUpgradeable.UintToAddressMap map, uint256 key) internal view returns (bool, address)
_Tries to returns the value associated with `key`. O(1). Does not revert if `key` is not in the map.
Available since v3.4._
get
function get(struct EnumerableMapUpgradeable.UintToAddressMap map, uint256 key) internal view returns (address)
_Returns the value associated with `key`. O(1).
Requirements:
`key` must be in the map._
get
function get(struct EnumerableMapUpgradeable.UintToAddressMap map, uint256 key, string errorMessage) internal view returns (address)
_Same as {get}, with a custom error message when `key` is not in the map.
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryGet}._
EnumerableSetUpgradeable
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._
Set
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
_add
function _add(struct EnumerableSetUpgradeable.Set set, bytes32 value) private returns (bool)
_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._
_remove
function _remove(struct EnumerableSetUpgradeable.Set set, bytes32 value) private returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
_contains
function _contains(struct EnumerableSetUpgradeable.Set set, bytes32 value) private view returns (bool)
Returns true if the value is in the set. O(1).
_length
function _length(struct EnumerableSetUpgradeable.Set set) private view returns (uint256)
Returns the number of values on the set. O(1).
_at
function _at(struct EnumerableSetUpgradeable.Set set, uint256 index) private view returns (bytes32)
_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}._
_values
function _values(struct EnumerableSetUpgradeable.Set set) private view returns (bytes32[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
Bytes32Set
struct Bytes32Set {
struct EnumerableSetUpgradeable.Set _inner;
}
add
function add(struct EnumerableSetUpgradeable.Bytes32Set set, bytes32 value) internal returns (bool)
_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._
remove
function remove(struct EnumerableSetUpgradeable.Bytes32Set set, bytes32 value) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
contains
function contains(struct EnumerableSetUpgradeable.Bytes32Set set, bytes32 value) internal view returns (bool)
Returns true if the value is in the set. O(1).
length
function length(struct EnumerableSetUpgradeable.Bytes32Set set) internal view returns (uint256)
Returns the number of values in the set. O(1).
at
function at(struct EnumerableSetUpgradeable.Bytes32Set set, uint256 index) internal view returns (bytes32)
_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}._
values
function values(struct EnumerableSetUpgradeable.Bytes32Set set) internal view returns (bytes32[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
AddressSet
struct AddressSet {
struct EnumerableSetUpgradeable.Set _inner;
}
add
function add(struct EnumerableSetUpgradeable.AddressSet set, address value) internal returns (bool)
_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._
remove
function remove(struct EnumerableSetUpgradeable.AddressSet set, address value) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
contains
function contains(struct EnumerableSetUpgradeable.AddressSet set, address value) internal view returns (bool)
Returns true if the value is in the set. O(1).
length
function length(struct EnumerableSetUpgradeable.AddressSet set) internal view returns (uint256)
Returns the number of values in the set. O(1).
at
function at(struct EnumerableSetUpgradeable.AddressSet set, uint256 index) internal view returns (address)
_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}._
values
function values(struct EnumerableSetUpgradeable.AddressSet set) internal view returns (address[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
UintSet
struct UintSet {
struct EnumerableSetUpgradeable.Set _inner;
}
add
function add(struct EnumerableSetUpgradeable.UintSet set, uint256 value) internal returns (bool)
_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._
remove
function remove(struct EnumerableSetUpgradeable.UintSet set, uint256 value) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
contains
function contains(struct EnumerableSetUpgradeable.UintSet set, uint256 value) internal view returns (bool)
Returns true if the value is in the set. O(1).
length
function length(struct EnumerableSetUpgradeable.UintSet set) internal view returns (uint256)
Returns the number of values on the set. O(1).
at
function at(struct EnumerableSetUpgradeable.UintSet set, uint256 index) internal view returns (uint256)
_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}._
values
function values(struct EnumerableSetUpgradeable.UintSet set) internal view returns (uint256[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
AccessControl
_Contract module that allows children to implement role-based access control mechanisms. This is a lightweight version that doesn't allow enumerating role members except through off-chain means by accessing the contract event logs. Some applications may benefit from on-chain enumerability, for those cases see {AccessControlEnumerable}.
Roles are referred to by their `bytes32` identifier. These should be exposed in the external API and be unique. The best way to achieve this is by using `public constant` hash digests:
``` bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); ```
Roles can be used to represent a set of permissions. To restrict access to a function call, use {hasRole}:
``` function foo() public { require(hasRole(MY_ROLE, msg.sender)); ... } ```
Roles can be granted and revoked dynamically via the {grantRole} and {revokeRole} functions. Each role has an associated admin role, and only accounts that have a role's admin role can call {grantRole} and {revokeRole}.
By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means that only accounts with this role will be able to grant or revoke other roles. More complex role relationships can be created by using {_setRoleAdmin}.
WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to grant and revoke this role. Extra precautions should be taken to secure accounts that have been granted it._
RoleData
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
_roles
mapping(bytes32 => struct AccessControl.RoleData) _roles
DEFAULT_ADMIN_ROLE
bytes32 DEFAULT_ADMIN_ROLE
onlyRole
modifier onlyRole(bytes32 role)
_Modifier that checks that an account has a specific role. Reverts with a standardized message including the required role.
The format of the revert reason is given by the following regular expression:
/^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
Available since v4.1._
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
hasRole
function hasRole(bytes32 role, address account) public view returns (bool)
Returns `true` if `account` has been granted `role`.
_checkRole
function _checkRole(bytes32 role, address account) internal view
_Revert with a standard message if `account` is missing `role`.
The format of the revert reason is given by the following regular expression:
/^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/_
getRoleAdmin
function getRoleAdmin(bytes32 role) public view returns (bytes32)
_Returns the admin role that controls `role`. See {grantRole} and {revokeRole}.
To change a role's admin, use {setRoleAdmin}.
grantRole
function grantRole(bytes32 role, address account) public virtual
_Grants `role` to `account`.
If `account` had not been already granted `role`, emits a {RoleGranted} event.
Requirements:
the caller must have ``role``'s admin role._
revokeRole
function revokeRole(bytes32 role, address account) public virtual
_Revokes `role` from `account`.
If `account` had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must have ``role``'s admin role._
renounceRole
function renounceRole(bytes32 role, address account) public virtual
_Revokes `role` from the calling account.
Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced).
If the calling account had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must be `account`._
_setupRole
function _setupRole(bytes32 role, address account) internal virtual
_Grants `role` to `account`.
If `account` had not been already granted `role`, emits a {RoleGranted} event. Note that unlike {grantRole}, this function doesn't perform any checks on the calling account.
[WARNING] ==== This function should only be called from the constructor when setting up the initial roles for the system.
Using this function in any other way is effectively circumventing the admin system imposed by {AccessControl}. ====_
_setRoleAdmin
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual
_Sets `adminRole` as ``role``'s admin role.
Emits a {RoleAdminChanged} event._
_grantRole
function _grantRole(bytes32 role, address account) private
_revokeRole
function _revokeRole(bytes32 role, address account) private
AccessControlEnumerable
Extension of {AccessControl} that allows enumerating the members of each role.
_roleMembers
mapping(bytes32 => struct EnumerableSet.AddressSet) _roleMembers
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
getRoleMember
function getRoleMember(bytes32 role, uint256 index) public view returns (address)
_Returns one of the accounts that have `role`. `index` must be a value between 0 and {getRoleMemberCount}, non-inclusive.
Role bearers are not sorted in any particular way, and their ordering may change at any point.
WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure you perform all queries on the same block. See the following https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] for more information._
getRoleMemberCount
function getRoleMemberCount(bytes32 role) public view returns (uint256)
Returns the number of accounts that have `role`. Can be used together with {getRoleMember} to enumerate all bearers of a role.
grantRole
function grantRole(bytes32 role, address account) public virtual
Overload {grantRole} to track enumerable memberships
revokeRole
function revokeRole(bytes32 role, address account) public virtual
Overload {revokeRole} to track enumerable memberships
renounceRole
function renounceRole(bytes32 role, address account) public virtual
Overload {renounceRole} to track enumerable memberships
_setupRole
function _setupRole(bytes32 role, address account) internal virtual
_Overload {setupRole} to track enumerable memberships
IAccessControl
External interface of AccessControl declared to support ERC165 detection.
RoleAdminChanged
event RoleAdminChanged(bytes32 role, bytes32 previousAdminRole, bytes32 newAdminRole)
_Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
`DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite {RoleAdminChanged} not being emitted signaling this.
Available since v3.1._
RoleGranted
event RoleGranted(bytes32 role, address account, address sender)
_Emitted when `account` is granted `role`.
`sender` is the account that originated the contract call, an admin role bearer except when using {AccessControl-setupRole}.
RoleRevoked
event RoleRevoked(bytes32 role, address account, address sender)
_Emitted when `account` is revoked `role`.
`sender` is the account that originated the contract call:
if using `revokeRole`, it is the admin role bearer
if using `renounceRole`, it is the role bearer (i.e. `account`)_
hasRole
function hasRole(bytes32 role, address account) external view returns (bool)
Returns `true` if `account` has been granted `role`.
getRoleAdmin
function getRoleAdmin(bytes32 role) external view returns (bytes32)
_Returns the admin role that controls `role`. See {grantRole} and {revokeRole}.
To change a role's admin, use {AccessControl-setRoleAdmin}.
grantRole
function grantRole(bytes32 role, address account) external
_Grants `role` to `account`.
If `account` had not been already granted `role`, emits a {RoleGranted} event.
Requirements:
the caller must have ``role``'s admin role._
revokeRole
function revokeRole(bytes32 role, address account) external
_Revokes `role` from `account`.
If `account` had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must have ``role``'s admin role._
renounceRole
function renounceRole(bytes32 role, address account) external
_Revokes `role` from the calling account.
Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced).
If the calling account had been granted `role`, emits a {RoleRevoked} event.
Requirements:
the caller must be `account`._
IAccessControlEnumerable
External interface of AccessControlEnumerable declared to support ERC165 detection.
getRoleMember
function getRoleMember(bytes32 role, uint256 index) external view returns (address)
_Returns one of the accounts that have `role`. `index` must be a value between 0 and {getRoleMemberCount}, non-inclusive.
Role bearers are not sorted in any particular way, and their ordering may change at any point.
WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure you perform all queries on the same block. See the following https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] for more information._
getRoleMemberCount
function getRoleMemberCount(bytes32 role) external view returns (uint256)
Returns the number of accounts that have `role`. Can be used together with {getRoleMember} to enumerate all bearers of a role.
Ownable
_Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions.
By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}.
This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner._
_owner
address _owner
OwnershipTransferred
event OwnershipTransferred(address previousOwner, address newOwner)
constructor
constructor() internal
Initializes the contract setting the deployer as the initial owner.
owner
function owner() public view virtual returns (address)
Returns the address of the current owner.
onlyOwner
modifier onlyOwner()
Throws if called by any account other than the owner.
renounceOwnership
function renounceOwnership() public virtual
_Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner.
NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner._
transferOwnership
function transferOwnership(address newOwner) public virtual
Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.
_setOwner
function _setOwner(address newOwner) private
PaymentSplitter
_This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware that the Ether will be split in this way, since it is handled transparently by the contract.
The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim an amount proportional to the percentage of total shares they were assigned.
`PaymentSplitter` follows a pull payment model. This means that payments are not automatically forwarded to the accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} function._
PayeeAdded
event PayeeAdded(address account, uint256 shares)
PaymentReleased
event PaymentReleased(address to, uint256 amount)
PaymentReceived
event PaymentReceived(address from, uint256 amount)
_totalShares
uint256 _totalShares
_totalReleased
uint256 _totalReleased
_shares
mapping(address => uint256) _shares
_released
mapping(address => uint256) _released
_payees
address[] _payees
constructor
constructor(address[] payees, uint256[] shares_) public payable
_Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at the matching position in the `shares` array.
All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no duplicates in `payees`._
receive
receive() external payable virtual
_The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the reliability of the events, and not the actual splitting of Ether.
To learn more about this see the Solidity documentation for https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback functions]._
totalShares
function totalShares() public view returns (uint256)
Getter for the total shares held by payees.
totalReleased
function totalReleased() public view returns (uint256)
Getter for the total amount of Ether already released.
shares
function shares(address account) public view returns (uint256)
Getter for the amount of shares held by an account.
released
function released(address account) public view returns (uint256)
Getter for the amount of Ether already released to a payee.
payee
function payee(uint256 index) public view returns (address)
Getter for the address of the payee number `index`.
release
function release(address payable account) public virtual
Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the total shares and their previous withdrawals.
_addPayee
function _addPayee(address account, uint256 shares_) private
Add a new payee to the contract.
account
address
The address of the payee to add.
shares_
uint256
The number of shares owned by the payee.
Governor
_Core of the governance system, designed to be extended though various modules.
This contract is abstract and requires several function to be implemented in various modules:
A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
A voting module must implement {getVotes}
Additionanly, the {votingPeriod} must also be implemented
Available since v4.3._
BALLOT_TYPEHASH
bytes32 BALLOT_TYPEHASH
ProposalCore
struct ProposalCore {
struct Timers.BlockNumber voteStart;
struct Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
_name
string _name
_proposals
mapping(uint256 => struct Governor.ProposalCore) _proposals
onlyGovernance
modifier onlyGovernance()
_Restrict access to governor executing address. Some module might override the executor function to make sure this modifier is consistant with the execution model.
constructor
constructor(string name_) internal
Sets the value for {name} and {version}
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
name
function name() public view virtual returns (string)
See {IGovernor-name}.
version
function version() public view virtual returns (string)
See {IGovernor-version}.
hashProposal
function hashProposal(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public pure virtual returns (uint256)
_See {IGovernor-hashProposal}.
The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in advance, before the proposal is submitted.
Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the same proposal (with same operation and same description) will have the same id if submitted on multiple governors accross multiple networks. This also means that in order to execute the same operation twice (on the same governor) the proposer will have to change the description in order to avoid proposal id conflicts._
state
function state(uint256 proposalId) public view virtual returns (enum IGovernor.ProposalState)
See {IGovernor-state}.
proposalSnapshot
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256)
See {IGovernor-proposalSnapshot}.
proposalDeadline
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256)
See {IGovernor-proposalDeadline}.
_quorumReached
function _quorumReached(uint256 proposalId) internal view virtual returns (bool)
Amount of votes already cast passes the threshold limit.
_voteSucceeded
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool)
Is the proposal successful or not.
_countVote
function _countVote(uint256 proposalId, address account, uint8 support, uint256 weight) internal virtual
_Register a vote with a given support and voting weight.
Note: Support is generic and can represent various things depending on the voting system used._
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernor-propose}.
execute
function execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public payable virtual returns (uint256)
See {IGovernor-execute}.
_execute
function _execute(uint256, address[] targets, uint256[] values, bytes[] calldatas, bytes32) internal virtual
Internal execution mechanism. Can be overriden to implement different execution mechanism
_cancel
function _cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual returns (uint256)
_Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as canceled to allow distinguishing it from executed proposals.
Emits a {IGovernor-ProposalCanceled} event._
castVote
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256)
See {IGovernor-castVote}.
castVoteWithReason
function castVoteWithReason(uint256 proposalId, uint8 support, string reason) public virtual returns (uint256)
See {IGovernor-castVoteWithReason}.
castVoteBySig
function castVoteBySig(uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public virtual returns (uint256)
See {IGovernor-castVoteBySig}.
_castVote
function _castVote(uint256 proposalId, address account, uint8 support, string reason) internal virtual returns (uint256)
_Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
Emits a {IGovernor-VoteCast} event._
_executor
function _executor() internal view virtual returns (address)
Address through which the governor executes action. Will be overloaded by module that execute actions through another contract such as a timelock.
IGovernor
_Interface of the {Governor} core.
Available since v4.3._
ProposalState
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
ProposalCreated
event ProposalCreated(uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description)
Emitted when a proposal is created.
ProposalCanceled
event ProposalCanceled(uint256 proposalId)
Emitted when a proposal is canceled.
ProposalExecuted
event ProposalExecuted(uint256 proposalId)
Emitted when a proposal is executed.
VoteCast
event VoteCast(address voter, uint256 proposalId, uint8 support, uint256 weight, string reason)
_Emitted when a vote is cast.
Note: `support` values should be seen as buckets. There interpretation depends on the voting module used._
name
function name() public view virtual returns (string)
module:core
Name of the governor instance (used in building the ERC712 domain separator).
version
function version() public view virtual returns (string)
module:core
Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
COUNTING_MODE
function COUNTING_MODE() public pure virtual returns (string)
module:voting
_A description of the possible `support` values for {castVote} and the way these votes are counted, meant to be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
There are 2 standard keys: `support` and `quorum`.
`support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
`quorum=bravo` means that only For votes are counted towards quorum.
`quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
NOTE: The string can be decoded by the standard https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] JavaScript class._
hashProposal
function hashProposal(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public pure virtual returns (uint256)
module:core
Hashing function used to (re)build the proposal id from the proposal details..
state
function state(uint256 proposalId) public view virtual returns (enum IGovernor.ProposalState)
module:core
Current state of a proposal, following Compound's convention
proposalSnapshot
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256)
module:core
block number used to retrieve user's votes and quorum.
proposalDeadline
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256)
module:core
timestamp at which votes close.
votingDelay
function votingDelay() public view virtual returns (uint256)
module:user-config
delay, in number of block, between the proposal is created and the vote starts. This can be increassed to leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
votingPeriod
function votingPeriod() public view virtual returns (uint256)
module:user-config
_delay, in number of blocks, between the vote start and vote ends.
Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting duration compared to the voting delay._
quorum
function quorum(uint256 blockNumber) public view virtual returns (uint256)
module:user-config
_Minimum number of cast voted required for a proposal to be successful.
Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes})._
getVotes
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256)
module:reputation
_Voting power of an `account` at a specific `blockNumber`.
Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or multiple), {ERC20Votes} tokens._
hasVoted
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool)
module:voting
Returns weither `account` has cast a vote on `proposalId`.
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256 proposalId)
_Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends {IGovernor-votingPeriod} blocks after the voting starts.
Emits a {ProposalCreated} event._
execute
function execute(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public payable virtual returns (uint256 proposalId)
_Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the deadline to be reached.
Emits a {ProposalExecuted} event.
Note: some module can modify the requirements for execution, for example by adding an additional timelock._
castVote
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance)
_Cast a vote
Emits a {VoteCast} event._
castVoteWithReason
function castVoteWithReason(uint256 proposalId, uint8 support, string reason) public virtual returns (uint256 balance)
_Cast a with a reason
Emits a {VoteCast} event._
castVoteBySig
function castVoteBySig(uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public virtual returns (uint256 balance)
_Cast a vote using the user cryptographic signature.
Emits a {VoteCast} event._
TimelockController
_Contract module which acts as a timelocked controller. When set as the owner of an `Ownable` smart contract, it enforces a timelock on all `onlyOwner` maintenance operations. This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied.
By default, this contract is self administered, meaning administration tasks have to go through the timelock process. The proposer (resp executor) role is in charge of proposing (resp executing) operations. A common use case is to position this {TimelockController} as the owner of a smart contract, with a multisig or a DAO as the sole proposer.
Available since v3.3._
TIMELOCK_ADMIN_ROLE
bytes32 TIMELOCK_ADMIN_ROLE
PROPOSER_ROLE
bytes32 PROPOSER_ROLE
EXECUTOR_ROLE
bytes32 EXECUTOR_ROLE
_DONE_TIMESTAMP
uint256 _DONE_TIMESTAMP
_timestamps
mapping(bytes32 => uint256) _timestamps
_minDelay
uint256 _minDelay
CallScheduled
event CallScheduled(bytes32 id, uint256 index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay)
Emitted when a call is scheduled as part of operation `id`.
CallExecuted
event CallExecuted(bytes32 id, uint256 index, address target, uint256 value, bytes data)
Emitted when a call is performed as part of operation `id`.
Cancelled
event Cancelled(bytes32 id)
Emitted when operation `id` is cancelled.
MinDelayChange
event MinDelayChange(uint256 oldDuration, uint256 newDuration)
Emitted when the minimum delay for future operations is modified.
constructor
constructor(uint256 minDelay, address[] proposers, address[] executors) public
Initializes the contract with a given `minDelay`.
onlyRoleOrOpenRole
modifier onlyRoleOrOpenRole(bytes32 role)
Modifier to make a function callable only by a certain role. In addition to checking the sender's role, `address(0)` 's role is also considered. Granting a role to `address(0)` is equivalent to enabling this role for everyone.
receive
receive() external payable
Contract might receive/hold ETH as part of the maintenance process.
isOperation
function isOperation(bytes32 id) public view virtual returns (bool pending)
Returns whether an id correspond to a registered operation. This includes both Pending, Ready and Done operations.
isOperationPending
function isOperationPending(bytes32 id) public view virtual returns (bool pending)
Returns whether an operation is pending or not.
isOperationReady
function isOperationReady(bytes32 id) public view virtual returns (bool ready)
Returns whether an operation is ready or not.
isOperationDone
function isOperationDone(bytes32 id) public view virtual returns (bool done)
Returns whether an operation is done or not.
getTimestamp
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp)
Returns the timestamp at with an operation becomes ready (0 for unset operations, 1 for done operations).
getMinDelay
function getMinDelay() public view virtual returns (uint256 duration)
_Returns the minimum delay for an operation to become valid.
This value can be changed by executing an operation that calls `updateDelay`._
hashOperation
function hashOperation(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash)
Returns the identifier of an operation containing a single transaction.
hashOperationBatch
function hashOperationBatch(address[] targets, uint256[] values, bytes[] datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash)
Returns the identifier of an operation containing a batch of transactions.
schedule
function schedule(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual
_Schedule an operation containing a single transaction.
Emits a {CallScheduled} event.
Requirements:
the caller must have the 'proposer' role._
scheduleBatch
function scheduleBatch(address[] targets, uint256[] values, bytes[] datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual
_Schedule an operation containing a batch of transactions.
Emits one {CallScheduled} event per transaction in the batch.
Requirements:
the caller must have the 'proposer' role._
_schedule
function _schedule(bytes32 id, uint256 delay) private
Schedule an operation that is to becomes valid after a given delay.
cancel
function cancel(bytes32 id) public virtual
_Cancel an operation.
Requirements:
the caller must have the 'proposer' role._
execute
function execute(address target, uint256 value, bytes data, bytes32 predecessor, bytes32 salt) public payable virtual
_Execute an (ready) operation containing a single transaction.
Emits a {CallExecuted} event.
Requirements:
the caller must have the 'executor' role._
executeBatch
function executeBatch(address[] targets, uint256[] values, bytes[] datas, bytes32 predecessor, bytes32 salt) public payable virtual
_Execute an (ready) operation containing a batch of transactions.
Emits one {CallExecuted} event per transaction in the batch.
Requirements:
the caller must have the 'executor' role._
_beforeCall
function _beforeCall(bytes32 id, bytes32 predecessor) private view
Checks before execution of an operation's calls.
_afterCall
function _afterCall(bytes32 id) private
Checks after execution of an operation's calls.
_call
function _call(bytes32 id, uint256 index, address target, uint256 value, bytes data) private
_Execute an operation's call.
Emits a {CallExecuted} event._
updateDelay
function updateDelay(uint256 newDelay) external virtual
_Changes the minimum timelock duration for future operations.
Emits a {MinDelayChange} event.
Requirements:
the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function._
GovernorCompatibilityBravo
_Compatibility layer that implements GovernorBravo compatibility on to of {Governor}.
This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added through inheritance. It does not include token bindings, not does it include any variable upgrade patterns.
Available since v4.3._
VoteType
enum VoteType {
Against,
For,
Abstain
}
ProposalDetails
struct ProposalDetails {
address proposer;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
mapping(address => struct IGovernorCompatibilityBravo.Receipt) receipts;
bytes32 descriptionHash;
}
_proposalDetails
mapping(uint256 => struct GovernorCompatibilityBravo.ProposalDetails) _proposalDetails
COUNTING_MODE
function COUNTING_MODE() public pure virtual returns (string)
module:voting
_A description of the possible `support` values for {castVote} and the way these votes are counted, meant to be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
There are 2 standard keys: `support` and `quorum`.
`support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
`quorum=bravo` means that only For votes are counted towards quorum.
`quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
NOTE: The string can be decoded by the standard https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] JavaScript class._
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernor-propose}.
propose
function propose(address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernorCompatibilityBravo-propose}.
queue
function queue(uint256 proposalId) public virtual
See {IGovernorCompatibilityBravo-queue}.
execute
function execute(uint256 proposalId) public payable virtual
See {IGovernorCompatibilityBravo-execute}.
cancel
function cancel(uint256 proposalId) public virtual
Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
_encodeCalldata
function _encodeCalldata(string[] signatures, bytes[] calldatas) private pure returns (bytes[])
Encodes calldatas with optional function signature.
_storeProposal
function _storeProposal(address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, string description) private
Store proposal metadata for later lookup
proposalThreshold
function proposalThreshold() public view virtual returns (uint256)
Part of the Governor Bravo's interface: "The number of votes required in order for a voter to become a proposer".
proposals
function proposals(uint256 proposalId) public view virtual returns (uint256 id, address proposer, uint256 eta, uint256 startBlock, uint256 endBlock, uint256 forVotes, uint256 againstVotes, uint256 abstainVotes, bool canceled, bool executed)
See {IGovernorCompatibilityBravo-proposals}.
getActions
function getActions(uint256 proposalId) public view virtual returns (address[] targets, uint256[] values, string[] signatures, bytes[] calldatas)
See {IGovernorCompatibilityBravo-getActions}.
getReceipt
function getReceipt(uint256 proposalId, address voter) public view virtual returns (struct IGovernorCompatibilityBravo.Receipt)
See {IGovernorCompatibilityBravo-getReceipt}.
quorumVotes
function quorumVotes() public view virtual returns (uint256)
See {IGovernorCompatibilityBravo-quorumVotes}.
hasVoted
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool)
See {IGovernor-hasVoted}.
_quorumReached
function _quorumReached(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-quorumReached}. In this module, only forVotes count toward the quorum.
_voteSucceeded
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
_countVote
function _countVote(uint256 proposalId, address account, uint8 support, uint256 weight) internal virtual
_See {Governor-countVote}. In this module, the support follows Governor Bravo.
IGovernorCompatibilityBravo
_Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility.
Available since v4.3._
Proposal
struct Proposal {
uint256 id;
address proposer;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
bool canceled;
bool executed;
mapping(address => struct IGovernorCompatibilityBravo.Receipt) receipts;
}
Receipt
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
quorumVotes
function quorumVotes() public view virtual returns (uint256)
Part of the Governor Bravo's interface.
proposals
function proposals(uint256) public view virtual returns (uint256 id, address proposer, uint256 eta, uint256 startBlock, uint256 endBlock, uint256 forVotes, uint256 againstVotes, uint256 abstainVotes, bool canceled, bool executed)
Part of the Governor Bravo's interface: "The official record of all proposals ever proposed".
propose
function propose(address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, string description) public virtual returns (uint256)
Part of the Governor Bravo's interface: "Function used to propose a new proposal".
queue
function queue(uint256 proposalId) public virtual
Part of the Governor Bravo's interface: "Queues a proposal of state succeeded".
execute
function execute(uint256 proposalId) public payable virtual
Part of the Governor Bravo's interface: "Executes a queued proposal if eta has passed".
cancel
function cancel(uint256 proposalId) public virtual
Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
getActions
function getActions(uint256 proposalId) public view virtual returns (address[] targets, uint256[] values, string[] signatures, bytes[] calldatas)
Part of the Governor Bravo's interface: "Gets actions of a proposal".
getReceipt
function getReceipt(uint256 proposalId, address voter) public view virtual returns (struct IGovernorCompatibilityBravo.Receipt)
Part of the Governor Bravo's interface: "Gets the receipt for a voter on a given proposal".
proposalThreshold
function proposalThreshold() public view virtual returns (uint256)
Part of the Governor Bravo's interface: "The number of votes required in order for a voter to become a proposer".
GovernorCountingSimple
_Extension of {Governor} for simple, 3 options, vote counting.
Available since v4.3._
VoteType
enum VoteType {
Against,
For,
Abstain
}
ProposalVote
struct ProposalVote {
uint256 againstVotes;
uint256 forVotes;
uint256 abstainVotes;
mapping(address => bool) hasVoted;
}
_proposalVotes
mapping(uint256 => struct GovernorCountingSimple.ProposalVote) _proposalVotes
COUNTING_MODE
function COUNTING_MODE() public pure virtual returns (string)
See {IGovernor-COUNTING_MODE}.
hasVoted
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool)
See {IGovernor-hasVoted}.
proposalVotes
function proposalVotes(uint256 proposalId) public view virtual returns (uint256 againstVotes, uint256 forVotes, uint256 abstainVotes)
Accessor to the internal vote counts.
_quorumReached
function _quorumReached(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-quorumReached}.
_voteSucceeded
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool)
_See {Governor-voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
_countVote
function _countVote(uint256 proposalId, address account, uint8 support, uint256 weight) internal virtual
_See {Governor-countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
GovernorProposalThreshold
_Extension of {Governor} for proposal restriction to token holders with a minimum balance.
Available since v4.3._
propose
function propose(address[] targets, uint256[] values, bytes[] calldatas, string description) public virtual returns (uint256)
See {IGovernor-propose}.
proposalThreshold
function proposalThreshold() public view virtual returns (uint256)
Part of the Governor Bravo's interface: "The number of votes required in order for a voter to become a proposer".
ICompoundTimelock
https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[Compound's timelock] interface
receive
receive() external payable
GRACE_PERIOD
function GRACE_PERIOD() external view returns (uint256)
MINIMUM_DELAY
function MINIMUM_DELAY() external view returns (uint256)
MAXIMUM_DELAY
function MAXIMUM_DELAY() external view returns (uint256)
admin
function admin() external view returns (address)
pendingAdmin
function pendingAdmin() external view returns (address)
delay
function delay() external view returns (uint256)
queuedTransactions
function queuedTransactions(bytes32) external view returns (bool)
setDelay
function setDelay(uint256) external
acceptAdmin
function acceptAdmin() external
setPendingAdmin
function setPendingAdmin(address) external
queueTransaction
function queueTransaction(address target, uint256 value, string signature, bytes data, uint256 eta) external returns (bytes32)
cancelTransaction
function cancelTransaction(address target, uint256 value, string signature, bytes data, uint256 eta) external
executeTransaction
function executeTransaction(address target, uint256 value, string signature, bytes data, uint256 eta) external payable returns (bytes)
GovernorTimelockCompound
_Extension of {Governor} that binds the execution process to a Compound Timelock. This adds a delay, enforced by the external timelock to all successful proposal (in addition to the voting duration). The {Governor} needs to be the admin of the timelock for any operation to be performed. A public, unrestricted, {GovernorTimelockCompound-__acceptAdmin} is available to accept ownership of the timelock.
Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be inaccessible.
Available since v4.3._
ProposalTimelock
struct ProposalTimelock {
struct Timers.Timestamp timer;
}
_timelock
contract ICompoundTimelock _timelock
_proposalTimelocks
mapping(uint256 => struct GovernorTimelockCompound.ProposalTimelock) _proposalTimelocks
TimelockChange
event TimelockChange(address oldTimelock, address newTimelock)
Emitted when the timelock controller used for proposal execution is modified.
constructor
constructor(contract ICompoundTimelock timelockAddress) internal
Set the timelock.
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
state
function state(uint256 proposalId) public view virtual returns (enum IGovernor.ProposalState)
Overriden version of the {Governor-state} function with added support for the `Queued` and `Expired` status.
timelock
function timelock() public view virtual returns (address)
Public accessor to check the address of the timelock
proposalEta
function proposalEta(uint256 proposalId) public view virtual returns (uint256)
Public accessor to check the eta of a queued proposal
queue
function queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public virtual returns (uint256)
Function to queue a proposal to the timelock.
_execute
function _execute(uint256 proposalId, address[] targets, uint256[] values, bytes[] calldatas, bytes32) internal virtual
Overriden execute function that run the already queued proposal through the timelock.
_cancel
function _cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual returns (uint256)
_Overriden version of the {Governor-cancel} function to cancel the timelocked proposal if it as already been queued.
_executor
function _executor() internal view virtual returns (address)
Address through which the governor executes action. In this case, the timelock.
__acceptAdmin
function __acceptAdmin() public
Accept admin right over the timelock.
updateTimelock
function updateTimelock(contract ICompoundTimelock newTimelock) external virtual
_Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates must be proposed, scheduled and executed using the {Governor} workflow.
For security reason, the timelock must be handed over to another admin before setting up a new one. The two operations (hand over the timelock) and do the update can be batched in a single proposal.
Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of governance._
_updateTimelock
function _updateTimelock(contract ICompoundTimelock newTimelock) private
GovernorTimelockControl
_Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The {Governor} needs the proposer (an ideally the executor) roles for the {Governor} to work properly.
Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be inaccessible.
Available since v4.3._
_timelock
contract TimelockController _timelock
_timelockIds
mapping(uint256 => bytes32) _timelockIds
TimelockChange
event TimelockChange(address oldTimelock, address newTimelock)
Emitted when the timelock controller used for proposal execution is modified.
constructor
constructor(contract TimelockController timelockAddress) internal
Set the timelock.
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
state
function state(uint256 proposalId) public view virtual returns (enum IGovernor.ProposalState)
Overriden version of the {Governor-state} function with added support for the `Queued` status.
timelock
function timelock() public view virtual returns (address)
Public accessor to check the address of the timelock
proposalEta
function proposalEta(uint256 proposalId) public view virtual returns (uint256)
Public accessor to check the eta of a queued proposal
queue
function queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public virtual returns (uint256)
Function to queue a proposal to the timelock.
_execute
function _execute(uint256, address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual
Overriden execute function that run the already queued proposal through the timelock.
_cancel
function _cancel(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) internal virtual returns (uint256)
_Overriden version of the {Governor-cancel} function to cancel the timelocked proposal if it as already been queued.
_executor
function _executor() internal view virtual returns (address)
Address through which the governor executes action. In this case, the timelock.
updateTimelock
function updateTimelock(contract TimelockController newTimelock) external virtual
Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates must be proposed, scheduled and executed using the {Governor} workflow.
_updateTimelock
function _updateTimelock(contract TimelockController newTimelock) private
GovernorVotes
_Extension of {Governor} for voting weight extraction from an {ERC20Votes} token.
Available since v4.3._
token
contract ERC20Votes token
constructor
constructor(contract ERC20Votes tokenAddress) internal
getVotes
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256)
Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
GovernorVotesComp
_Extension of {Governor} for voting weight extraction from a Comp token.
Available since v4.3._
token
contract ERC20VotesComp token
constructor
constructor(contract ERC20VotesComp token_) internal
getVotes
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256)
Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
GovernorVotesQuorumFraction
_Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a fraction of the total supply.
Available since v4.3._
_quorumNumerator
uint256 _quorumNumerator
QuorumNumeratorUpdated
event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator)
constructor
constructor(uint256 quorumNumeratorValue) internal
quorumNumerator
function quorumNumerator() public view virtual returns (uint256)
quorumDenominator
function quorumDenominator() public view virtual returns (uint256)
quorum
function quorum(uint256 blockNumber) public view virtual returns (uint256)
module:user-config
_Minimum number of cast voted required for a proposal to be successful.
Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes})._
updateQuorumNumerator
function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual
_updateQuorumNumerator
function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual
IGovernorTimelock
_Extension of the {IGovernor} for timelock supporting modules.
Available since v4.3._
ProposalQueued
event ProposalQueued(uint256 proposalId, uint256 eta)
timelock
function timelock() public view virtual returns (address)
proposalEta
function proposalEta(uint256 proposalId) public view virtual returns (uint256)
queue
function queue(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash) public virtual returns (uint256 proposalId)
IERC1271
_Interface of the ERC1271 standard signature validation method for contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
Available since v4.1._
isValidSignature
function isValidSignature(bytes32 hash, bytes signature) external view returns (bytes4 magicValue)
Should return whether the signature provided is valid for the provided data
hash
bytes32
Hash of the data to be signed
signature
bytes
Signature byte array associated with _data
IERC1363
transferAndCall
function transferAndCall(address to, uint256 value) external returns (bool)
Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
[0]
bool
true unless throwing
transferAndCall
function transferAndCall(address to, uint256 value, bytes data) external returns (bool)
Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
data
bytes
bytes Additional data with no specified format, sent in call to `to`
[0]
bool
true unless throwing
transferFromAndCall
function transferFromAndCall(address from, address to, uint256 value) external returns (bool)
Transfer tokens from one address to another and then call `onTransferReceived` on receiver
from
address
address The address which you want to send tokens from
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
[0]
bool
true unless throwing
transferFromAndCall
function transferFromAndCall(address from, address to, uint256 value, bytes data) external returns (bool)
Transfer tokens from one address to another and then call `onTransferReceived` on receiver
from
address
address The address which you want to send tokens from
to
address
address The address which you want to transfer to
value
uint256
uint256 The amount of tokens to be transferred
data
bytes
bytes Additional data with no specified format, sent in call to `to`
[0]
bool
true unless throwing
approveAndCall
function approveAndCall(address spender, uint256 value) external returns (bool)
Approve the passed address to spend the specified amount of tokens on behalf of msg.sender and then call `onApprovalReceived` on spender.
spender
address
address The address which will spend the funds
value
uint256
uint256 The amount of tokens to be spent
approveAndCall
function approveAndCall(address spender, uint256 value, bytes data) external returns (bool)
Approve the passed address to spend the specified amount of tokens on behalf of msg.sender and then call `onApprovalReceived` on spender.
spender
address
address The address which will spend the funds
value
uint256
uint256 The amount of tokens to be spent
data
bytes
bytes Additional data with no specified format, sent in call to `spender`
IERC2981
Interface for the NFT Royalty Standard
royaltyInfo
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount)
Called with the sale price to determine how much royalty is owed and to whom.
tokenId
uint256
- the NFT asset queried for royalty information
salePrice
uint256
- the sale price of the NFT asset specified by `tokenId`
receiver
address
- address of who should be sent the royalty payment
royaltyAmount
uint256
- the royalty payment amount for `salePrice`
IERC3156FlashBorrower
_Interface of the ERC3156 FlashBorrower, as defined in https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
Available since v4.1._
onFlashLoan
function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes data) external returns (bytes32)
Receive a flash loan.
initiator
address
The initiator of the loan.
token
address
The loan currency.
amount
uint256
The amount of tokens lent.
fee
uint256
The additional amount of tokens to repay.
data
bytes
Arbitrary data structure, intended to contain user-defined parameters.
[0]
bytes32
The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
IERC3156FlashLender
_Interface of the ERC3156 FlashLender, as defined in https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
Available since v4.1._
maxFlashLoan
function maxFlashLoan(address token) external view returns (uint256)
The amount of currency available to be lended.
token
address
The loan currency.
[0]
uint256
The amount of `token` that can be borrowed.
flashFee
function flashFee(address token, uint256 amount) external view returns (uint256)
The fee to be charged for a given loan.
token
address
The loan currency.
amount
uint256
The amount of tokens lent.
[0]
uint256
The amount of `token` to be charged for the loan, on top of the returned principal.
flashLoan
function flashLoan(contract IERC3156FlashBorrower receiver, address token, uint256 amount, bytes data) external returns (bool)
Initiate a flash loan.
receiver
contract IERC3156FlashBorrower
The receiver of the tokens in the loan, and the receiver of the callback.
token
address
The loan currency.
amount
uint256
The amount of tokens lent.
data
bytes
Arbitrary data structure, intended to contain user-defined parameters.
IERC2612
ERC2771Context
Context variant with ERC2771 support.
_trustedForwarder
address _trustedForwarder
constructor
constructor(address trustedForwarder) internal
isTrustedForwarder
function isTrustedForwarder(address forwarder) public view virtual returns (bool)
_msgSender
function _msgSender() internal view virtual returns (address sender)
_msgData
function _msgData() internal view virtual returns (bytes)
MinimalForwarder
Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.
ForwardRequest
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
_TYPEHASH
bytes32 _TYPEHASH
_nonces
mapping(address => uint256) _nonces
constructor
constructor() public
getNonce
function getNonce(address from) public view returns (uint256)
verify
function verify(struct MinimalForwarder.ForwardRequest req, bytes signature) public view returns (bool)
execute
function execute(struct MinimalForwarder.ForwardRequest req, bytes signature) public payable returns (bool, bytes)
ERC1967Proxy
This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an implementation address that can be changed. This address is stored in storage in the location specified by https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the implementation behind the proxy.
constructor
constructor(address _logic, bytes _data) public payable
_Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
If `_data` is nonempty, it's used as data in a delegate call to `logic`. This will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity constructor.
_implementation
function _implementation() internal view virtual returns (address impl)
Returns the current implementation address.
ERC1967Upgrade
_This abstract contract provides getters and event emitting update functions for https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
Available since v4.1._
_ROLLBACK_SLOT
bytes32 _ROLLBACK_SLOT
_IMPLEMENTATION_SLOT
bytes32 _IMPLEMENTATION_SLOT
Storage slot with the address of the current implementation. This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is validated in the constructor.
Upgraded
event Upgraded(address implementation)
Emitted when the implementation is upgraded.
_getImplementation
function _getImplementation() internal view returns (address)
Returns the current implementation address.
_setImplementation
function _setImplementation(address newImplementation) private
Stores a new address in the EIP1967 implementation slot.
_upgradeTo
function _upgradeTo(address newImplementation) internal
_Perform implementation upgrade
Emits an {Upgraded} event._
_upgradeToAndCall
function _upgradeToAndCall(address newImplementation, bytes data, bool forceCall) internal
_Perform implementation upgrade with additional setup call.
Emits an {Upgraded} event._
_upgradeToAndCallSecure
function _upgradeToAndCallSecure(address newImplementation, bytes data, bool forceCall) internal
_Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
Emits an {Upgraded} event._
_ADMIN_SLOT
bytes32 _ADMIN_SLOT
Storage slot with the admin of the contract. This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is validated in the constructor.
AdminChanged
event AdminChanged(address previousAdmin, address newAdmin)
Emitted when the admin account has changed.
_getAdmin
function _getAdmin() internal view returns (address)
Returns the current admin.
_setAdmin
function _setAdmin(address newAdmin) private
Stores a new address in the EIP1967 admin slot.
_changeAdmin
function _changeAdmin(address newAdmin) internal
_Changes the admin of the proxy.
Emits an {AdminChanged} event._
_BEACON_SLOT
bytes32 _BEACON_SLOT
The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
BeaconUpgraded
event BeaconUpgraded(address beacon)
Emitted when the beacon is upgraded.
_getBeacon
function _getBeacon() internal view returns (address)
Returns the current beacon.
_setBeacon
function _setBeacon(address newBeacon) private
Stores a new beacon in the EIP1967 beacon slot.
_upgradeBeaconToAndCall
function _upgradeBeaconToAndCall(address newBeacon, bytes data, bool forceCall) internal
_Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
Emits a {BeaconUpgraded} event._
Proxy
_This abstract contract provides a fallback function that delegates all calls to another contract using the EVM instruction `delegatecall`. We refer to the second contract as the implementation behind the proxy, and it has to be specified by overriding the virtual {_implementation} function.
Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a different contract through the {_delegate} function.
The success and return data of the delegated call will be returned back to the caller of the proxy._
_delegate
function _delegate(address implementation) internal virtual
_Delegates the current call to `implementation`.
This function does not return to its internall call site, it will return directly to the external caller._
_implementation
function _implementation() internal view virtual returns (address)
_This is a virtual function that should be overriden so it returns the address to which the fallback function and {fallback} should delegate.
_fallback
function _fallback() internal virtual
_Delegates the current call to the address returned by `_implementation()`.
This function does not return to its internall call site, it will return directly to the external caller._
fallback
fallback() external payable virtual
_Fallback function that delegates calls to the address returned by `implementation()`. Will run if no other function in the contract matches the call data.
receive
receive() external payable virtual
_Fallback function that delegates calls to the address returned by `implementation()`. Will run if call data is empty.
_beforeFallback
function _beforeFallback() internal virtual
_Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` call, or as part of the Solidity `fallback` or `receive` functions.
If overriden should call `super.beforeFallback()`.
BeaconProxy
_This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't conflict with the storage layout of the implementation behind the proxy.
Available since v3.4._
constructor
constructor(address beacon, bytes data) public payable
_Initializes the proxy with `beacon`.
If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity constructor.
Requirements:
`beacon` must be a contract with the interface {IBeacon}._
_beacon
function _beacon() internal view virtual returns (address)
Returns the current beacon address.
_implementation
function _implementation() internal view virtual returns (address)
Returns the current implementation address of the associated beacon.
_setBeacon
function _setBeacon(address beacon, bytes data) internal virtual
_Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
Requirements:
`beacon` must be a contract.
The implementation returned by `beacon` must be a contract._
IBeacon
This is the interface that {BeaconProxy} expects of its beacon.
implementation
function implementation() external view returns (address)
_Must return an address that can be used as a delegate call target.
{BeaconProxy} will check that this address is a contract._
UpgradeableBeacon
_This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their implementation contract, which is where they will delegate all function calls.
An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon._
_implementation
address _implementation
Upgraded
event Upgraded(address implementation)
Emitted when the implementation returned by the beacon is changed.
constructor
constructor(address implementation_) public
Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the beacon.
implementation
function implementation() public view virtual returns (address)
Returns the current implementation address.
upgradeTo
function upgradeTo(address newImplementation) public virtual
_Upgrades the beacon to a new implementation.
Emits an {Upgraded} event.
Requirements:
msg.sender must be the owner of the contract.
`newImplementation` must be a contract._
_setImplementation
function _setImplementation(address newImplementation) private
_Sets the implementation contract address for this beacon
Requirements:
`newImplementation` must be a contract._
ProxyAdmin
This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
getProxyImplementation
function getProxyImplementation(contract TransparentUpgradeableProxy proxy) public view virtual returns (address)
_Returns the current implementation of `proxy`.
Requirements:
This contract must be the admin of `proxy`._
getProxyAdmin
function getProxyAdmin(contract TransparentUpgradeableProxy proxy) public view virtual returns (address)
_Returns the current admin of `proxy`.
Requirements:
This contract must be the admin of `proxy`._
changeProxyAdmin
function changeProxyAdmin(contract TransparentUpgradeableProxy proxy, address newAdmin) public virtual
_Changes the admin of `proxy` to `newAdmin`.
Requirements:
This contract must be the current admin of `proxy`._
upgrade
function upgrade(contract TransparentUpgradeableProxy proxy, address implementation) public virtual
_Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
Requirements:
This contract must be the admin of `proxy`._
upgradeAndCall
function upgradeAndCall(contract TransparentUpgradeableProxy proxy, address implementation, bytes data) public payable virtual
_Upgrades `proxy` to `implementation` and calls a function on the new implementation. See {TransparentUpgradeableProxy-upgradeToAndCall}.
Requirements:
This contract must be the admin of `proxy`._
TransparentUpgradeableProxy
_This contract implements a proxy that is upgradeable by an admin.
To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand:
If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself.
If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says "admin cannot fallback to proxy target".
These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation.
Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy._
constructor
constructor(address _logic, address admin_, bytes _data) public payable
_Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `data` as explained in {ERC1967Proxy-constructor}.
ifAdmin
modifier ifAdmin()
Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
admin
function admin() external returns (address admin_)
_Returns the current admin.
NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`_
implementation
function implementation() external returns (address implementation_)
_Returns the current implementation.
NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`_
changeAdmin
function changeAdmin(address newAdmin) external virtual
_Changes the admin of the proxy.
Emits an {AdminChanged} event.
NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}._
upgradeTo
function upgradeTo(address newImplementation) external
_Upgrade the implementation of the proxy.
NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}._
upgradeToAndCall
function upgradeToAndCall(address newImplementation, bytes data) external payable
_Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract.
NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}._
_admin
function _admin() internal view virtual returns (address)
Returns the current admin.
_beforeFallback
function _beforeFallback() internal virtual
_Makes sure the admin cannot access the fallback function. See {Proxy-beforeFallback}.
UUPSUpgradeable
_An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing `UUPSUpgradeable` with a custom implementation of upgrades.
The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
Available since v4.1._
upgradeTo
function upgradeTo(address newImplementation) external virtual
_Upgrade the implementation of the proxy to `newImplementation`.
Calls {_authorizeUpgrade}.
Emits an {Upgraded} event._
upgradeToAndCall
function upgradeToAndCall(address newImplementation, bytes data) external payable virtual
_Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call encoded in `data`.
Calls {_authorizeUpgrade}.
Emits an {Upgraded} event._
_authorizeUpgrade
function _authorizeUpgrade(address newImplementation) internal virtual
_Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by {upgradeTo} and {upgradeToAndCall}.
Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
```solidity function authorizeUpgrade(address) internal override onlyOwner {} ```
Pausable
_Contract module which allows children to implement an emergency stop mechanism that can be triggered by an authorized account.
This module is used through inheritance. It will make available the modifiers `whenNotPaused` and `whenPaused`, which can be applied to the functions of your contract. Note that they will not be pausable by simply including this module, only once the modifiers are put in place._
Paused
event Paused(address account)
Emitted when the pause is triggered by `account`.
Unpaused
event Unpaused(address account)
Emitted when the pause is lifted by `account`.
_paused
bool _paused
constructor
constructor() internal
Initializes the contract in unpaused state.
paused
function paused() public view virtual returns (bool)
Returns true if the contract is paused, and false otherwise.
whenNotPaused
modifier whenNotPaused()
_Modifier to make a function callable only when the contract is not paused.
Requirements:
The contract must not be paused._
whenPaused
modifier whenPaused()
_Modifier to make a function callable only when the contract is paused.
Requirements:
The contract must be paused._
_pause
function _pause() internal virtual
_Triggers stopped state.
Requirements:
The contract must not be paused._
_unpause
function _unpause() internal virtual
_Returns to normal state.
Requirements:
The contract must be paused._
PullPayment
_Simple implementation of a https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] strategy, where the paying contract doesn't interact directly with the receiver account, which must withdraw its payments itself.
Pull-payments are often considered the best practice when it comes to sending Ether, security-wise. It prevents recipients from blocking execution, and eliminates reentrancy concerns.
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].
To use, derive from the `PullPayment` contract, and use {asyncTransfer} instead of Solidity's `transfer` function. Payees can query their due payments with {payments}, and retrieve them with {withdrawPayments}.
_escrow
contract Escrow _escrow
constructor
constructor() internal
withdrawPayments
function withdrawPayments(address payable payee) public virtual
_Withdraw accumulated payments, forwarding all gas to the recipient.
Note that any account can call this function, not just the `payee`. This means that contracts unaware of the `PullPayment` protocol can still receive funds this way, by having a separate account call {withdrawPayments}.
WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. Make sure you trust the recipient, or are either following the checks-effects-interactions pattern or using {ReentrancyGuard}._
payee
address payable
Whose payments will be withdrawn.
payments
function payments(address dest) public view returns (uint256)
Returns the payments owed to an address.
dest
address
The creditor's address.
_asyncTransfer
function _asyncTransfer(address dest, uint256 amount) internal virtual
Called by the payer to store the sent amount as credit to be pulled. Funds sent in this way are stored in an intermediate {Escrow} contract, so there is no danger of them being spent before withdrawal.
dest
address
The destination address of the funds.
amount
uint256
The amount to transfer.
ERC1155
_Implementation of the basic standard multi-token. See https://eips.ethereum.org/EIPS/eip-1155 Originally based on code by Enjin: https://github.com/enjin/erc-1155
Available since v3.1._
_balances
mapping(uint256 => mapping(address => uint256)) _balances
_operatorApprovals
mapping(address => mapping(address => bool)) _operatorApprovals
_uri
string _uri
constructor
constructor(string uri_) public
_See {setURI}.
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
uri
function uri(uint256) public view virtual returns (string)
_See {IERC1155MetadataURI-uri}.
This implementation returns the same URI for all token types. It relies on the token type ID substitution mechanism https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
Clients calling this function must replace the `{id}` substring with the actual token type ID._
balanceOf
function balanceOf(address account, uint256 id) public view virtual returns (uint256)
_See {IERC1155-balanceOf}.
Requirements:
`account` cannot be the zero address._
balanceOfBatch
function balanceOfBatch(address[] accounts, uint256[] ids) public view virtual returns (uint256[])
_See {IERC1155-balanceOfBatch}.
Requirements:
`accounts` and `ids` must have the same length._
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public virtual
See {IERC1155-setApprovalForAll}.
isApprovedForAll
function isApprovedForAll(address account, address operator) public view virtual returns (bool)
See {IERC1155-isApprovedForAll}.
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) public virtual
See {IERC1155-safeTransferFrom}.
safeBatchTransferFrom
function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data) public virtual
See {IERC1155-safeBatchTransferFrom}.
_safeTransferFrom
function _safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) internal virtual
_Transfers `amount` tokens of token type `id` from `from` to `to`.
Emits a {TransferSingle} event.
Requirements:
`to` cannot be the zero address.
`from` must have a balance of tokens of type `id` of at least `amount`.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value._
_safeBatchTransferFrom
function _safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
Emits a {TransferBatch} event.
Requirements:
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value._
_setURI
function _setURI(string newuri) internal virtual
_Sets a new URI for all token types, by relying on the token type ID substitution mechanism https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
By this mechanism, any occurrence of the `{id}` substring in either the URI or any of the amounts in the JSON file at said URI will be replaced by clients with the token type ID.
For example, the `https://token-cdn-domain/{id}.json` URI would be interpreted by clients as `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` for token type ID 0x4cce0.
See {uri}.
Because these URIs cannot be meaningfully represented by the {URI} event, this function emits no events._
_mint
function _mint(address account, uint256 id, uint256 amount, bytes data) internal virtual
_Creates `amount` tokens of token type `id`, and assigns them to `account`.
Emits a {TransferSingle} event.
Requirements:
`account` cannot be the zero address.
If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value._
_mintBatch
function _mintBatch(address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
Requirements:
`ids` and `amounts` must have the same length.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value._
_burn
function _burn(address account, uint256 id, uint256 amount) internal virtual
_Destroys `amount` tokens of token type `id` from `account`
Requirements:
`account` cannot be the zero address.
`account` must have at least `amount` tokens of token type `id`._
_burnBatch
function _burnBatch(address account, uint256[] ids, uint256[] amounts) internal virtual
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
Requirements:
`ids` and `amounts` must have the same length._
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_Hook that is called before any token transfer. This includes minting and burning, as well as batched variants.
The same hook is called on both single and batched variants. For single transfers, the length of the `id` and `amount` arrays will be 1.
Calling conditions (for each `id` and `amount` pair):
When `from` and `to` are both non-zero, `amount` of ``from``'s tokens of token type `id` will be transferred to `to`.
When `from` is zero, `amount` tokens of token type `id` will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens of token type `id` will be burned.
`from` and `to` are never both zero.
`ids` and `amounts` have the same, non-zero length.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_doSafeTransferAcceptanceCheck
function _doSafeTransferAcceptanceCheck(address operator, address from, address to, uint256 id, uint256 amount, bytes data) private
_doSafeBatchTransferAcceptanceCheck
function _doSafeBatchTransferAcceptanceCheck(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) private
_asSingletonArray
function _asSingletonArray(uint256 element) private pure returns (uint256[])
IERC1155
_Required interface of an ERC1155 compliant contract, as defined in the https://eips.ethereum.org/EIPS/eip-1155[EIP].
Available since v3.1._
TransferSingle
event TransferSingle(address operator, address from, address to, uint256 id, uint256 value)
Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
TransferBatch
event TransferBatch(address operator, address from, address to, uint256[] ids, uint256[] values)
Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all transfers.
ApprovalForAll
event ApprovalForAll(address account, address operator, bool approved)
Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to `approved`.
URI
event URI(string value, uint256 id)
_Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
If an {URI} event was emitted for `id`, the standard https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value returned by {IERC1155MetadataURI-uri}._
balanceOf
function balanceOf(address account, uint256 id) external view returns (uint256)
_Returns the amount of tokens of token type `id` owned by `account`.
Requirements:
`account` cannot be the zero address._
balanceOfBatch
function balanceOfBatch(address[] accounts, uint256[] ids) external view returns (uint256[])
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
Requirements:
`accounts` and `ids` must have the same length._
setApprovalForAll
function setApprovalForAll(address operator, bool approved) external
_Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
Emits an {ApprovalForAll} event.
Requirements:
`operator` cannot be the caller._
isApprovedForAll
function isApprovedForAll(address account, address operator) external view returns (bool)
_Returns true if `operator` is approved to transfer ``account``'s tokens.
See {setApprovalForAll}._
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data) external
_Transfers `amount` tokens of token type `id` from `from` to `to`.
Emits a {TransferSingle} event.
Requirements:
`to` cannot be the zero address.
If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
`from` must have a balance of tokens of type `id` of at least `amount`.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value._
safeBatchTransferFrom
function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data) external
_xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
Emits a {TransferBatch} event.
Requirements:
`ids` and `amounts` must have the same length.
If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value._
IERC1155Receiver
Available since v3.1.
onERC1155Received
function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes data) external returns (bytes4)
Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
onERC1155BatchReceived
function onERC1155BatchReceived(address operator, address from, uint256[] ids, uint256[] values, bytes data) external returns (bytes4)
Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
ERC1155Burnable
_Extension of {ERC1155} that allows token holders to destroy both their own tokens and those that they have been approved to use.
Available since v3.1._
burn
function burn(address account, uint256 id, uint256 value) public virtual
burnBatch
function burnBatch(address account, uint256[] ids, uint256[] values) public virtual
ERC1155Pausable
_ERC1155 token with pausable token transfers, minting and burning.
Useful for scenarios such as preventing trades until the end of an evaluation period, or having an emergency switch for freezing all token transfers in the event of a large bug.
Available since v3.1._
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_See {ERC1155-_beforeTokenTransfer}.
Requirements:
the contract must not be paused._
ERC1155Supply
_Extension of ERC1155 that adds tracking of total supply per id.
Useful for scenarios where Fungible and Non-fungible tokens have to be clearly identified. Note: While a totalSupply of 1 might mean the corresponding is an NFT, there is no guarantees that no other token with the same id are not going to be minted._
_totalSupply
mapping(uint256 => uint256) _totalSupply
totalSupply
function totalSupply(uint256 id) public view virtual returns (uint256)
Total amount of tokens in with a given id.
exists
function exists(uint256 id) public view virtual returns (bool)
Indicates weither any token exist with a given id, or not.
_mint
function _mint(address account, uint256 id, uint256 amount, bytes data) internal virtual
_See {ERC1155-mint}.
_mintBatch
function _mintBatch(address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
_See {ERC1155-mintBatch}.
_burn
function _burn(address account, uint256 id, uint256 amount) internal virtual
_See {ERC1155-burn}.
_burnBatch
function _burnBatch(address account, uint256[] ids, uint256[] amounts) internal virtual
_See {ERC1155-burnBatch}.
IERC1155MetadataURI
_Interface of the optional ERC1155MetadataExtension interface, as defined in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
Available since v3.1._
uri
function uri(uint256 id) external view returns (string)
_Returns the URI for token type `id`.
If the `{id}` substring is present in the URI, it must be replaced by clients with the actual token type ID._
ERC1155PresetMinterPauser
_{ERC1155} token, including:
ability for holders to burn (destroy) their tokens
a minter role that allows for token minting (creation)
a pauser role that allows to stop all token transfers
This contract uses {AccessControl} to lock permissioned functions using the different roles - head to its documentation for details.
The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role, which will let it grant both minter and pauser roles to other accounts._
MINTER_ROLE
bytes32 MINTER_ROLE
PAUSER_ROLE
bytes32 PAUSER_ROLE
constructor
constructor(string uri) public
Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that deploys the contract.
mint
function mint(address to, uint256 id, uint256 amount, bytes data) public virtual
_Creates `amount` new tokens for `to`, of token type `id`.
See {ERC1155-_mint}.
Requirements:
the caller must have the `MINTER_ROLE`._
mintBatch
function mintBatch(address to, uint256[] ids, uint256[] amounts, bytes data) public virtual
xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
pause
function pause() public virtual
_Pauses all token transfers.
See {ERC1155Pausable} and {Pausable-_pause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
unpause
function unpause() public virtual
_Unpauses all token transfers.
See {ERC1155Pausable} and {Pausable-_unpause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256[] ids, uint256[] amounts, bytes data) internal virtual
ERC1155Holder
Available since v3.1.
onERC1155Received
function onERC1155Received(address, address, uint256, uint256, bytes) public virtual returns (bytes4)
onERC1155BatchReceived
function onERC1155BatchReceived(address, address, uint256[], uint256[], bytes) public virtual returns (bytes4)
ERC1155Receiver
Available since v3.1.
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
ERC20
_Implementation of the {IERC20} interface.
This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}.
TIP: For a detailed writeup see our guide https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How to implement supply mechanisms].
We have followed general OpenZeppelin Contracts guidelines: functions revert instead returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications.
Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification.
Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}._
_balances
mapping(address => uint256) _balances
_allowances
mapping(address => mapping(address => uint256)) _allowances
_totalSupply
uint256 _totalSupply
_name
string _name
_symbol
string _symbol
constructor
constructor(string name_, string symbol_) public
_Sets the values for {name} and {symbol}.
The default value of {decimals} is 18. To select a different value for {decimals} you should overload it.
All two of these values are immutable: they can only be set once during construction._
name
function name() public view virtual returns (string)
Returns the name of the token.
symbol
function symbol() public view virtual returns (string)
Returns the symbol of the token, usually a shorter version of the name.
decimals
function decimals() public view virtual returns (uint8)
_Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5.05` (`505 / 10 ** 2`).
Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless this function is overridden;
NOTE: This information is only used for display purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}._
totalSupply
function totalSupply() public view virtual returns (uint256)
See {IERC20-totalSupply}.
balanceOf
function balanceOf(address account) public view virtual returns (uint256)
See {IERC20-balanceOf}.
transfer
function transfer(address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transfer}.
Requirements:
`recipient` cannot be the zero address.
the caller must have a balance of at least `amount`._
allowance
function allowance(address owner, address spender) public view virtual returns (uint256)
See {IERC20-allowance}.
approve
function approve(address spender, uint256 amount) public virtual returns (bool)
_See {IERC20-approve}.
Requirements:
`spender` cannot be the zero address._
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transferFrom}.
Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}.
Requirements:
`sender` and `recipient` cannot be the zero address.
`sender` must have a balance of at least `amount`.
the caller must have allowance for ``sender``'s tokens of at least `amount`._
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool)
_Atomically increases the allowance granted to `spender` by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
`spender` cannot be the zero address._
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool)
_Atomically decreases the allowance granted to `spender` by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
`spender` cannot be the zero address.
`spender` must have allowance for the caller of at least `subtractedValue`._
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal virtual
_Moves `amount` of tokens from `sender` to `recipient`.
This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc.
Emits a {Transfer} event.
Requirements:
`sender` cannot be the zero address.
`recipient` cannot be the zero address.
`sender` must have a balance of at least `amount`._
_mint
function _mint(address account, uint256 amount) internal virtual
_Creates `amount` tokens and assigns them to `account`, increasing the total supply.
Emits a {Transfer} event with `from` set to the zero address.
Requirements:
`account` cannot be the zero address._
_burn
function _burn(address account, uint256 amount) internal virtual
_Destroys `amount` tokens from `account`, reducing the total supply.
Emits a {Transfer} event with `to` set to the zero address.
Requirements:
`account` cannot be the zero address.
`account` must have at least `amount` tokens._
_approve
function _approve(address owner, address spender, uint256 amount) internal virtual
_Sets `amount` as the allowance of `spender` over the `owner` s tokens.
This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc.
Emits an {Approval} event.
Requirements:
`owner` cannot be the zero address.
`spender` cannot be the zero address._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
_Hook that is called before any transfer of tokens. This includes minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens will be transferred to `to`.
when `from` is zero, `amount` tokens will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens will be burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_afterTokenTransfer
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual
_Hook that is called after any transfer of tokens. This includes minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens has been transferred to `to`.
when `from` is zero, `amount` tokens have been minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens have been burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
IERC20
Interface of the ERC20 standard as defined in the EIP.
totalSupply
function totalSupply() external view returns (uint256)
Returns the amount of tokens in existence.
balanceOf
function balanceOf(address account) external view returns (uint256)
Returns the amount of tokens owned by `account`.
transfer
function transfer(address recipient, uint256 amount) external returns (bool)
_Moves `amount` tokens from the caller's account to `recipient`.
Returns a boolean value indicating whether the operation succeeded.
Emits a {Transfer} event._
allowance
function allowance(address owner, address spender) external view returns (uint256)
_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._
approve
function approve(address spender, uint256 amount) external returns (bool)
_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._
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)
_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._
Transfer
event Transfer(address from, address to, uint256 value)
_Emitted when `value` tokens are moved from one account (`from`) to another (`to`).
Note that `value` may be zero._
Approval
event Approval(address owner, address spender, uint256 value)
Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance.
ERC20Burnable
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).
burn
function burn(uint256 amount) public virtual
_Destroys `amount` tokens from the caller.
See {ERC20-burn}.
burnFrom
function burnFrom(address account, uint256 amount) public virtual
_Destroys `amount` tokens from `account`, deducting from the caller's allowance.
See {ERC20-_burn} and {ERC20-allowance}.
Requirements:
the caller must have allowance for ``accounts``'s tokens of at least `amount`._
ERC20Capped
Extension of {ERC20} that adds a cap to the supply of tokens.
_cap
uint256 _cap
constructor
constructor(uint256 cap_) internal
Sets the value of the `cap`. This value is immutable, it can only be set once during construction.
cap
function cap() public view virtual returns (uint256)
Returns the cap on the token's total supply.
_mint
function _mint(address account, uint256 amount) internal virtual
_See {ERC20-mint}.
ERC20FlashMint
_Implementation of the ERC3156 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}.
Available since v4.1._
_RETURN_VALUE
bytes32 _RETURN_VALUE
maxFlashLoan
function maxFlashLoan(address token) public view returns (uint256)
Returns the maximum amount of tokens available for loan.
token
address
The address of the token that is requested.
[0]
uint256
The amont of token that can be loaned.
flashFee
function flashFee(address token, uint256 amount) public view virtual returns (uint256)
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.
token
address
The token to be flash loaned.
amount
uint256
The amount of tokens to be loaned.
[0]
uint256
The fees applied to the corresponding flash loan.
flashLoan
function flashLoan(contract IERC3156FlashBorrower receiver, address token, uint256 amount, bytes data) public virtual returns (bool)
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 amount + fee tokens and have them approved back to the token contract itself so they can be burned.
receiver
contract IERC3156FlashBorrower
The receiver of the flash loan. Should implement the {IERC3156FlashBorrower.onFlashLoan} interface.
token
address
The token to be flash loaned. Only `address(this)` is supported.
amount
uint256
The amount of tokens to be loaned.
data
bytes
An arbitrary datafield that is passed to the receiver.
[0]
bool
`true` is the flash loan was successful.
ERC20Pausable
_ERC20 token with pausable token transfers, minting and burning.
Useful for scenarios such as preventing trades until the end of an evaluation period, or having an emergency switch for freezing all token transfers in the event of a large bug._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
_See {ERC20-_beforeTokenTransfer}.
Requirements:
the contract must not be paused._
ERC20Snapshot
_This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and total supply at the time are recorded for later access.
This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be used to create an efficient ERC20 forking mechanism.
Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id and the account address.
NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient alternative consider {ERC20Votes}.
==== Gas Costs
Snapshots are efficient. Snapshot creation is O(1). Retrieval of balances or total supply from a snapshot is O(log n) in the number of snapshots that have been created, although n for a specific account will generally be much smaller since identical balances in subsequent snapshots are stored as a single entry.
There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent transfers will have normal cost until the next snapshot, and so on._
Snapshots
struct Snapshots {
uint256[] ids;
uint256[] values;
}
_accountBalanceSnapshots
mapping(address => struct ERC20Snapshot.Snapshots) _accountBalanceSnapshots
_totalSupplySnapshots
struct ERC20Snapshot.Snapshots _totalSupplySnapshots
_currentSnapshotId
struct Counters.Counter _currentSnapshotId
Snapshot
event Snapshot(uint256 id)
_Emitted by {snapshot} when a snapshot identified by `id` is created.
_snapshot
function _snapshot() internal virtual returns (uint256)
_Creates a new snapshot and returns its snapshot id.
Emits a {Snapshot} event that contains the same id.
{_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a set of accounts, for example using {AccessControl}, or it may be open to the public.
[WARNING] ==== While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, you must consider that it can potentially be used by attackers in two ways.
First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs section above.
We haven't measured the actual numbers; if this is something you're interested in please reach out to us. ====_
_getCurrentSnapshotId
function _getCurrentSnapshotId() internal view virtual returns (uint256)
Get the current snapshotId
balanceOfAt
function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256)
Retrieves the balance of `account` at the time `snapshotId` was created.
totalSupplyAt
function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256)
Retrieves the total supply at the time `snapshotId` was created.
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
_Hook that is called before any transfer of tokens. This includes minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens will be transferred to `to`.
when `from` is zero, `amount` tokens will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens will be burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_valueAt
function _valueAt(uint256 snapshotId, struct ERC20Snapshot.Snapshots snapshots) private view returns (bool, uint256)
_updateAccountSnapshot
function _updateAccountSnapshot(address account) private
_updateTotalSupplySnapshot
function _updateTotalSupplySnapshot() private
_updateSnapshot
function _updateSnapshot(struct ERC20Snapshot.Snapshots snapshots, uint256 currentValue) private
_lastSnapshotId
function _lastSnapshotId(uint256[] ids) private view returns (uint256)
ERC20Votes
_Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting power can be queried through the public accessors {getVotes} and {getPastVotes}.
By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this will significantly increase the base gas cost of transfers.
Available since v4.2._
Checkpoint
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
_DELEGATION_TYPEHASH
bytes32 _DELEGATION_TYPEHASH
_delegates
mapping(address => address) _delegates
_checkpoints
mapping(address => struct ERC20Votes.Checkpoint[]) _checkpoints
_totalSupplyCheckpoints
struct ERC20Votes.Checkpoint[] _totalSupplyCheckpoints
DelegateChanged
event DelegateChanged(address delegator, address fromDelegate, address toDelegate)
Emitted when an account changes their delegate.
DelegateVotesChanged
event DelegateVotesChanged(address delegate, uint256 previousBalance, uint256 newBalance)
Emitted when a token transfer or delegate change results in changes to an account's voting power.
checkpoints
function checkpoints(address account, uint32 pos) public view virtual returns (struct ERC20Votes.Checkpoint)
Get the `pos`-th checkpoint for `account`.
numCheckpoints
function numCheckpoints(address account) public view virtual returns (uint32)
Get number of checkpoints for `account`.
delegates
function delegates(address account) public view virtual returns (address)
Get the address `account` is currently delegating to.
getVotes
function getVotes(address account) public view returns (uint256)
Gets the current votes balance for `account`
getPastVotes
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256)
_Retrieve the number of votes for `account` at the end of `blockNumber`.
Requirements:
`blockNumber` must have been already mined_
getPastTotalSupply
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256)
_Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. It is but NOT the sum of all the delegated votes!
Requirements:
`blockNumber` must have been already mined_
_checkpointsLookup
function _checkpointsLookup(struct ERC20Votes.Checkpoint[] ckpts, uint256 blockNumber) private view returns (uint256)
Lookup a value in a list of (sorted) checkpoints.
delegate
function delegate(address delegatee) public virtual
Delegate votes from the sender to `delegatee`.
delegateBySig
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) public virtual
Delegates votes from signer to `delegatee`
_maxSupply
function _maxSupply() internal view virtual returns (uint224)
Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
_mint
function _mint(address account, uint256 amount) internal virtual
Snapshots the totalSupply after it has been increased.
_burn
function _burn(address account, uint256 amount) internal virtual
Snapshots the totalSupply after it has been decreased.
_afterTokenTransfer
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual
_Move voting power when tokens are transferred.
Emits a {DelegateVotesChanged} event._
_delegate
function _delegate(address delegator, address delegatee) internal virtual
_Change delegation for `delegator` to `delegatee`.
Emits events {DelegateChanged} and {DelegateVotesChanged}._
_moveVotingPower
function _moveVotingPower(address src, address dst, uint256 amount) private
_writeCheckpoint
function _writeCheckpoint(struct ERC20Votes.Checkpoint[] ckpts, function (uint256,uint256) view returns (uint256) op, uint256 delta) private returns (uint256 oldWeight, uint256 newWeight)
_add
function _add(uint256 a, uint256 b) private pure returns (uint256)
_subtract
function _subtract(uint256 a, uint256 b) private pure returns (uint256)
ERC20VotesComp
_Extension of ERC20 to support Compound's voting and delegation. This version exactly matches Compound's interface, with the drawback of only supporting supply up to (2^96^ - 1).
NOTE: You should use this contract if you need exact compatibility with COMP (for example in order to use your token with Governor Alpha or Bravo) and if you are sure the supply cap of 2^96^ is enough for you. Otherwise, use the {ERC20Votes} variant of this module.
This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting power can be queried through the public accessors {getCurrentVotes} and {getPriorVotes}.
By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this will significantly increase the base gas cost of transfers.
Available since v4.2._
getCurrentVotes
function getCurrentVotes(address account) external view returns (uint96)
Comp version of the {getVotes} accessor, with `uint96` return type.
getPriorVotes
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96)
Comp version of the {getPastVotes} accessor, with `uint96` return type.
_maxSupply
function _maxSupply() internal view virtual returns (uint224)
Maximum token supply. Reduced to `type(uint96).max` (2^96^ - 1) to fit COMP interface.
ERC20Wrapper
_Extension of the ERC20 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" ERC20 into a governance token.
Available since v4.2._
underlying
contract IERC20 underlying
constructor
constructor(contract IERC20 underlyingToken) internal
depositFor
function depositFor(address account, uint256 amount) public virtual returns (bool)
Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
withdrawTo
function withdrawTo(address account, uint256 amount) public virtual returns (bool)
Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
_recover
function _recover(address account) internal virtual returns (uint256)
Mint wrapped token to cover any underlyingTokens that would have been transfered by mistake. Internal function that can be exposed with access control if desired.
IERC20Metadata
_Interface for the optional metadata functions from the ERC20 standard.
Available since v4.1._
name
function name() external view returns (string)
Returns the name of the token.
symbol
function symbol() external view returns (string)
Returns the symbol of the token.
decimals
function decimals() external view returns (uint8)
Returns the decimals places of the token.
ERC20Permit
_Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all.
Available since v3.4._
_nonces
mapping(address => struct Counters.Counter) _nonces
_PERMIT_TYPEHASH
bytes32 _PERMIT_TYPEHASH
constructor
constructor(string name) internal
_Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
It's a good idea to use the same `name` that is defined as the ERC20 token name._
permit
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual
See {IERC20Permit-permit}.
nonces
function nonces(address owner) public view virtual returns (uint256)
See {IERC20Permit-nonces}.
DOMAIN_SEPARATOR
function DOMAIN_SEPARATOR() external view returns (bytes32)
See {IERC20Permit-DOMAIN_SEPARATOR}.
_useNonce
function _useNonce(address owner) internal virtual returns (uint256 current)
_"Consume a nonce": return the current value and increment.
Available since v4.1._
IERC20Permit
_Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all._
permit
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external
_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]._
nonces
function nonces(address owner) external view returns (uint256)
_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._
DOMAIN_SEPARATOR
function DOMAIN_SEPARATOR() external view returns (bytes32)
Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
ERC20PresetFixedSupply
_{ERC20} token, including:
Preminted initial supply
Ability for holders to burn (destroy) their tokens
No access control mechanism (for minting/pausing) and hence no governance
This contract uses {ERC20Burnable} to include burn capabilities - head to its documentation for details.
Available since v3.4._
constructor
constructor(string name, string symbol, uint256 initialSupply, address owner) public
_Mints `initialSupply` amount of token and transfers them to `owner`.
See {ERC20-constructor}._
ERC20PresetMinterPauser
_{ERC20} token, including:
ability for holders to burn (destroy) their tokens
a minter role that allows for token minting (creation)
a pauser role that allows to stop all token transfers
This contract uses {AccessControl} to lock permissioned functions using the different roles - head to its documentation for details.
The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role, which will let it grant both minter and pauser roles to other accounts._
MINTER_ROLE
bytes32 MINTER_ROLE
PAUSER_ROLE
bytes32 PAUSER_ROLE
constructor
constructor(string name, string symbol) public
_Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the account that deploys the contract.
See {ERC20-constructor}._
mint
function mint(address to, uint256 amount) public virtual
_Creates `amount` new tokens for `to`.
See {ERC20-_mint}.
Requirements:
the caller must have the `MINTER_ROLE`._
pause
function pause() public virtual
_Pauses all token transfers.
See {ERC20Pausable} and {Pausable-_pause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
unpause
function unpause() public virtual
_Unpauses all token transfers.
See {ERC20Pausable} and {Pausable-_unpause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual
SafeERC20
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.
safeTransfer
function safeTransfer(contract IERC20 token, address to, uint256 value) internal
safeTransferFrom
function safeTransferFrom(contract IERC20 token, address from, address to, uint256 value) internal
safeApprove
function safeApprove(contract IERC20 token, address spender, uint256 value) internal
_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._
safeIncreaseAllowance
function safeIncreaseAllowance(contract IERC20 token, address spender, uint256 value) internal
safeDecreaseAllowance
function safeDecreaseAllowance(contract IERC20 token, address spender, uint256 value) internal
_callOptionalReturn
function _callOptionalReturn(contract IERC20 token, bytes data) private
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).
token
contract IERC20
The token targeted by the call.
data
bytes
The call data (encoded using abi.encode or one of its variants).
TokenTimelock
_A token holder contract that will allow a beneficiary to extract the tokens after a given release time.
Useful for simple vesting schedules like "advisors get all of their tokens after 1 year"._
_token
contract IERC20 _token
_beneficiary
address _beneficiary
_releaseTime
uint256 _releaseTime
constructor
constructor(contract IERC20 token_, address beneficiary_, uint256 releaseTime_) public
token
function token() public view virtual returns (contract IERC20)
[0]
contract IERC20
the token being held.
beneficiary
function beneficiary() public view virtual returns (address)
[0]
address
the beneficiary of the tokens.
releaseTime
function releaseTime() public view virtual returns (uint256)
[0]
uint256
the time when the tokens are released.
release
function release() public virtual
Transfers tokens held by timelock to beneficiary.
ERC721
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}.
_name
string _name
_symbol
string _symbol
_owners
mapping(uint256 => address) _owners
_balances
mapping(address => uint256) _balances
_tokenApprovals
mapping(uint256 => address) _tokenApprovals
_operatorApprovals
mapping(address => mapping(address => bool)) _operatorApprovals
constructor
constructor(string name_, string symbol_) public
Initializes the contract by setting a `name` and a `symbol` to the token collection.
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
balanceOf
function balanceOf(address owner) public view virtual returns (uint256)
See {IERC721-balanceOf}.
ownerOf
function ownerOf(uint256 tokenId) public view virtual returns (address)
See {IERC721-ownerOf}.
name
function name() public view virtual returns (string)
See {IERC721Metadata-name}.
symbol
function symbol() public view virtual returns (string)
See {IERC721Metadata-symbol}.
tokenURI
function tokenURI(uint256 tokenId) public view virtual returns (string)
See {IERC721Metadata-tokenURI}.
_baseURI
function _baseURI() internal view virtual returns (string)
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.
approve
function approve(address to, uint256 tokenId) public virtual
See {IERC721-approve}.
getApproved
function getApproved(uint256 tokenId) public view virtual returns (address)
See {IERC721-getApproved}.
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public virtual
See {IERC721-setApprovalForAll}.
isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual returns (bool)
See {IERC721-isApprovedForAll}.
transferFrom
function transferFrom(address from, address to, uint256 tokenId) public virtual
See {IERC721-transferFrom}.
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual
See {IERC721-safeTransferFrom}.
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) public virtual
See {IERC721-safeTransferFrom}.
_safeTransfer
function _safeTransfer(address from, address to, uint256 tokenId, bytes _data) internal virtual
_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._
_exists
function _exists(uint256 tokenId) internal view virtual returns (bool)
_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`).
_isApprovedOrOwner
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool)
_Returns whether `spender` is allowed to manage `tokenId`.
Requirements:
`tokenId` must exist._
_safeMint
function _safeMint(address to, uint256 tokenId) internal virtual
_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._
_safeMint
function _safeMint(address to, uint256 tokenId, bytes _data) internal virtual
_Same as {xref-ERC721-_safeMint-address-uint256-}[`safeMint`], with an additional `data` parameter which is forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
_mint
function _mint(address to, uint256 tokenId) internal virtual
_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._
_burn
function _burn(uint256 tokenId) internal virtual
_Destroys `tokenId`. The approval is cleared when the token is burned.
Requirements:
`tokenId` must exist.
Emits a {Transfer} event._
_transfer
function _transfer(address from, address to, uint256 tokenId) internal virtual
_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._
_approve
function _approve(address to, uint256 tokenId) internal virtual
_Approve `to` to operate on `tokenId`
Emits a {Approval} event._
_checkOnERC721Received
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes _data) private returns (bool)
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract.
from
address
address representing the previous owner of the given token ID
to
address
target address that will receive the tokens
tokenId
uint256
uint256 ID of the token to be transferred
_data
bytes
bytes optional data to send along with the call
[0]
bool
bool whether the call correctly returned the expected magic value
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
_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]._
IERC721
Required interface of an ERC721 compliant contract.
Transfer
event Transfer(address from, address to, uint256 tokenId)
Emitted when `tokenId` token is transferred from `from` to `to`.
Approval
event Approval(address owner, address approved, uint256 tokenId)
Emitted when `owner` enables `approved` to manage the `tokenId` token.
ApprovalForAll
event ApprovalForAll(address owner, address operator, bool approved)
Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
balanceOf
function balanceOf(address owner) external view returns (uint256 balance)
Returns the number of tokens in ``owner``'s account.
ownerOf
function ownerOf(uint256 tokenId) external view returns (address owner)
_Returns the owner of the `tokenId` token.
Requirements:
`tokenId` must exist._
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId) external
_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._
transferFrom
function transferFrom(address from, address to, uint256 tokenId) external
_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._
approve
function approve(address to, uint256 tokenId) external
_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._
getApproved
function getApproved(uint256 tokenId) external view returns (address operator)
_Returns the account approved for `tokenId` token.
Requirements:
`tokenId` must exist._
setApprovalForAll
function setApprovalForAll(address operator, bool _approved) external
_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._
isApprovedForAll
function isApprovedForAll(address owner, address operator) external view returns (bool)
_Returns if the `operator` is allowed to manage all of the assets of `owner`.
See {setApprovalForAll}_
safeTransferFrom
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) external
_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._
IERC721Receiver
Interface for any contract that wants to support safeTransfers from ERC721 asset contracts.
onERC721Received
function onERC721Received(address operator, address from, uint256 tokenId, bytes data) external returns (bytes4)
_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`._
ERC721Burnable
ERC721 Token that can be irreversibly burned (destroyed).
burn
function burn(uint256 tokenId) public virtual
_Burns `tokenId`. See {ERC721-_burn}.
Requirements:
The caller must own `tokenId` or be an approved operator._
ERC721Enumerable
This implements an optional extension of {ERC721} defined in the EIP that adds enumerability of all the token ids in the contract as well as all token ids owned by each account.
_ownedTokens
mapping(address => mapping(uint256 => uint256)) _ownedTokens
_ownedTokensIndex
mapping(uint256 => uint256) _ownedTokensIndex
_allTokens
uint256[] _allTokens
_allTokensIndex
mapping(uint256 => uint256) _allTokensIndex
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256)
See {IERC721Enumerable-tokenOfOwnerByIndex}.
totalSupply
function totalSupply() public view virtual returns (uint256)
See {IERC721Enumerable-totalSupply}.
tokenByIndex
function tokenByIndex(uint256 index) public view virtual returns (uint256)
See {IERC721Enumerable-tokenByIndex}.
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
_Hook that is called before any token transfer. This includes minting and burning.
Calling conditions:
When `from` and `to` are both non-zero, ``from``'s `tokenId` will be transferred to `to`.
When `from` is zero, `tokenId` will be minted for `to`.
When `to` is zero, ``from``'s `tokenId` will be burned.
`from` cannot be the zero address.
`to` cannot be the zero address.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
_addTokenToOwnerEnumeration
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private
Private function to add a token to this extension's ownership-tracking data structures.
to
address
address representing the new owner of the given token ID
tokenId
uint256
uint256 ID of the token to be added to the tokens list of the given address
_addTokenToAllTokensEnumeration
function _addTokenToAllTokensEnumeration(uint256 tokenId) private
Private function to add a token to this extension's token tracking data structures.
tokenId
uint256
uint256 ID of the token to be added to the tokens list
_removeTokenFromOwnerEnumeration
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private
_Private function to remove a token from this extension's ownership-tracking data structures. Note that while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is not updated: this allows for gas optimizations e.g. when performing a transfer operation (avoiding double writes). This has O(1) time complexity, but alters the order of the ownedTokens array.
from
address
address representing the previous owner of the given token ID
tokenId
uint256
uint256 ID of the token to be removed from the tokens list of the given address
_removeTokenFromAllTokensEnumeration
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private
_Private function to remove a token from this extension's token tracking data structures. This has O(1) time complexity, but alters the order of the allTokens array.
tokenId
uint256
uint256 ID of the token to be removed from the tokens list
ERC721Pausable
_ERC721 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._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
_See {ERC721-_beforeTokenTransfer}.
Requirements:
the contract must not be paused._
ERC721URIStorage
ERC721 token with storage based token URI management.
_tokenURIs
mapping(uint256 => string) _tokenURIs
tokenURI
function tokenURI(uint256 tokenId) public view virtual returns (string)
See {IERC721Metadata-tokenURI}.
_setTokenURI
function _setTokenURI(uint256 tokenId, string _tokenURI) internal virtual
_Sets `_tokenURI` as the tokenURI of `tokenId`.
Requirements:
`tokenId` must exist._
_burn
function _burn(uint256 tokenId) internal virtual
_Destroys `tokenId`. The approval is cleared when the token is burned.
Requirements:
`tokenId` must exist.
Emits a {Transfer} event._
IERC721Enumerable
See https://eips.ethereum.org/EIPS/eip-721
totalSupply
function totalSupply() external view returns (uint256)
Returns the total amount of tokens stored by the contract.
tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId)
Returns a token ID owned by `owner` at a given `index` of its token list. Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
tokenByIndex
function tokenByIndex(uint256 index) external view returns (uint256)
Returns a token ID at a given `index` of all the tokens stored by the contract. Use along with {totalSupply} to enumerate all tokens.
IERC721Metadata
See https://eips.ethereum.org/EIPS/eip-721
name
function name() external view returns (string)
Returns the token collection name.
symbol
function symbol() external view returns (string)
Returns the token collection symbol.
tokenURI
function tokenURI(uint256 tokenId) external view returns (string)
Returns the Uniform Resource Identifier (URI) for `tokenId` token.
ERC721PresetMinterPauserAutoId
_{ERC721} token, including:
ability for holders to burn (destroy) their tokens
a minter role that allows for token minting (creation)
a pauser role that allows to stop all token transfers
token ID and URI autogeneration
This contract uses {AccessControl} to lock permissioned functions using the different roles - head to its documentation for details.
The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role, which will let it grant both minter and pauser roles to other accounts._
MINTER_ROLE
bytes32 MINTER_ROLE
PAUSER_ROLE
bytes32 PAUSER_ROLE
_tokenIdTracker
struct Counters.Counter _tokenIdTracker
_baseTokenURI
string _baseTokenURI
constructor
constructor(string name, string symbol, string baseTokenURI) public
_Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the account that deploys the contract.
Token URIs will be autogenerated based on `baseURI` and their token IDs. See {ERC721-tokenURI}._
_baseURI
function _baseURI() internal view virtual returns (string)
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.
mint
function mint(address to) public virtual
_Creates a new token for `to`. Its token ID will be automatically assigned (and available on the emitted {IERC721-Transfer} event), and the token URI autogenerated based on the base URI passed at construction.
See {ERC721-_mint}.
Requirements:
the caller must have the `MINTER_ROLE`._
pause
function pause() public virtual
_Pauses all token transfers.
See {ERC721Pausable} and {Pausable-_pause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
unpause
function unpause() public virtual
_Unpauses all token transfers.
See {ERC721Pausable} and {Pausable-_unpause}.
Requirements:
the caller must have the `PAUSER_ROLE`._
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
ERC721Holder
_Implementation of the {IERC721Receiver} interface.
Accepts all token transfers. Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}._
onERC721Received
function onERC721Received(address, address, uint256, bytes) public virtual returns (bytes4)
_See {IERC721Receiver-onERC721Received}.
Always returns `IERC721Receiver.onERC721Received.selector`._
ERC777
_Implementation of the {IERC777} 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}.
Support for ERC20 is included in this contract, as specified by the EIP: both the ERC777 and ERC20 interfaces can be safely used when interacting with it. Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token movements.
Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there are no special restrictions in the amount of tokens that created, moved, or destroyed. This makes integration with ERC20 applications seamless._
_ERC1820_REGISTRY
contract IERC1820Registry _ERC1820_REGISTRY
_balances
mapping(address => uint256) _balances
_totalSupply
uint256 _totalSupply
_name
string _name
_symbol
string _symbol
_TOKENS_SENDER_INTERFACE_HASH
bytes32 _TOKENS_SENDER_INTERFACE_HASH
_TOKENS_RECIPIENT_INTERFACE_HASH
bytes32 _TOKENS_RECIPIENT_INTERFACE_HASH
_defaultOperatorsArray
address[] _defaultOperatorsArray
_defaultOperators
mapping(address => bool) _defaultOperators
_operators
mapping(address => mapping(address => bool)) _operators
_revokedDefaultOperators
mapping(address => mapping(address => bool)) _revokedDefaultOperators
_allowances
mapping(address => mapping(address => uint256)) _allowances
constructor
constructor(string name_, string symbol_, address[] defaultOperators_) public
`defaultOperators` may be an empty array.
name
function name() public view virtual returns (string)
See {IERC777-name}.
symbol
function symbol() public view virtual returns (string)
See {IERC777-symbol}.
decimals
function decimals() public pure virtual returns (uint8)
_See {ERC20-decimals}.
Always returns 18, as per the ERC777 EIP._
granularity
function granularity() public view virtual returns (uint256)
_See {IERC777-granularity}.
This implementation always returns `1`._
totalSupply
function totalSupply() public view virtual returns (uint256)
See {IERC777-totalSupply}.
balanceOf
function balanceOf(address tokenHolder) public view virtual returns (uint256)
Returns the amount of tokens owned by an account (`tokenHolder`).
send
function send(address recipient, uint256 amount, bytes data) public virtual
_See {IERC777-send}.
Also emits a {IERC20-Transfer} event for ERC20 compatibility._
transfer
function transfer(address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transfer}.
Unlike `send`, `recipient` is not required to implement the {IERC777Recipient} interface if it is a contract.
Also emits a {Sent} event._
burn
function burn(uint256 amount, bytes data) public virtual
_See {IERC777-burn}.
Also emits a {IERC20-Transfer} event for ERC20 compatibility._
isOperatorFor
function isOperatorFor(address operator, address tokenHolder) public view virtual returns (bool)
See {IERC777-isOperatorFor}.
authorizeOperator
function authorizeOperator(address operator) public virtual
See {IERC777-authorizeOperator}.
revokeOperator
function revokeOperator(address operator) public virtual
See {IERC777-revokeOperator}.
defaultOperators
function defaultOperators() public view virtual returns (address[])
See {IERC777-defaultOperators}.
operatorSend
function operatorSend(address sender, address recipient, uint256 amount, bytes data, bytes operatorData) public virtual
_See {IERC777-operatorSend}.
Emits {Sent} and {IERC20-Transfer} events._
operatorBurn
function operatorBurn(address account, uint256 amount, bytes data, bytes operatorData) public virtual
_See {IERC777-operatorBurn}.
Emits {Burned} and {IERC20-Transfer} events._
allowance
function allowance(address holder, address spender) public view virtual returns (uint256)
_See {IERC20-allowance}.
Note that operator and allowance concepts are orthogonal: operators may not have allowance, and accounts with allowance may not be operators themselves._
approve
function approve(address spender, uint256 value) public virtual returns (bool)
_See {IERC20-approve}.
Note that accounts cannot have allowance issued by their operators._
transferFrom
function transferFrom(address holder, address recipient, uint256 amount) public virtual returns (bool)
_See {IERC20-transferFrom}.
Note that operator and allowance concepts are orthogonal: operators cannot call `transferFrom` (unless they have allowance), and accounts with allowance cannot call `operatorSend` (unless they are operators).
Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events._
_mint
function _mint(address account, uint256 amount, bytes userData, bytes operatorData) internal virtual
_Creates `amount` tokens and assigns them to `account`, increasing the total supply.
If a send hook is registered for `account`, the corresponding function will be called with `operator`, `data` and `operatorData`.
See {IERC777Sender} and {IERC777Recipient}.
Emits {Minted} and {IERC20-Transfer} events.
Requirements
`account` cannot be the zero address.
if `account` is a contract, it must implement the {IERC777Recipient} interface._
_mint
function _mint(address account, uint256 amount, bytes userData, bytes operatorData, bool requireReceptionAck) internal virtual
_Creates `amount` tokens and assigns them to `account`, increasing the total supply.
If `requireReceptionAck` is set to true, and if a send hook is registered for `account`, the corresponding function will be called with `operator`, `data` and `operatorData`.
See {IERC777Sender} and {IERC777Recipient}.
Emits {Minted} and {IERC20-Transfer} events.
Requirements
`account` cannot be the zero address.
if `account` is a contract, it must implement the {IERC777Recipient} interface._
_send
function _send(address from, address to, uint256 amount, bytes userData, bytes operatorData, bool requireReceptionAck) internal virtual
Send tokens
from
address
address token holder address
to
address
address recipient address
amount
uint256
uint256 amount of tokens to transfer
userData
bytes
bytes extra information provided by the token holder (if any)
operatorData
bytes
bytes extra information provided by the operator (if any)
requireReceptionAck
bool
if true, contract recipients are required to implement ERC777TokensRecipient
_burn
function _burn(address from, uint256 amount, bytes data, bytes operatorData) internal virtual
Burn tokens
from
address
address token holder address
amount
uint256
uint256 amount of tokens to burn
data
bytes
bytes extra information provided by the token holder
operatorData
bytes
bytes extra information provided by the operator (if any)
_move
function _move(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) private
_approve
function _approve(address holder, address spender, uint256 value) internal
_See {ERC20-_approve}.
Note that accounts cannot have allowance issued by their operators._
_callTokensToSend
function _callTokensToSend(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) private
Call from.tokensToSend() if the interface is registered
operator
address
address operator requesting the transfer
from
address
address token holder address
to
address
address recipient address
amount
uint256
uint256 amount of tokens to transfer
userData
bytes
bytes extra information provided by the token holder (if any)
operatorData
bytes
bytes extra information provided by the operator (if any)
_callTokensReceived
function _callTokensReceived(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData, bool requireReceptionAck) private
Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but tokensReceived() was not registered for the recipient
operator
address
address operator requesting the transfer
from
address
address token holder address
to
address
address recipient address
amount
uint256
uint256 amount of tokens to transfer
userData
bytes
bytes extra information provided by the token holder (if any)
operatorData
bytes
bytes extra information provided by the operator (if any)
requireReceptionAck
bool
if true, contract recipients are required to implement ERC777TokensRecipient
_beforeTokenTransfer
function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual
_Hook that is called before any token transfer. This includes calls to {send}, {transfer}, {operatorSend}, minting and burning.
Calling conditions:
when `from` and `to` are both non-zero, `amount` of ``from``'s tokens will be to transferred to `to`.
when `from` is zero, `amount` tokens will be minted for `to`.
when `to` is zero, `amount` of ``from``'s tokens will be burned.
`from` and `to` are never both zero.
To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]._
IERC777
_Interface of the ERC777Token standard as defined in the EIP.
This contract uses the https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let token holders and recipients react to token movements by using setting implementers for the associated interfaces in said registry. See {IERC1820Registry} and {ERC1820Implementer}._
name
function name() external view returns (string)
Returns the name of the token.
symbol
function symbol() external view returns (string)
Returns the symbol of the token, usually a shorter version of the name.
granularity
function granularity() external view returns (uint256)
_Returns the smallest part of the token that is not divisible. This means all token operations (creation, movement and destruction) must have amounts that are a multiple of this number.
For most token contracts, this value will equal 1._
totalSupply
function totalSupply() external view returns (uint256)
Returns the amount of tokens in existence.
balanceOf
function balanceOf(address owner) external view returns (uint256)
Returns the amount of tokens owned by an account (`owner`).
send
function send(address recipient, uint256 amount, bytes data) external
_Moves `amount` tokens from the caller's account to `recipient`.
If send or receive hooks are registered for the caller and `recipient`, the corresponding functions will be called with `data` and empty `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
Emits a {Sent} event.
Requirements
the caller must have at least `amount` tokens.
`recipient` cannot be the zero address.
if `recipient` is a contract, it must implement the {IERC777Recipient} interface._
burn
function burn(uint256 amount, bytes data) external
_Destroys `amount` tokens from the caller's account, reducing the total supply.
If a send hook is registered for the caller, the corresponding function will be called with `data` and empty `operatorData`. See {IERC777Sender}.
Emits a {Burned} event.
Requirements
the caller must have at least `amount` tokens._
isOperatorFor
function isOperatorFor(address operator, address tokenHolder) external view returns (bool)
_Returns true if an account is an operator of `tokenHolder`. Operators can send and burn tokens on behalf of their owners. All accounts are their own operator.
See {operatorSend} and {operatorBurn}._
authorizeOperator
function authorizeOperator(address operator) external
_Make an account an operator of the caller.
See {isOperatorFor}.
Emits an {AuthorizedOperator} event.
Requirements
`operator` cannot be calling address._
revokeOperator
function revokeOperator(address operator) external
_Revoke an account's operator status for the caller.
See {isOperatorFor} and {defaultOperators}.
Emits a {RevokedOperator} event.
Requirements
`operator` cannot be calling address._
defaultOperators
function defaultOperators() external view returns (address[])
_Returns the list of default operators. These accounts are operators for all token holders, even if {authorizeOperator} was never called on them.
This list is immutable, but individual holders may revoke these via {revokeOperator}, in which case {isOperatorFor} will return false._
operatorSend
function operatorSend(address sender, address recipient, uint256 amount, bytes data, bytes operatorData) external
_Moves `amount` tokens from `sender` to `recipient`. The caller must be an operator of `sender`.
If send or receive hooks are registered for `sender` and `recipient`, the corresponding functions will be called with `data` and `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
Emits a {Sent} event.
Requirements
`sender` cannot be the zero address.
`sender` must have at least `amount` tokens.
the caller must be an operator for `sender`.
`recipient` cannot be the zero address.
if `recipient` is a contract, it must implement the {IERC777Recipient} interface._
operatorBurn
function operatorBurn(address account, uint256 amount, bytes data, bytes operatorData) external
_Destroys `amount` tokens from `account`, reducing the total supply. The caller must be an operator of `account`.
If a send hook is registered for `account`, the corresponding function will be called with `data` and `operatorData`. See {IERC777Sender}.
Emits a {Burned} event.
Requirements
`account` cannot be the zero address.
`account` must have at least `amount` tokens.
the caller must be an operator for `account`._
Sent
event Sent(address operator, address from, address to, uint256 amount, bytes data, bytes operatorData)
Minted
event Minted(address operator, address to, uint256 amount, bytes data, bytes operatorData)
Burned
event Burned(address operator, address from, uint256 amount, bytes data, bytes operatorData)
AuthorizedOperator
event AuthorizedOperator(address operator, address tokenHolder)
RevokedOperator
event RevokedOperator(address operator, address tokenHolder)
IERC777Recipient
_Interface of the ERC777TokensRecipient standard as defined in the EIP.
Accounts can be notified of {IERC777} tokens being sent to them by having a contract implement this interface (contract holders can be their own implementer) and registering it on the https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
See {IERC1820Registry} and {ERC1820Implementer}._
tokensReceived
function tokensReceived(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) external
_Called by an {IERC777} token contract whenever tokens are being moved or created into a registered account (`to`). The type of operation is conveyed by `from` being the zero address or not.
This call occurs after the token contract's state is updated, so {IERC777-balanceOf}, etc., can be used to query the post-operation state.
This function may revert to prevent the operation from being executed._
IERC777Sender
_Interface of the ERC777TokensSender standard as defined in the EIP.
{IERC777} Token holders can be notified of operations performed on their tokens by having a contract implement this interface (contract holders can be their own implementer) and registering it on the https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
See {IERC1820Registry} and {ERC1820Implementer}._
tokensToSend
function tokensToSend(address operator, address from, address to, uint256 amount, bytes userData, bytes operatorData) external
_Called by an {IERC777} token contract whenever a registered holder's (`from`) tokens are about to be moved or destroyed. The type of operation is conveyed by `to` being the zero address or not.
This call occurs before the token contract's state is updated, so {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
This function may revert to prevent the operation from being executed._
ERC777PresetFixedSupply
_{ERC777} token, including:
Preminted initial supply
No access control mechanism (for minting/pausing) and hence no governance
Available since v3.4._
constructor
constructor(string name, string symbol, address[] defaultOperators, uint256 initialSupply, address owner) public
_Mints `initialSupply` amount of token and transfers them to `owner`.
See {ERC777-constructor}._
Address
Collection of functions related to the address type
isContract
function isContract(address account) internal view returns (bool)
_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 ====_
sendValue
function sendValue(address payable recipient, uint256 amount) internal
_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]._
functionCall
function functionCall(address target, bytes data) internal returns (bytes)
_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._
functionCall
function functionCall(address target, bytes data, string errorMessage) internal returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with `errorMessage` as a fallback revert reason when `target` reverts.
Available since v3.1._
functionCallWithValue
function functionCallWithValue(address target, bytes data, uint256 value) internal returns (bytes)
_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._
functionCallWithValue
function functionCallWithValue(address target, bytes data, uint256 value, string errorMessage) internal returns (bytes)
_Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but with `errorMessage` as a fallback revert reason when `target` reverts.
Available since v3.1._
functionStaticCall
function functionStaticCall(address target, bytes data) internal view returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but performing a static call.
Available since v3.3._
functionStaticCall
function functionStaticCall(address target, bytes data, string errorMessage) internal view returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a static call.
Available since v3.3._
functionDelegateCall
function functionDelegateCall(address target, bytes data) internal returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but performing a delegate call.
Available since v3.4._
functionDelegateCall
function functionDelegateCall(address target, bytes data, string errorMessage) internal returns (bytes)
_Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a delegate call.
Available since v3.4._
verifyCallResult
function verifyCallResult(bool success, bytes returndata, string errorMessage) internal pure returns (bytes)
_Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the revert reason using the provided one.
Available since v4.3._
Arrays
Collection of functions related to array types.
findUpperBound
function findUpperBound(uint256[] array, uint256 element) internal view returns (uint256)
_Searches a sorted `array` and returns the first index that contains a value greater or equal to `element`. If no such index exists (i.e. all values in the array are strictly less than `element`), the array length is returned. Time complexity O(log n).
`array` is expected to be sorted in ascending order, and to contain no repeated elements._
Context
_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._
_msgSender
function _msgSender() internal view virtual returns (address)
_msgData
function _msgData() internal view virtual returns (bytes)
Counters
_Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number of elements in a mapping, issuing ERC721 ids, or counting request ids.
Include with `using Counters for Counters.Counter;`_
Counter
struct Counter {
uint256 _value;
}
current
function current(struct Counters.Counter counter) internal view returns (uint256)
increment
function increment(struct Counters.Counter counter) internal
decrement
function decrement(struct Counters.Counter counter) internal
reset
function reset(struct Counters.Counter counter) internal
Multicall
_Provides a function to batch together multiple calls in a single external call.
Available since v4.1._
multicall
function multicall(bytes[] data) external returns (bytes[] results)
Receives and executes a batch of function calls on this contract.
StorageSlot
_Library for reading and writing primitive types to specific storage slots.
Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. This library helps with reading and writing to such slots without the need for inline assembly.
The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
Example usage to set ERC1967 implementation slot: ``` contract ERC1967 { bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
} ```
Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
AddressSlot
struct AddressSlot {
address value;
}
BooleanSlot
struct BooleanSlot {
bool value;
}
Bytes32Slot
struct Bytes32Slot {
bytes32 value;
}
Uint256Slot
struct Uint256Slot {
uint256 value;
}
getAddressSlot
function getAddressSlot(bytes32 slot) internal pure returns (struct StorageSlot.AddressSlot r)
Returns an `AddressSlot` with member `value` located at `slot`.
getBooleanSlot
function getBooleanSlot(bytes32 slot) internal pure returns (struct StorageSlot.BooleanSlot r)
Returns an `BooleanSlot` with member `value` located at `slot`.
getBytes32Slot
function getBytes32Slot(bytes32 slot) internal pure returns (struct StorageSlot.Bytes32Slot r)
Returns an `Bytes32Slot` with member `value` located at `slot`.
getUint256Slot
function getUint256Slot(bytes32 slot) internal pure returns (struct StorageSlot.Uint256Slot r)
Returns an `Uint256Slot` with member `value` located at `slot`.
Strings
String operations.
_HEX_SYMBOLS
bytes16 _HEX_SYMBOLS
toString
function toString(uint256 value) internal pure returns (string)
Converts a `uint256` to its ASCII `string` decimal representation.
toHexString
function toHexString(uint256 value) internal pure returns (string)
Converts a `uint256` to its ASCII `string` hexadecimal representation.
toHexString
function toHexString(uint256 value, uint256 length) internal pure returns (string)
Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
Timers
Tooling for timepoints, timers and delays
Timestamp
struct Timestamp {
uint64 _deadline;
}
getDeadline
function getDeadline(struct Timers.Timestamp timer) internal pure returns (uint64)
setDeadline
function setDeadline(struct Timers.Timestamp timer, uint64 timestamp) internal
reset
function reset(struct Timers.Timestamp timer) internal
isUnset
function isUnset(struct Timers.Timestamp timer) internal pure returns (bool)
isStarted
function isStarted(struct Timers.Timestamp timer) internal pure returns (bool)
isPending
function isPending(struct Timers.Timestamp timer) internal view returns (bool)
isExpired
function isExpired(struct Timers.Timestamp timer) internal view returns (bool)
BlockNumber
struct BlockNumber {
uint64 _deadline;
}
getDeadline
function getDeadline(struct Timers.BlockNumber timer) internal pure returns (uint64)
setDeadline
function setDeadline(struct Timers.BlockNumber timer, uint64 timestamp) internal
reset
function reset(struct Timers.BlockNumber timer) internal
isUnset
function isUnset(struct Timers.BlockNumber timer) internal pure returns (bool)
isStarted
function isStarted(struct Timers.BlockNumber timer) internal pure returns (bool)
isPending
function isPending(struct Timers.BlockNumber timer) internal view returns (bool)
isExpired
function isExpired(struct Timers.BlockNumber timer) internal view returns (bool)
ECDSA
_Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
These functions can be used to verify that a message was signed by the holder of the private keys of a given address._
RecoverError
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
_throwError
function _throwError(enum ECDSA.RecoverError error) private pure
tryRecover
function tryRecover(bytes32 hash, bytes signature) internal pure returns (address, enum ECDSA.RecoverError)
_Returns the address that signed a hashed message (`hash`) with `signature` or error string. This address can then be used for verification purposes.
The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: this function rejects them by requiring the `s` value to be in the lower half order, and the `v` value to be either 27 or 28.
IMPORTANT: `hash` must be the result of a hash operation for the verification to be secure: it is possible to craft signatures that recover to arbitrary addresses for non-hashed data. A safe way to ensure this is by receiving a hash of the original message (which may otherwise be too long), and then calling {toEthSignedMessageHash} on it.
Documentation for signature generation:
with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
Available since v4.3._
recover
function recover(bytes32 hash, bytes signature) internal pure returns (address)
_Returns the address that signed a hashed message (`hash`) with `signature`. This address can then be used for verification purposes.
The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: this function rejects them by requiring the `s` value to be in the lower half order, and the `v` value to be either 27 or 28.
IMPORTANT: `hash` must be the result of a hash operation for the verification to be secure: it is possible to craft signatures that recover to arbitrary addresses for non-hashed data. A safe way to ensure this is by receiving a hash of the original message (which may otherwise be too long), and then calling {toEthSignedMessageHash} on it._
tryRecover
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, enum ECDSA.RecoverError)
_Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
Available since v4.3._
recover
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address)
_Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
Available since v4.2._
tryRecover
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, enum ECDSA.RecoverError)
_Overload of {ECDSA-tryRecover} that receives the `v`, `r` and `s` signature fields separately.
Available since v4.3._
recover
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address)
Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. /
toEthSignedMessageHash
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32)
_Returns an Ethereum Signed Message, created from a `hash`. This produces hash corresponding to the one signed with the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method as part of EIP-191.
See {recover}. /_
toTypedDataHash
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32)
_Returns an Ethereum Signed Typed Data, created from a `domainSeparator` and a `structHash`. This produces hash corresponding to the one signed with the https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
See {recover}. /_
SignatureChecker
_Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with smart contract wallets such as Argent and Gnosis.
Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change through time. It could return true at block N and false at block N+1 (or the opposite).
Available since v4.1._
isValidSignatureNow
function isValidSignatureNow(address signer, bytes32 hash, bytes signature) internal view returns (bool)
EIP712
_https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in their contracts using a combination of `abi.encode` and `keccak256`.
This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA ({_hashTypedDataV4}).
The implementation of the domain separator was designed to be as efficient as possible while still properly updating the chain id to protect against replay attacks on an eventual fork of the chain.
NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
Available since v3.4._
_CACHED_DOMAIN_SEPARATOR
bytes32 _CACHED_DOMAIN_SEPARATOR
_CACHED_CHAIN_ID
uint256 _CACHED_CHAIN_ID
_HASHED_NAME
bytes32 _HASHED_NAME
_HASHED_VERSION
bytes32 _HASHED_VERSION
_TYPE_HASH
bytes32 _TYPE_HASH
constructor
constructor(string name, string version) internal
_Initializes the domain separator and parameter caches.
The meaning of `name` and `version` is specified in https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
`name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
`version`: the current major version of the signing domain.
NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart contract upgrade]._
_domainSeparatorV4
function _domainSeparatorV4() internal view returns (bytes32)
Returns the domain separator for the current chain.
_buildDomainSeparator
function _buildDomainSeparator(bytes32 typeHash, bytes32 nameHash, bytes32 versionHash) private view returns (bytes32)
_hashTypedDataV4
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32)
_Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this function returns the hash of the fully encoded EIP712 message for this domain.
This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
```solidity bytes32 digest = hashTypedDataV4(keccak256(abi.encode( keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents)) ))); address signer = ECDSA.recover(digest, signature); ```
ConditionalEscrow
Base abstract escrow to only allow withdrawal if a condition is met. Intended usage: See {Escrow}. Same usage guidelines apply here.
withdrawalAllowed
function withdrawalAllowed(address payee) public view virtual returns (bool)
Returns whether an address is allowed to withdraw their funds. To be implemented by derived contracts.
payee
address
The destination address of the funds.
withdraw
function withdraw(address payable payee) public virtual
_Withdraw accumulated balance for a payee, forwarding all gas to the recipient.
WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. Make sure you trust the recipient, or are either following the checks-effects-interactions pattern or using {ReentrancyGuard}._
payee
address payable
The address whose funds will be withdrawn and transferred to.
Escrow
_Base escrow contract, holds funds designated for a payee until they withdraw them.
Intended usage: This contract (and derived escrow contracts) should be a standalone contract, that only interacts with the contract that instantiated it. That way, it is guaranteed that all Ether will be handled according to the `Escrow` rules, and there is no need to check for payable functions or transfers in the inheritance tree. The contract that uses the escrow as its payment method should be its owner, and provide public methods redirecting to the escrow's deposit and withdraw._
Deposited
event Deposited(address payee, uint256 weiAmount)
Withdrawn
event Withdrawn(address payee, uint256 weiAmount)
_deposits
mapping(address => uint256) _deposits
depositsOf
function depositsOf(address payee) public view returns (uint256)
deposit
function deposit(address payee) public payable virtual
Stores the sent amount as credit to be withdrawn.
payee
address
The destination address of the funds.
withdraw
function withdraw(address payable payee) public virtual
_Withdraw accumulated balance for a payee, forwarding all gas to the recipient.
WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. Make sure you trust the recipient, or are either following the checks-effects-interactions pattern or using {ReentrancyGuard}._
payee
address payable
The address whose funds will be withdrawn and transferred to.
RefundEscrow
Escrow that holds funds for a beneficiary, deposited from multiple parties. Intended usage: See {Escrow}. Same usage guidelines apply here. The owner account (that is, the contract that instantiates this contract) may deposit, close the deposit period, and allow for either withdrawal by the beneficiary, or refunds to the depositors. All interactions with `RefundEscrow` will be made through the owner contract.
State
enum State {
Active,
Refunding,
Closed
}
RefundsClosed
event RefundsClosed()
RefundsEnabled
event RefundsEnabled()
_state
enum RefundEscrow.State _state
_beneficiary
address payable _beneficiary
constructor
constructor(address payable beneficiary_) public
Constructor.
beneficiary_
address payable
The beneficiary of the deposits.
state
function state() public view virtual returns (enum RefundEscrow.State)
[0]
enum RefundEscrow.State
The current state of the escrow.
beneficiary
function beneficiary() public view virtual returns (address payable)
[0]
address payable
The beneficiary of the escrow.
deposit
function deposit(address refundee) public payable virtual
Stores funds that may later be refunded.
refundee
address
The address funds will be sent to if a refund occurs.
close
function close() public virtual
Allows for the beneficiary to withdraw their funds, rejecting further deposits.
enableRefunds
function enableRefunds() public virtual
Allows for refunds to take place, rejecting further deposits.
beneficiaryWithdraw
function beneficiaryWithdraw() public virtual
Withdraws the beneficiary's funds.
withdrawalAllowed
function withdrawalAllowed(address) public view returns (bool)
Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a 'payee' argument, but we ignore it here since the condition is global, not per-payee.
ERC165
_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._
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
ERC165Checker
_Library used to query support of an interface declared via {IERC165}.
Note that these functions return the actual result of the query: they do not `revert` if an interface is not supported. It is up to the caller to decide what to do in these cases._
_INTERFACE_ID_INVALID
bytes4 _INTERFACE_ID_INVALID
supportsERC165
function supportsERC165(address account) internal view returns (bool)
Returns true if `account` supports the {IERC165} interface,
supportsInterface
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool)
_Returns true if `account` supports the interface defined by `interfaceId`. Support for {IERC165} itself is queried automatically.
See {IERC165-supportsInterface}._
getSupportedInterfaces
function getSupportedInterfaces(address account, bytes4[] interfaceIds) internal view returns (bool[])
_Returns a boolean array where each value corresponds to the interfaces passed in and whether they're supported or not. This allows you to batch check interfaces for a contract where your expectation is that some interfaces may not be supported.
See {IERC165-supportsInterface}.
Available since v3.4._
supportsAllInterfaces
function supportsAllInterfaces(address account, bytes4[] interfaceIds) internal view returns (bool)
_Returns true if `account` supports all the interfaces defined in `interfaceIds`. Support for {IERC165} itself is queried automatically.
Batch-querying can lead to gas savings by skipping repeated checks for {IERC165} support.
See {IERC165-supportsInterface}._
_supportsERC165Interface
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool)
Query if a contract implements an interface, does not check ERC165 support
Assumes that account contains a contract that supports ERC165, otherwise the behavior of this method is undefined. This precondition can be checked with {supportsERC165}. Interface identification is specified in ERC-165.
account
address
The address of the contract to query for support of an interface
interfaceId
bytes4
The interface identifier, as specified in ERC-165
[0]
bool
true if the contract at account indicates support of the interface with identifier interfaceId, false otherwise
ERC165Storage
_Storage based implementation of the {IERC165} interface.
Contracts may inherit from this and call {registerInterface} to declare their support of an interface.
_supportedInterfaces
mapping(bytes4 => bool) _supportedInterfaces
Mapping of interface ids to whether or not it's supported.
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool)
See {IERC165-supportsInterface}.
_registerInterface
function _registerInterface(bytes4 interfaceId) internal virtual
_Registers the contract as an implementer of the interface defined by `interfaceId`. Support of the actual ERC165 interface is automatic and registering its interface id is not required.
See {IERC165-supportsInterface}.
Requirements:
`interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`)._
IERC165
_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}._
supportsInterface
function supportsInterface(bytes4 interfaceId) external view returns (bool)
_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._
IERC1820Registry
_Interface of the global ERC1820 Registry, as defined in the https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register implementers for interfaces in this registry, as well as query support.
Implementers may be shared by multiple accounts, and can also implement more than a single interface for each account. Contracts can implement interfaces for themselves, but externally-owned accounts (EOA) must delegate this to a contract.
{IERC165} interfaces can also be queried via the registry.
For an in-depth explanation and source code analysis, see the EIP text._
setManager
function setManager(address account, address newManager) external
_Sets `newManager` as the manager for `account`. A manager of an account is able to set interface implementers for it.
By default, each account is its own manager. Passing a value of `0x0` in `newManager` will reset the manager to this initial state.
Emits a {ManagerChanged} event.
Requirements:
the caller must be the current manager for `account`._
getManager
function getManager(address account) external view returns (address)
_Returns the manager for `account`.
See {setManager}._
setInterfaceImplementer
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external
_Sets the `implementer` contract as ``account``'s implementer for `interfaceHash`.
`account` being the zero address is an alias for the caller's address. The zero address can also be used in `implementer` to remove an old one.
See {interfaceHash} to learn how these are created.
Emits an {InterfaceImplementerSet} event.
Requirements:
the caller must be the current manager for `account`.
`interfaceHash` must not be an {IERC165} interface id (i.e. it must not end in 28 zeroes).
`implementer` must implement {IERC1820Implementer} and return true when queried for support, unless `implementer` is the caller. See {IERC1820Implementer-canImplementInterfaceForAddress}._
getInterfaceImplementer
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address)
_Returns the implementer of `interfaceHash` for `account`. If no such implementer is registered, returns the zero address.
If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 zeroes), `account` will be queried for support of it.
`account` being the zero address is an alias for the caller's address._
interfaceHash
function interfaceHash(string interfaceName) external pure returns (bytes32)
Returns the interface hash for an `interfaceName`, as defined in the corresponding https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
updateERC165Cache
function updateERC165Cache(address account, bytes4 interfaceId) external
Updates the cache with whether the contract implements an ERC165 interface or not.
account
address
Address of the contract for which to update the cache.
interfaceId
bytes4
ERC165 interface for which to update the cache.
implementsERC165Interface
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool)
Checks whether a contract implements an ERC165 interface or not. If the result is not cached a direct lookup on the contract address is performed. If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling {updateERC165Cache} with the contract address.
account
address
Address of the contract to check.
interfaceId
bytes4
ERC165 interface to check.
[0]
bool
True if `account` implements `interfaceId`, false otherwise.
implementsERC165InterfaceNoCache
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool)
Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
account
address
Address of the contract to check.
interfaceId
bytes4
ERC165 interface to check.
[0]
bool
True if `account` implements `interfaceId`, false otherwise.
InterfaceImplementerSet
event InterfaceImplementerSet(address account, bytes32 interfaceHash, address implementer)
ManagerChanged
event ManagerChanged(address account, address newManager)
Math
Standard math utilities missing in the Solidity language.
max
function max(uint256 a, uint256 b) internal pure returns (uint256)
Returns the largest of two numbers.
min
function min(uint256 a, uint256 b) internal pure returns (uint256)
Returns the smallest of two numbers.
average
function average(uint256 a, uint256 b) internal pure returns (uint256)
Returns the average of two numbers. The result is rounded towards zero.
ceilDiv
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the ceiling of the division of two numbers.
This differs from standard division with `/` in that it rounds up instead of rounding down._
SafeCast
_Wrappers over Solidity's uintXX/intXX casting operators with added overflow checks.
Downcasting from uint256/int256 in Solidity does not revert on overflow. This can easily result in undesired exploitation or bugs, since developers usually assume that overflows raise errors. `SafeCast` restores this intuition by reverting the transaction when such an operation overflows.
Using this library instead of the unchecked operations eliminates an entire class of bugs, so it's recommended to use it always.
Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing all math on `uint256` and `int256` and then downcasting._
toUint224
function toUint224(uint256 value) internal pure returns (uint224)
_Returns the downcasted uint224 from uint256, reverting on overflow (when the input is greater than largest uint224).
Counterpart to Solidity's `uint224` operator.
Requirements:
input must fit into 224 bits_
toUint128
function toUint128(uint256 value) internal pure returns (uint128)
_Returns the downcasted uint128 from uint256, reverting on overflow (when the input is greater than largest uint128).
Counterpart to Solidity's `uint128` operator.
Requirements:
input must fit into 128 bits_
toUint96
function toUint96(uint256 value) internal pure returns (uint96)
_Returns the downcasted uint96 from uint256, reverting on overflow (when the input is greater than largest uint96).
Counterpart to Solidity's `uint96` operator.
Requirements:
input must fit into 96 bits_
toUint64
function toUint64(uint256 value) internal pure returns (uint64)
_Returns the downcasted uint64 from uint256, reverting on overflow (when the input is greater than largest uint64).
Counterpart to Solidity's `uint64` operator.
Requirements:
input must fit into 64 bits_
toUint32
function toUint32(uint256 value) internal pure returns (uint32)
_Returns the downcasted uint32 from uint256, reverting on overflow (when the input is greater than largest uint32).
Counterpart to Solidity's `uint32` operator.
Requirements:
input must fit into 32 bits_
toUint16
function toUint16(uint256 value) internal pure returns (uint16)
_Returns the downcasted uint16 from uint256, reverting on overflow (when the input is greater than largest uint16).
Counterpart to Solidity's `uint16` operator.
Requirements:
input must fit into 16 bits_
toUint8
function toUint8(uint256 value) internal pure returns (uint8)
_Returns the downcasted uint8 from uint256, reverting on overflow (when the input is greater than largest uint8).
Counterpart to Solidity's `uint8` operator.
Requirements:
input must fit into 8 bits._
toUint256
function toUint256(int256 value) internal pure returns (uint256)
_Converts a signed int256 into an unsigned uint256.
Requirements:
input must be greater than or equal to 0._
toInt128
function toInt128(int256 value) internal pure returns (int128)
_Returns the downcasted int128 from int256, reverting on overflow (when the input is less than smallest int128 or greater than largest int128).
Counterpart to Solidity's `int128` operator.
Requirements:
input must fit into 128 bits
Available since v3.1._
toInt64
function toInt64(int256 value) internal pure returns (int64)
_Returns the downcasted int64 from int256, reverting on overflow (when the input is less than smallest int64 or greater than largest int64).
Counterpart to Solidity's `int64` operator.
Requirements:
input must fit into 64 bits
Available since v3.1._
toInt32
function toInt32(int256 value) internal pure returns (int32)
_Returns the downcasted int32 from int256, reverting on overflow (when the input is less than smallest int32 or greater than largest int32).
Counterpart to Solidity's `int32` operator.
Requirements:
input must fit into 32 bits
Available since v3.1._
toInt16
function toInt16(int256 value) internal pure returns (int16)
_Returns the downcasted int16 from int256, reverting on overflow (when the input is less than smallest int16 or greater than largest int16).
Counterpart to Solidity's `int16` operator.
Requirements:
input must fit into 16 bits
Available since v3.1._
toInt8
function toInt8(int256 value) internal pure returns (int8)
_Returns the downcasted int8 from int256, reverting on overflow (when the input is less than smallest int8 or greater than largest int8).
Counterpart to Solidity's `int8` operator.
Requirements:
input must fit into 8 bits.
Available since v3.1._
toInt256
function toInt256(uint256 value) internal pure returns (int256)
_Converts an unsigned uint256 into a signed int256.
Requirements:
input must be less than or equal to maxInt256._
SafeMath
_Wrappers over Solidity's arithmetic operations.
NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler now has built in overflow checking._
tryAdd
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the addition of two unsigned integers, with an overflow flag.
Available since v3.4._
trySub
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the substraction of two unsigned integers, with an overflow flag.
Available since v3.4._
tryMul
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the multiplication of two unsigned integers, with an overflow flag.
Available since v3.4._
tryDiv
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the division of two unsigned integers, with a division by zero flag.
Available since v3.4._
tryMod
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the remainder of dividing two unsigned integers, with a division by zero flag.
Available since v3.4._
add
function add(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the addition of two unsigned integers, reverting on overflow.
Counterpart to Solidity's `+` operator.
Requirements:
Addition cannot overflow._
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the subtraction of two unsigned integers, reverting on overflow (when the result is negative).
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the multiplication of two unsigned integers, reverting on overflow.
Counterpart to Solidity's `*` operator.
Requirements:
Multiplication cannot overflow._
div
function div(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the integer division of two unsigned integers, reverting on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator.
Requirements:
The divisor cannot be zero._
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting when dividing by zero.
Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
sub
function sub(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the subtraction of two unsigned integers, reverting with custom message on overflow (when the result is negative).
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {trySub}.
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
div
function div(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the integer division of two unsigned integers, reverting with custom message on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator. Note: this function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
mod
function mod(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting with custom message when dividing by zero.
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryMod}.
Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
EnumerableMap
_Library for managing an enumerable variant of Solidity's https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] type.
Maps have the following properties:
Entries are added, removed, and checked for existence in constant time (O(1)).
Entries are enumerated in O(n). No guarantees are made on the ordering.
``` contract Example { // Add the library methods using EnumerableMap for EnumerableMap.UintToAddressMap;
// Declare a set state variable
EnumerableMap.UintToAddressMap private myMap;
} ```
As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are supported._
Map
struct Map {
struct EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
_set
function _set(struct EnumerableMap.Map map, bytes32 key, bytes32 value) private returns (bool)
_Adds a key-value pair to a map, or updates the value for an existing key. O(1).
Returns true if the key was added to the map, that is if it was not already present._
_remove
function _remove(struct EnumerableMap.Map map, bytes32 key) private returns (bool)
_Removes a key-value pair from a map. O(1).
Returns true if the key was removed from the map, that is if it was present._
_contains
function _contains(struct EnumerableMap.Map map, bytes32 key) private view returns (bool)
Returns true if the key is in the map. O(1).
_length
function _length(struct EnumerableMap.Map map) private view returns (uint256)
Returns the number of key-value pairs in the map. O(1).
_at
function _at(struct EnumerableMap.Map map, uint256 index) private view returns (bytes32, bytes32)
_Returns the key-value pair stored at position `index` in the map. O(1).
Note that there are no guarantees on the ordering of entries inside the array, and it may change when more entries are added or removed.
Requirements:
`index` must be strictly less than {length}._
_tryGet
function _tryGet(struct EnumerableMap.Map map, bytes32 key) private view returns (bool, bytes32)
Tries to returns the value associated with `key`. O(1). Does not revert if `key` is not in the map.
_get
function _get(struct EnumerableMap.Map map, bytes32 key) private view returns (bytes32)
_Returns the value associated with `key`. O(1).
Requirements:
`key` must be in the map._
_get
function _get(struct EnumerableMap.Map map, bytes32 key, string errorMessage) private view returns (bytes32)
_Same as {_get}, with a custom error message when `key` is not in the map.
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryGet}.
UintToAddressMap
struct UintToAddressMap {
struct EnumerableMap.Map _inner;
}
set
function set(struct EnumerableMap.UintToAddressMap map, uint256 key, address value) internal returns (bool)
_Adds a key-value pair to a map, or updates the value for an existing key. O(1).
Returns true if the key was added to the map, that is if it was not already present._
remove
function remove(struct EnumerableMap.UintToAddressMap map, uint256 key) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the key was removed from the map, that is if it was present._
contains
function contains(struct EnumerableMap.UintToAddressMap map, uint256 key) internal view returns (bool)
Returns true if the key is in the map. O(1).
length
function length(struct EnumerableMap.UintToAddressMap map) internal view returns (uint256)
Returns the number of elements in the map. O(1).
at
function at(struct EnumerableMap.UintToAddressMap map, uint256 index) internal view returns (uint256, address)
_Returns the element stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed.
Requirements:
`index` must be strictly less than {length}._
tryGet
function tryGet(struct EnumerableMap.UintToAddressMap map, uint256 key) internal view returns (bool, address)
_Tries to returns the value associated with `key`. O(1). Does not revert if `key` is not in the map.
Available since v3.4._
get
function get(struct EnumerableMap.UintToAddressMap map, uint256 key) internal view returns (address)
_Returns the value associated with `key`. O(1).
Requirements:
`key` must be in the map._
get
function get(struct EnumerableMap.UintToAddressMap map, uint256 key, string errorMessage) internal view returns (address)
_Same as {get}, with a custom error message when `key` is not in the map.
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryGet}._
EnumerableSet
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._
Set
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
_add
function _add(struct EnumerableSet.Set set, bytes32 value) private returns (bool)
_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._
_remove
function _remove(struct EnumerableSet.Set set, bytes32 value) private returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
_contains
function _contains(struct EnumerableSet.Set set, bytes32 value) private view returns (bool)
Returns true if the value is in the set. O(1).
_length
function _length(struct EnumerableSet.Set set) private view returns (uint256)
Returns the number of values on the set. O(1).
_at
function _at(struct EnumerableSet.Set set, uint256 index) private view returns (bytes32)
_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}._
_values
function _values(struct EnumerableSet.Set set) private view returns (bytes32[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
Bytes32Set
struct Bytes32Set {
struct EnumerableSet.Set _inner;
}
add
function add(struct EnumerableSet.Bytes32Set set, bytes32 value) internal returns (bool)
_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._
remove
function remove(struct EnumerableSet.Bytes32Set set, bytes32 value) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
contains
function contains(struct EnumerableSet.Bytes32Set set, bytes32 value) internal view returns (bool)
Returns true if the value is in the set. O(1).
length
function length(struct EnumerableSet.Bytes32Set set) internal view returns (uint256)
Returns the number of values in the set. O(1).
at
function at(struct EnumerableSet.Bytes32Set set, uint256 index) internal view returns (bytes32)
_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}._
values
function values(struct EnumerableSet.Bytes32Set set) internal view returns (bytes32[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
AddressSet
struct AddressSet {
struct EnumerableSet.Set _inner;
}
add
function add(struct EnumerableSet.AddressSet set, address value) internal returns (bool)
_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._
remove
function remove(struct EnumerableSet.AddressSet set, address value) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
contains
function contains(struct EnumerableSet.AddressSet set, address value) internal view returns (bool)
Returns true if the value is in the set. O(1).
length
function length(struct EnumerableSet.AddressSet set) internal view returns (uint256)
Returns the number of values in the set. O(1).
at
function at(struct EnumerableSet.AddressSet set, uint256 index) internal view returns (address)
_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}._
values
function values(struct EnumerableSet.AddressSet set) internal view returns (address[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
UintSet
struct UintSet {
struct EnumerableSet.Set _inner;
}
add
function add(struct EnumerableSet.UintSet set, uint256 value) internal returns (bool)
_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._
remove
function remove(struct EnumerableSet.UintSet set, uint256 value) internal returns (bool)
_Removes a value from a set. O(1).
Returns true if the value was removed from the set, that is if it was present._
contains
function contains(struct EnumerableSet.UintSet set, uint256 value) internal view returns (bool)
Returns true if the value is in the set. O(1).
length
function length(struct EnumerableSet.UintSet set) internal view returns (uint256)
Returns the number of values on the set. O(1).
at
function at(struct EnumerableSet.UintSet set, uint256 index) internal view returns (uint256)
_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}._
values
function values(struct EnumerableSet.UintSet set) internal view returns (uint256[])
_Return the entire set in an array
WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that this function has an unbounded cost, and using it as part of a state-changing function may render the function uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block._
PriceProviderAggregator
MODERATOR_ROLE
bytes32 MODERATOR_ROLE
usdDecimals
uint8 usdDecimals
tokenPriceProvider
mapping(address => struct PriceProviderAggregator.PriceProviderInfo) tokenPriceProvider
PriceProviderInfo
struct PriceProviderInfo {
address priceProvider;
bool hasSignedFunction;
}
GrandModeratorRole
event GrandModeratorRole(address who, address newModerator)
RevokeModeratorRole
event RevokeModeratorRole(address who, address moderator)
SetTokenAndPriceProvider
event SetTokenAndPriceProvider(address who, address token, address priceProvider)
ChangeActive
event ChangeActive(address who, address priceProvider, address token, bool active)
initialize
function initialize() public
onlyAdmin
modifier onlyAdmin()
onlyModerator
modifier onlyModerator()
grandModerator
function grandModerator(address newModerator) public
revokeModerator
function revokeModerator(address moderator) public
setTokenAndPriceProvider
function setTokenAndPriceProvider(address token, address priceProvider, bool hasFunctionWithSign) public
sets price provider to `token`
token
address
the address of token
priceProvider
address
the address of price provider. Should implememnt the interface of `PriceProvider`
hasFunctionWithSign
bool
true - if price provider has function with signatures false - if price provider does not have function with signatures
changeActive
function changeActive(address priceProvider, address token, bool active) public
getPrice
function getPrice(address token) public view returns (uint256 priceMantissa, uint8 priceDecimals)
price = priceMantissa / (10 ** priceDecimals)
returns tuple (priceMantissa, priceDecimals)
token
address
the address of token wich price is to return
getPriceSigned
function getPriceSigned(address token, uint256 priceMantissa, uint256 validTo, bytes signature) public view returns (uint256 priceMantissa_, uint8 priceDecimals)
returns the tupple (priceMantissa, priceDecimals) of token multiplied by 10 ** priceDecimals given by price provider. price can be calculated as priceMantissa / (10 ** priceDecimals) i.e. price = priceMantissa / (10 ** priceDecimals)
token
address
the address of token
priceMantissa
uint256
- the price of token (used in verifying the signature)
validTo
uint256
- the timestamp in seconds (used in verifying the signature)
signature
bytes
- the backend signature of secp256k1. length is 65 bytes
getEvaluation
function getEvaluation(address token, uint256 tokenAmount) public view returns (uint256 evaluation)
returns the USD evaluation of token by its `tokenAmount`
token
address
the address of token to evaluate
tokenAmount
uint256
the amount of token to evaluate
getEvaluationSigned
function getEvaluationSigned(address token, uint256 tokenAmount, uint256 priceMantissa, uint256 validTo, bytes signature) public view returns (uint256 evaluation)
returns the USD evaluation of token by its `tokenAmount`
token
address
the address of token
tokenAmount
uint256
the amount of token including decimals
priceMantissa
uint256
- the price of token (used in verifying the signature)
validTo
uint256
- the timestamp in seconds (used in verifying the signature)
signature
bytes
- the backend signature of secp256k1. length is 65 bytes
BackendPriceProvider
Backend price verifier.
TRUSTED_BACKEND_ROLE
bytes32 TRUSTED_BACKEND_ROLE
DESCRIPTION
string DESCRIPTION
usdDecimals
uint8 usdDecimals
backendMetadata
mapping(address => struct BackendPriceProvider.BackendMetadata) backendMetadata
BackendMetadata
struct BackendMetadata {
bool isListed;
bool isActive;
}
GrandTrustedBackendRole
event GrandTrustedBackendRole(address who, address newTrustedBackend)
RevokeTrustedBackendRole
event RevokeTrustedBackendRole(address who, address trustedBackend)
SetToken
event SetToken(address who, address token)
ChangeActive
event ChangeActive(address who, address token, bool active)
initialize
function initialize() public
onlyAdmin
modifier onlyAdmin()
onlyTrustedBackend
modifier onlyTrustedBackend()
grandTrustedBackendRole
function grandTrustedBackendRole(address newTrustedBackend) public
revokeTrustedBackendRole
function revokeTrustedBackendRole(address trustedBackend) public
setToken
function setToken(address token) public
changeActive
function changeActive(address token, bool active) public
getMessageHash
function getMessageHash(address token, uint256 priceMantissa, uint256 validTo) public pure returns (bytes32)
step. Backend creates offchain data and get hash of this data. This data calls message.
returns the keccak256 of concatenated input data
token
address
the address of asset
priceMantissa
uint256
the price of asset that include decimals
validTo
uint256
the unix timestamp in seconds that define the validity of given price to `validTo` timestamp
getEthSignedMessageHash
function getEthSignedMessageHash(bytes32 messageHash) public pure returns (bytes32)
step. Backend formatting the message and get hash of this message.
returns the keccak256 of formatted message
messageHash
bytes32
the keccak256 of message
verify
function verify(address token, uint256 priceMantissa, uint256 validTo, bytes signature) public view returns (bool)
step. Smart contract verify the message (tuple)
returns true if the message is signed by trusted backend. Else returns false.
token
address
the address of asset
priceMantissa
uint256
the price of asset that include decimals
validTo
uint256
the unix timestamp in seconds that define the validity of given price to `validTo` timestamp
signature
bytes
the sign of message.
recoverSigner
function recoverSigner(bytes32 ethSignedMessageHash, bytes signature) public pure returns (address)
returns the signer of `ethSignedMessageHash`
isListed
function isListed(address token) public view returns (bool)
isActive
function isActive(address token) public view returns (bool)
getPrice
function getPrice(address token) public pure returns (uint256 price, uint8 priceDecimals)
Returns the latest asset price and price decimals
token
address
the token address
getPriceSigned
function getPriceSigned(address token, uint256 priceMantissa, uint256 validTo, bytes signature) public view returns (uint256 _priceMantissa, uint8 priceDecimals)
getEvaluation
function getEvaluation(address token, uint256 tokenAmount) public pure returns (uint256 evaluation)
getEvaluationSigned
function getEvaluationSigned(address token, uint256 tokenAmount, uint256 priceMantissa, uint256 validTo, bytes signature) public view returns (uint256 evaluation)
return the evaluation in $ of `tokenAmount` with signed price
token
address
the address of token to get evaluation in $
tokenAmount
uint256
the amount of token to get evaluation. Amount is scaled by 10 in power token decimals
priceMantissa
uint256
the price multiplied by priceDecimals. The dimension of priceMantissa should be $/token
validTo
uint256
the timestamp in seconds, when price is gonna be not valid.
signature
bytes
the ECDSA sign on eliptic curve secp256k1.
getPriceDecimals
function getPriceDecimals() public view returns (uint8)
ChainlinkPriceProvider
Chainlink price provider
MODERATOR_ROLE
bytes32 MODERATOR_ROLE
DESCRIPTION
string DESCRIPTION
usdDecimals
uint8 usdDecimals
chainlinkMetadata
mapping(address => struct ChainlinkPriceProvider.ChainlinkMetadata) chainlinkMetadata
ChainlinkMetadata
struct ChainlinkMetadata {
bool isActive;
address[] aggregatorPath;
}
GrandModeratorRole
event GrandModeratorRole(address who, address newModerator)
RevokeModeratorRole
event RevokeModeratorRole(address who, address moderator)
SetTokenAndAggregator
event SetTokenAndAggregator(address who, address token, address[] aggeregatorPath)
ChangeActive
event ChangeActive(address who, address token, bool active)
initialize
function initialize() public
onlyAdmin
modifier onlyAdmin()
onlyModerator
modifier onlyModerator()
grandModerator
function grandModerator(address newModerator) public
revokeModerator
function revokeModerator(address moderator) public
setTokenAndAggregator
function setTokenAndAggregator(address token, address[] aggregatorPath) public
changeActive
function changeActive(address token, bool active) public
isListed
function isListed(address token) public view returns (bool)
isActive
function isActive(address token) public view returns (bool)
getPrice
function getPrice(address token) public view returns (uint256 priceMantissa, uint8 priceDecimals)
Returns the latest asset price mantissa and price decimals [price] = USD/token
First step is get priceMantissa with priceDecimals by this formula: price = 1 * 10 ** tokenDecimals * (chainlinkPrice_1 / 10 ** priceDecimals_1) * ... * (chainlinkPrice_n / 10 ** priceDecimals_n) = = 10 ** tokenDecimals (chainlinkPrice_1 * ... * chainlinkPrice_n) / 10 ** (priceDecimals_1 + ... + priceDecimals_n) Second step is scale priceMantissa to usdDecimals
token
address
the token address
getEvaluation
function getEvaluation(address token, uint256 tokenAmount) public view returns (uint256 evaluation)
returns the equivalent amount in USD
token
address
the address of token
tokenAmount
uint256
the amount of token
getPriceDecimals
function getPriceDecimals() public view returns (uint8)
PriceProvider
changeActive
function changeActive(address token, bool active) public virtual
isActive
function isActive(address token) public view virtual returns (bool)
isListed
function isListed(address token) public view virtual returns (bool)
getPrice
function getPrice(address token) public view virtual returns (uint256 priceMantissa, uint8 priceDecimals)
getPriceSigned
function getPriceSigned(address token, uint256 priceMantissa, uint256 validTo, bytes signature) public view virtual returns (uint256 _priceMantissa, uint8 _priceDecimals)
getEvaluation
function getEvaluation(address token, uint256 tokenAmount) public view virtual returns (uint256 evaluation)
getEvaluationSigned
function getEvaluationSigned(address token, uint256 tokenAmount, uint256 priceMantissa, uint256 validTo, bytes signature) public view virtual returns (uint256 evaluation)
return the evaluation in $ of `tokenAmount` with signed price
token
address
the address of token to get evaluation in $
tokenAmount
uint256
the amount of token to get evaluation. Amount is scaled by 10 in power token decimals
priceMantissa
uint256
the price multiplied by priceDecimals. The dimension of priceMantissa should be $/token
validTo
uint256
the timestamp in seconds, when price is gonna be not valid.
signature
bytes
the ECDSA sign on eliptic curve secp256k1.
getPriceDecimals
function getPriceDecimals() public view virtual returns (uint8 priceDecimals)
UniswapV2PriceProvider
UniswapV2 price provider This implementation can be affected by price manipulation due to not using TWAP For development purposes only
MODERATOR_ROLE
bytes32 MODERATOR_ROLE
DESCRIPTION
string DESCRIPTION
usdDecimals
uint8 usdDecimals
uniswapV2Metadata
mapping(address => struct UniswapV2PriceProvider.UniswapV2Metadata) uniswapV2Metadata
UniswapV2Metadata
struct UniswapV2Metadata {
bool isActive;
address pair;
address pairAsset;
uint8 tokenDecimals;
uint8 pairAssetDecimals;
}
GrandModeratorRole
event GrandModeratorRole(address who, address newModerator)
RevokeModeratorRole
event RevokeModeratorRole(address who, address moderator)
SetTokenAndPair
event SetTokenAndPair(address who, address token, address pair)
ChangeActive
event ChangeActive(address who, address token, bool active)
initialize
function initialize() public
onlyAdmin
modifier onlyAdmin()
onlyModerator
modifier onlyModerator()
grandModerator
function grandModerator(address newModerator) public
revokeModerator
function revokeModerator(address moderator) public
setTokenAndPair
function setTokenAndPair(address token, address pair) public
changeActive
function changeActive(address token, bool active) public
isListed
function isListed(address token) public view returns (bool)
isActive
function isActive(address token) public view returns (bool)
getPrice
function getPrice(address token) public view returns (uint256 price, uint8 priceDecimals)
getEvaluation
function getEvaluation(address token, uint256 tokenAmount) public view returns (uint256 evaluation)
getReserves
function getReserves(address uniswapPair, address tokenA, address tokenB) public view returns (uint256 reserveA, uint256 reserveB)
getPriceDecimals
function getPriceDecimals() public view returns (uint8)
AggregatorV3Interface
decimals
function decimals() external view returns (uint8)
description
function description() external view returns (string)
version
function version() external view returns (uint256)
getRoundData
function getRoundData(uint80 _roundId) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
latestRoundData
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
latestAnswer
function latestAnswer() external view returns (uint256 answer)
IUniswapV2Pair
Approval
event Approval(address owner, address spender, uint256 value)
Transfer
event Transfer(address from, address to, uint256 value)
name
function name() external pure returns (string)
symbol
function symbol() external pure returns (string)
decimals
function decimals() external pure returns (uint8)
totalSupply
function totalSupply() external view returns (uint256)
balanceOf
function balanceOf(address owner) external view returns (uint256)
allowance
function allowance(address owner, address spender) external view returns (uint256)
approve
function approve(address spender, uint256 value) external returns (bool)
transfer
function transfer(address to, uint256 value) external returns (bool)
transferFrom
function transferFrom(address from, address to, uint256 value) external returns (bool)
DOMAIN_SEPARATOR
function DOMAIN_SEPARATOR() external view returns (bytes32)
PERMIT_TYPEHASH
function PERMIT_TYPEHASH() external pure returns (bytes32)
nonces
function nonces(address owner) external view returns (uint256)
permit
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external
Mint
event Mint(address sender, uint256 amount0, uint256 amount1)
Burn
event Burn(address sender, uint256 amount0, uint256 amount1, address to)
Swap
event Swap(address sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address to)
Sync
event Sync(uint112 reserve0, uint112 reserve1)
MINIMUM_LIQUIDITY
function MINIMUM_LIQUIDITY() external pure returns (uint256)
factory
function factory() external view returns (address)
token0
function token0() external view returns (address)
token1
function token1() external view returns (address)
getReserves
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)
price0CumulativeLast
function price0CumulativeLast() external view returns (uint256)
price1CumulativeLast
function price1CumulativeLast() external view returns (uint256)
kLast
function kLast() external view returns (uint256)
mint
function mint(address to) external returns (uint256 liquidity)
burn
function burn(address to) external returns (uint256 amount0, uint256 amount1)
swap
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes data) external
skim
function skim(address to) external
sync
function sync() external
initialize
function initialize(address, address) external
SafeMath
_Wrappers over Solidity's arithmetic operations.
NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler now has built in overflow checking._
tryAdd
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the addition of two unsigned integers, with an overflow flag.
Available since v3.4._
trySub
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the substraction of two unsigned integers, with an overflow flag.
Available since v3.4._
tryMul
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the multiplication of two unsigned integers, with an overflow flag.
Available since v3.4._
tryDiv
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the division of two unsigned integers, with a division by zero flag.
Available since v3.4._
tryMod
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256)
_Returns the remainder of dividing two unsigned integers, with a division by zero flag.
Available since v3.4._
add
function add(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the addition of two unsigned integers, reverting on overflow.
Counterpart to Solidity's `+` operator.
Requirements:
Addition cannot overflow._
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the subtraction of two unsigned integers, reverting on overflow (when the result is negative).
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the multiplication of two unsigned integers, reverting on overflow.
Counterpart to Solidity's `*` operator.
Requirements:
Multiplication cannot overflow._
div
function div(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the integer division of two unsigned integers, reverting on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator.
Requirements:
The divisor cannot be zero._
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256)
_Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting when dividing by zero.
Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
sub
function sub(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the subtraction of two unsigned integers, reverting with custom message on overflow (when the result is negative).
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {trySub}.
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
div
function div(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the integer division of two unsigned integers, reverting with custom message on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator. Note: this function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
mod
function mod(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
_Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), reverting with custom message when dividing by zero.
CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryMod}.
Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas).
Requirements:
The divisor cannot be zero._
UniswapV2Library
sortTokens
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1)
pairFor
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair)
getReserves
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint256 reserveA, uint256 reserveB)
quote
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB)
getAmountOut
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountOut)
getAmountIn
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountIn)
getAmountsOut
function getAmountsOut(address factory, uint256 amountIn, address[] path) internal view returns (uint256[] amounts)
getAmountsIn
function getAmountsIn(address factory, uint256 amountOut, address[] path) internal view returns (uint256[] amounts)
CarefulMath
Derived from OpenZeppelin's SafeMath library https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
MathError
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
mulUInt
function mulUInt(uint256 a, uint256 b) internal pure returns (enum CarefulMath.MathError, uint256)
Multiplies two numbers, returns an error on overflow.
divUInt
function divUInt(uint256 a, uint256 b) internal pure returns (enum CarefulMath.MathError, uint256)
Integer division of two numbers, truncating the quotient.
subUInt
function subUInt(uint256 a, uint256 b) internal pure returns (enum CarefulMath.MathError, uint256)
Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
addUInt
function addUInt(uint256 a, uint256 b) internal pure returns (enum CarefulMath.MathError, uint256)
Adds two numbers, returns an error on overflow.
addThenSubUInt
function addThenSubUInt(uint256 a, uint256 b, uint256 c) internal pure returns (enum CarefulMath.MathError, uint256)
add a and b and then subtract c
BondtrollerErrorReporter
Error
enum Error {
NO_ERROR,
UNAUTHORIZED,
BONDTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED,
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
FailureInfo
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
Failure
event Failure(uint256 error, uint256 info, uint256 detail)
`error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary contract-specific code that enables us to report opaque error codes from upgradeable contracts.
fail
function fail(enum BondtrollerErrorReporter.Error err, enum BondtrollerErrorReporter.FailureInfo info) internal returns (uint256)
use this when reporting a known error from the money market or a non-upgradeable collaborator
failOpaque
function failOpaque(enum BondtrollerErrorReporter.Error err, enum BondtrollerErrorReporter.FailureInfo info, uint256 opaqueError) internal returns (uint256)
use this when reporting an opaque error from an upgradeable collaborator contract
TokenErrorReporter
Error
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
FailureInfo
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
Failure
event Failure(uint256 error, uint256 info, uint256 detail)
`error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary contract-specific code that enables us to report opaque error codes from upgradeable contracts.
fail
function fail(enum TokenErrorReporter.Error err, enum TokenErrorReporter.FailureInfo info) internal returns (uint256)
use this when reporting a known error from the money market or a non-upgradeable collaborator
failOpaque
function failOpaque(enum TokenErrorReporter.Error err, enum TokenErrorReporter.FailureInfo info, uint256 opaqueError) internal returns (uint256)
use this when reporting an opaque error from an upgradeable collaborator contract
Exponential
Exp is a struct which stores decimals with a fixed precision of 18 decimal places. Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: `Exp({mantissa: 5100000000000000000})`.
Legacy contract for compatibility reasons with existing contracts that still use MathError
getExp
function getExp(uint256 num, uint256 denom) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Creates an exponential from numerator and denominator values. Note: Returns an error if (`num` * 10e18) > MAX_INT, or if `denom` is zero.
addExp
function addExp(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Adds two exponentials, returning a new exponential.
subExp
function subExp(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Subtracts two exponentials, returning a new exponential.
mulScalar
function mulScalar(struct ExponentialNoError.Exp a, uint256 scalar) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Multiply an Exp by a scalar, returning a new Exp.
mulScalarTruncate
function mulScalarTruncate(struct ExponentialNoError.Exp a, uint256 scalar) internal pure returns (enum CarefulMath.MathError, uint256)
Multiply an Exp by a scalar, then truncate to return an unsigned integer.
mulScalarTruncateAddUInt
function mulScalarTruncateAddUInt(struct ExponentialNoError.Exp a, uint256 scalar, uint256 addend) internal pure returns (enum CarefulMath.MathError, uint256)
Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
divScalar
function divScalar(struct ExponentialNoError.Exp a, uint256 scalar) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Divide an Exp by a scalar, returning a new Exp.
divScalarByExp
function divScalarByExp(uint256 scalar, struct ExponentialNoError.Exp divisor) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Divide a scalar by an Exp, returning a new Exp.
divScalarByExpTruncate
function divScalarByExpTruncate(uint256 scalar, struct ExponentialNoError.Exp divisor) internal pure returns (enum CarefulMath.MathError, uint256)
Divide a scalar by an Exp, then truncate to return an unsigned integer.
mulExp
function mulExp(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Multiplies two exponentials, returning a new exponential.
mulExp
function mulExp(uint256 a, uint256 b) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Multiplies two exponentials given their mantissas, returning a new exponential.
mulExp3
function mulExp3(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b, struct ExponentialNoError.Exp c) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Multiplies three exponentials, returning a new exponential.
divExp
function divExp(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (enum CarefulMath.MathError, struct ExponentialNoError.Exp)
Divides two exponentials, returning a new exponential. (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
ExponentialNoError
Exp is a struct which stores decimals with a fixed precision of 18 decimal places. Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: `Exp({mantissa: 5100000000000000000})`.
expScale
uint256 expScale
doubleScale
uint256 doubleScale
halfExpScale
uint256 halfExpScale
mantissaOne
uint256 mantissaOne
Exp
struct Exp {
uint256 mantissa;
}
Double
struct Double {
uint256 mantissa;
}
truncate
function truncate(struct ExponentialNoError.Exp exp) internal pure returns (uint256)
Truncates the given exp to a whole number value. For example, truncate(Exp{mantissa: 15 * expScale}) = 15
mul_ScalarTruncate
function mul_ScalarTruncate(struct ExponentialNoError.Exp a, uint256 scalar) internal pure returns (uint256)
Multiply an Exp by a scalar, then truncate to return an unsigned integer.
mul_ScalarTruncateAddUInt
function mul_ScalarTruncateAddUInt(struct ExponentialNoError.Exp a, uint256 scalar, uint256 addend) internal pure returns (uint256)
Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
lessThanExp
function lessThanExp(struct ExponentialNoError.Exp left, struct ExponentialNoError.Exp right) internal pure returns (bool)
Checks if first Exp is less than second Exp.
lessThanOrEqualExp
function lessThanOrEqualExp(struct ExponentialNoError.Exp left, struct ExponentialNoError.Exp right) internal pure returns (bool)
Checks if left Exp <= right Exp.
greaterThanExp
function greaterThanExp(struct ExponentialNoError.Exp left, struct ExponentialNoError.Exp right) internal pure returns (bool)
Checks if left Exp > right Exp.
isZeroExp
function isZeroExp(struct ExponentialNoError.Exp value) internal pure returns (bool)
returns true if Exp is exactly zero
safe224
function safe224(uint256 n, string errorMessage) internal pure returns (uint224)
safe32
function safe32(uint256 n, string errorMessage) internal pure returns (uint32)
add_
function add_(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (struct ExponentialNoError.Exp)
add_
function add_(struct ExponentialNoError.Double a, struct ExponentialNoError.Double b) internal pure returns (struct ExponentialNoError.Double)
add_
function add_(uint256 a, uint256 b) internal pure returns (uint256)
add_
function add_(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
sub_
function sub_(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (struct ExponentialNoError.Exp)
sub_
function sub_(struct ExponentialNoError.Double a, struct ExponentialNoError.Double b) internal pure returns (struct ExponentialNoError.Double)
sub_
function sub_(uint256 a, uint256 b) internal pure returns (uint256)
sub_
function sub_(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
mul_
function mul_(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (struct ExponentialNoError.Exp)
mul_
function mul_(struct ExponentialNoError.Exp a, uint256 b) internal pure returns (struct ExponentialNoError.Exp)
mul_
function mul_(uint256 a, struct ExponentialNoError.Exp b) internal pure returns (uint256)
mul_
function mul_(struct ExponentialNoError.Double a, struct ExponentialNoError.Double b) internal pure returns (struct ExponentialNoError.Double)
mul_
function mul_(struct ExponentialNoError.Double a, uint256 b) internal pure returns (struct ExponentialNoError.Double)
mul_
function mul_(uint256 a, struct ExponentialNoError.Double b) internal pure returns (uint256)
mul_
function mul_(uint256 a, uint256 b) internal pure returns (uint256)
mul_
function mul_(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
div_
function div_(struct ExponentialNoError.Exp a, struct ExponentialNoError.Exp b) internal pure returns (struct ExponentialNoError.Exp)
div_
function div_(struct ExponentialNoError.Exp a, uint256 b) internal pure returns (struct ExponentialNoError.Exp)
div_
function div_(uint256 a, struct ExponentialNoError.Exp b) internal pure returns (uint256)
div_
function div_(struct ExponentialNoError.Double a, struct ExponentialNoError.Double b) internal pure returns (struct ExponentialNoError.Double)
div_
function div_(struct ExponentialNoError.Double a, uint256 b) internal pure returns (struct ExponentialNoError.Double)
div_
function div_(uint256 a, struct ExponentialNoError.Double b) internal pure returns (uint256)
div_
function div_(uint256 a, uint256 b) internal pure returns (uint256)
div_
function div_(uint256 a, uint256 b, string errorMessage) internal pure returns (uint256)
fraction
function fraction(uint256 a, uint256 b) internal pure returns (struct ExponentialNoError.Double)
console
CONSOLE_ADDRESS
address CONSOLE_ADDRESS
_sendLogPayload
function _sendLogPayload(bytes payload) private view
log
function log() internal view
logInt
function logInt(int256 p0) internal view
logUint
function logUint(uint256 p0) internal view
logString
function logString(string p0) internal view
logBool
function logBool(bool p0) internal view
logAddress
function logAddress(address p0) internal view
logBytes
function logBytes(bytes p0) internal view
logBytes1
function logBytes1(bytes1 p0) internal view
logBytes2
function logBytes2(bytes2 p0) internal view
logBytes3
function logBytes3(bytes3 p0) internal view
logBytes4
function logBytes4(bytes4 p0) internal view
logBytes5
function logBytes5(bytes5 p0) internal view
logBytes6
function logBytes6(bytes6 p0) internal view
logBytes7
function logBytes7(bytes7 p0) internal view
logBytes8
function logBytes8(bytes8 p0) internal view
logBytes9
function logBytes9(bytes9 p0) internal view
logBytes10
function logBytes10(bytes10 p0) internal view
logBytes11
function logBytes11(bytes11 p0) internal view
logBytes12
function logBytes12(bytes12 p0) internal view
logBytes13
function logBytes13(bytes13 p0) internal view
logBytes14
function logBytes14(bytes14 p0) internal view
logBytes15
function logBytes15(bytes15 p0) internal view
logBytes16
function logBytes16(bytes16 p0) internal view
logBytes17
function logBytes17(bytes17 p0) internal view
logBytes18
function logBytes18(bytes18 p0) internal view
logBytes19
function logBytes19(bytes19 p0) internal view
logBytes20
function logBytes20(bytes20 p0) internal view
logBytes21
function logBytes21(bytes21 p0) internal view
logBytes22
function logBytes22(bytes22 p0) internal view
logBytes23
function logBytes23(bytes23 p0) internal view
logBytes24
function logBytes24(bytes24 p0) internal view
logBytes25
function logBytes25(bytes25 p0) internal view
logBytes26
function logBytes26(bytes26 p0) internal view
logBytes27
function logBytes27(bytes27 p0) internal view
logBytes28
function logBytes28(bytes28 p0) internal view
logBytes29
function logBytes29(bytes29 p0) internal view
logBytes30
function logBytes30(bytes30 p0) internal view
logBytes31
function logBytes31(bytes31 p0) internal view
logBytes32
function logBytes32(bytes32 p0) internal view
log
function log(uint256 p0) internal view
log
function log(string p0) internal view
log
function log(bool p0) internal view
log
function log(address p0) internal view
log
function log(uint256 p0, uint256 p1) internal view
log
function log(uint256 p0, string p1) internal view
log
function log(uint256 p0, bool p1) internal view
log
function log(uint256 p0, address p1) internal view
log
function log(string p0, uint256 p1) internal view
log
function log(string p0, string p1) internal view
log
function log(string p0, bool p1) internal view
log
function log(string p0, address p1) internal view
log
function log(bool p0, uint256 p1) internal view
log
function log(bool p0, string p1) internal view
log
function log(bool p0, bool p1) internal view
log
function log(bool p0, address p1) internal view
log
function log(address p0, uint256 p1) internal view
log
function log(address p0, string p1) internal view
log
function log(address p0, bool p1) internal view
log
function log(address p0, address p1) internal view
log
function log(uint256 p0, uint256 p1, uint256 p2) internal view
log
function log(uint256 p0, uint256 p1, string p2) internal view
log
function log(uint256 p0, uint256 p1, bool p2) internal view
log
function log(uint256 p0, uint256 p1, address p2) internal view
log
function log(uint256 p0, string p1, uint256 p2) internal view
log
function log(uint256 p0, string p1, string p2) internal view
log
function log(uint256 p0, string p1, bool p2) internal view
log
function log(uint256 p0, string p1, address p2) internal view
log
function log(uint256 p0, bool p1, uint256 p2) internal view
log
function log(uint256 p0, bool p1, string p2) internal view
log
function log(uint256 p0, bool p1, bool p2) internal view
log
function log(uint256 p0, bool p1, address p2) internal view
log
function log(uint256 p0, address p1, uint256 p2) internal view
log
function log(uint256 p0, address p1, string p2) internal view
log
function log(uint256 p0, address p1, bool p2) internal view
log
function log(uint256 p0, address p1, address p2) internal view
log
function log(string p0, uint256 p1, uint256 p2) internal view
log
function log(string p0, uint256 p1, string p2) internal view
log
function log(string p0, uint256 p1, bool p2) internal view
log
function log(string p0, uint256 p1, address p2) internal view
log
function log(string p0, string p1, uint256 p2) internal view
log
function log(string p0, string p1, string p2) internal view
log
function log(string p0, string p1, bool p2) internal view
log
function log(string p0, string p1, address p2) internal view
log
function log(string p0, bool p1, uint256 p2) internal view
log
function log(string p0, bool p1, string p2) internal view
log
function log(string p0, bool p1, bool p2) internal view
log
function log(string p0, bool p1, address p2) internal view
log
function log(string p0, address p1, uint256 p2) internal view
log
function log(string p0, address p1, string p2) internal view
log
function log(string p0, address p1, bool p2) internal view
log
function log(string p0, address p1, address p2) internal view
log
function log(bool p0, uint256 p1, uint256 p2) internal view
log
function log(bool p0, uint256 p1, string p2) internal view
log
function log(bool p0, uint256 p1, bool p2) internal view
log
function log(bool p0, uint256 p1, address p2) internal view
log
function log(bool p0, string p1, uint256 p2) internal view
log
function log(bool p0, string p1, string p2) internal view
log
function log(bool p0, string p1, bool p2) internal view
log
function log(bool p0, string p1, address p2) internal view
log
function log(bool p0, bool p1, uint256 p2) internal view
log
function log(bool p0, bool p1, string p2) internal view
log
function log(bool p0, bool p1, bool p2) internal view
log
function log(bool p0, bool p1, address p2) internal view
log
function log(bool p0, address p1, uint256 p2) internal view
log
function log(bool p0, address p1, string p2) internal view
log
function log(bool p0, address p1, bool p2) internal view
log
function log(bool p0, address p1, address p2) internal view
log
function log(address p0, uint256 p1, uint256 p2) internal view
log
function log(address p0, uint256 p1, string p2) internal view
log
function log(address p0, uint256 p1, bool p2) internal view
log
function log(address p0, uint256 p1, address p2) internal view
log
function log(address p0, string p1, uint256 p2) internal view
log
function log(address p0, string p1, string p2) internal view
log
function log(address p0, string p1, bool p2) internal view
log
function log(address p0, string p1, address p2) internal view
log
function log(address p0, bool p1, uint256 p2) internal view
log
function log(address p0, bool p1, string p2) internal view
log
function log(address p0, bool p1, bool p2) internal view
log
function log(address p0, bool p1, address p2) internal view
log
function log(address p0, address p1, uint256 p2) internal view
log
function log(address p0, address p1, string p2) internal view
log
function log(address p0, address p1, bool p2) internal view
log
function log(address p0, address p1, address p2) internal view
log
function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal view
log
function log(uint256 p0, uint256 p1, uint256 p2, string p3) internal view
log
function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal view
log
function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal view
log
function log(uint256 p0, uint256 p1, string p2, uint256 p3) internal view
log
function log(uint256 p0, uint256 p1, string p2, string p3) internal view
log
function log(uint256 p0, uint256 p1, string p2, bool p3) internal view
log
function log(uint256 p0, uint256 p1, string p2, address p3) internal view
log
function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal view
log
function log(uint256 p0, uint256 p1, bool p2, string p3) internal view
log
function log(uint256 p0, uint256 p1, bool p2, bool p3) internal view
log
function log(uint256 p0, uint256 p1, bool p2, address p3) internal view
log
function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal view
log
function log(uint256 p0, uint256 p1, address p2, string p3) internal view
log
function log(uint256 p0, uint256 p1, address p2, bool p3) internal view
log
function log(uint256 p0, uint256 p1, address p2, address p3) internal view
log
function log(uint256 p0, string p1, uint256 p2, uint256 p3) internal view
log
function log(uint256 p0, string p1, uint256 p2, string p3) internal view
log
function log(uint256 p0, string p1, uint256 p2, bool p3) internal view
log
function log(uint256 p0, string p1, uint256 p2, address p3) internal view
log
function log(uint256 p0, string p1, string p2, uint256 p3) internal view
log
function log(uint256 p0, string p1, string p2, string p3) internal view
log
function log(uint256 p0, string p1, string p2, bool p3) internal view
log
function log(uint256 p0, string p1, string p2, address p3) internal view
log
function log(uint256 p0, string p1, bool p2, uint256 p3) internal view
log
function log(uint256 p0, string p1, bool p2, string p3) internal view
log
function log(uint256 p0, string p1, bool p2, bool p3) internal view
log
function log(uint256 p0, string p1, bool p2, address p3) internal view
log
function log(uint256 p0, string p1, address p2, uint256 p3) internal view
log
function log(uint256 p0, string p1, address p2, string p3) internal view
log
function log(uint256 p0, string p1, address p2, bool p3) internal view
log
function log(uint256 p0, string p1, address p2, address p3) internal view
log
function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal view
log
function log(uint256 p0, bool p1, uint256 p2, string p3) internal view
log
function log(uint256 p0, bool p1, uint256 p2, bool p3) internal view
log
function log(uint256 p0, bool p1, uint256 p2, address p3) internal view
log
function log(uint256 p0, bool p1, string p2, uint256 p3) internal view
log
function log(uint256 p0, bool p1, string p2, string p3) internal view
log
function log(uint256 p0, bool p1, string p2, bool p3) internal view
log
function log(uint256 p0, bool p1, string p2, address p3) internal view
log
function log(uint256 p0, bool p1, bool p2, uint256 p3) internal view
log
function log(uint256 p0, bool p1, bool p2, string p3) internal view
log
function log(uint256 p0, bool p1, bool p2, bool p3) internal view
log
function log(uint256 p0, bool p1, bool p2, address p3) internal view
log
function log(uint256 p0, bool p1, address p2, uint256 p3) internal view
log
function log(uint256 p0, bool p1, address p2, string p3) internal view
log
function log(uint256 p0, bool p1, address p2, bool p3) internal view
log
function log(uint256 p0, bool p1, address p2, address p3) internal view
log
function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal view
log
function log(uint256 p0, address p1, uint256 p2, string p3) internal view
log
function log(uint256 p0, address p1, uint256 p2, bool p3) internal view
log
function log(uint256 p0, address p1, uint256 p2, address p3) internal view
log
function log(uint256 p0, address p1, string p2, uint256 p3) internal view
log
function log(uint256 p0, address p1, string p2, string p3) internal view
log
function log(uint256 p0, address p1, string p2, bool p3) internal view
log
function log(uint256 p0, address p1, string p2, address p3) internal view
log
function log(uint256 p0, address p1, bool p2, uint256 p3) internal view
log
function log(uint256 p0, address p1, bool p2, string p3) internal view
log
function log(uint256 p0, address p1, bool p2, bool p3) internal view
log
function log(uint256 p0, address p1, bool p2, address p3) internal view
log
function log(uint256 p0, address p1, address p2, uint256 p3) internal view
log
function log(uint256 p0, address p1, address p2, string p3) internal view
log
function log(uint256 p0, address p1, address p2, bool p3) internal view
log
function log(uint256 p0, address p1, address p2, address p3) internal view
log
function log(string p0, uint256 p1, uint256 p2, uint256 p3) internal view
log
function log(string p0, uint256 p1, uint256 p2, string p3) internal view
log
function log(string p0, uint256 p1, uint256 p2, bool p3) internal view
log
function log(string p0, uint256 p1, uint256 p2, address p3) internal view
log
function log(string p0, uint256 p1, string p2, uint256 p3) internal view
log
function log(string p0, uint256 p1, string p2, string p3) internal view
log
function log(string p0, uint256 p1, string p2, bool p3) internal view
log
function log(string p0, uint256 p1, string p2, address p3) internal view
log
function log(string p0, uint256 p1, bool p2, uint256 p3) internal view
log
function log(string p0, uint256 p1, bool p2, string p3) internal view
log
function log(string p0, uint256 p1, bool p2, bool p3) internal view
log
function log(string p0, uint256 p1, bool p2, address p3) internal view
log
function log(string p0, uint256 p1, address p2, uint256 p3) internal view
log
function log(string p0, uint256 p1, address p2, string p3) internal view
log
function log(string p0, uint256 p1, address p2, bool p3) internal view
log
function log(string p0, uint256 p1, address p2, address p3) internal view
log
function log(string p0, string p1, uint256 p2, uint256 p3) internal view
log
function log(string p0, string p1, uint256 p2, string p3) internal view
log
function log(string p0, string p1, uint256 p2, bool p3) internal view
log
function log(string p0, string p1, uint256 p2, address p3) internal view
log
function log(string p0, string p1, string p2, uint256 p3) internal view
log
function log(string p0, string p1, string p2, string p3) internal view
log
function log(string p0, string p1, string p2, bool p3) internal view
log
function log(string p0, string p1, string p2, address p3) internal view
log
function log(string p0, string p1, bool p2, uint256 p3) internal view
log
function log(string p0, string p1, bool p2, string p3) internal view
log
function log(string p0, string p1, bool p2, bool p3) internal view
log
function log(string p0, string p1, bool p2, address p3) internal view
log
function log(string p0, string p1, address p2, uint256 p3) internal view
log
function log(string p0, string p1, address p2, string p3) internal view
log
function log(string p0, string p1, address p2, bool p3) internal view
log
function log(string p0, string p1, address p2, address p3) internal view
log
function log(string p0, bool p1, uint256 p2, uint256 p3) internal view
log
function log(string p0, bool p1, uint256 p2, string p3) internal view
log
function log(string p0, bool p1, uint256 p2, bool p3) internal view
log
function log(string p0, bool p1, uint256 p2, address p3) internal view
log
function log(string p0, bool p1, string p2, uint256 p3) internal view
log
function log(string p0, bool p1, string p2, string p3) internal view
log
function log(string p0, bool p1, string p2, bool p3) internal view
log
function log(string p0, bool p1, string p2, address p3) internal view
log
function log(string p0, bool p1, bool p2, uint256 p3) internal view
log
function log(string p0, bool p1, bool p2, string p3) internal view
log
function log(string p0, bool p1, bool p2, bool p3) internal view
log
function log(string p0, bool p1, bool p2, address p3) internal view
log
function log(string p0, bool p1, address p2, uint256 p3) internal view
log
function log(string p0, bool p1, address p2, string p3) internal view
log
function log(string p0, bool p1, address p2, bool p3) internal view
log
function log(string p0, bool p1, address p2, address p3) internal view
log
function log(string p0, address p1, uint256 p2, uint256 p3) internal view
log
function log(string p0, address p1, uint256 p2, string p3) internal view
log
function log(string p0, address p1, uint256 p2, bool p3) internal view
log
function log(string p0, address p1, uint256 p2, address p3) internal view
log
function log(string p0, address p1, string p2, uint256 p3) internal view
log
function log(string p0, address p1, string p2, string p3) internal view
log
function log(string p0, address p1, string p2, bool p3) internal view
log
function log(string p0, address p1, string p2, address p3) internal view
log
function log(string p0, address p1, bool p2, uint256 p3) internal view
log
function log(string p0, address p1, bool p2, string p3) internal view
log
function log(string p0, address p1, bool p2, bool p3) internal view
log
function log(string p0, address p1, bool p2, address p3) internal view
log
function log(string p0, address p1, address p2, uint256 p3) internal view
log
function log(string p0, address p1, address p2, string p3) internal view
log
function log(string p0, address p1, address p2, bool p3) internal view
log
function log(string p0, address p1, address p2, address p3) internal view
log
function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal view
log
function log(bool p0, uint256 p1, uint256 p2, string p3) internal view
log
function log(bool p0, uint256 p1, uint256 p2, bool p3) internal view
log
function log(bool p0, uint256 p1, uint256 p2, address p3) internal view
log
function log(bool p0, uint256 p1, string p2, uint256 p3) internal view
log
function log(bool p0, uint256 p1, string p2, string p3) internal view
log
function log(bool p0, uint256 p1, string p2, bool p3) internal view
log
function log(bool p0, uint256 p1, string p2, address p3) internal view
log
function log(bool p0, uint256 p1, bool p2, uint256 p3) internal view
log
function log(bool p0, uint256 p1, bool p2, string p3) internal view
log
function log(bool p0, uint256 p1, bool p2, bool p3) internal view
log
function log(bool p0, uint256 p1, bool p2, address p3) internal view
log
function log(bool p0, uint256 p1, address p2, uint256 p3) internal view
log
function log(bool p0, uint256 p1, address p2, string p3) internal view
log
function log(bool p0, uint256 p1, address p2, bool p3) internal view
log
function log(bool p0, uint256 p1, address p2, address p3) internal view
log
function log(bool p0, string p1, uint256 p2, uint256 p3) internal view
log
function log(bool p0, string p1, uint256 p2, string p3) internal view
log
function log(bool p0, string p1, uint256 p2, bool p3) internal view
log
function log(bool p0, string p1, uint256 p2, address p3) internal view
log
function log(bool p0, string p1, string p2, uint256 p3) internal view
log
function log(bool p0, string p1, string p2, string p3) internal view
log
function log(bool p0, string p1, string p2, bool p3) internal view
log
function log(bool p0, string p1, string p2, address p3) internal view
log
function log(bool p0, string p1, bool p2, uint256 p3) internal view
log
function log(bool p0, string p1, bool p2, string p3) internal view
log
function log(bool p0, string p1, bool p2, bool p3) internal view
log
function log(bool p0, string p1, bool p2, address p3) internal view
log
function log(bool p0, string p1, address p2, uint256 p3) internal view
log
function log(bool p0, string p1, address p2, string p3) internal view
log
function log(bool p0, string p1, address p2, bool p3) internal view
log
function log(bool p0, string p1, address p2, address p3) internal view
log
function log(bool p0, bool p1, uint256 p2, uint256 p3) internal view
log
function log(bool p0, bool p1, uint256 p2, string p3) internal view
log
function log(bool p0, bool p1, uint256 p2, bool p3) internal view
log
function log(bool p0, bool p1, uint256 p2, address p3) internal view
log
function log(bool p0, bool p1, string p2, uint256 p3) internal view
log
function log(bool p0, bool p1, string p2, string p3) internal view
log
function log(bool p0, bool p1, string p2, bool p3) internal view
log
function log(bool p0, bool p1, string p2, address p3) internal view
log
function log(bool p0, bool p1, bool p2, uint256 p3) internal view
log
function log(bool p0, bool p1, bool p2, string p3) internal view
log
function log(bool p0, bool p1, bool p2, bool p3) internal view
log
function log(bool p0, bool p1, bool p2, address p3) internal view
log
function log(bool p0, bool p1, address p2, uint256 p3) internal view
log
function log(bool p0, bool p1, address p2, string p3) internal view
log
function log(bool p0, bool p1, address p2, bool p3) internal view
log
function log(bool p0, bool p1, address p2, address p3) internal view
log
function log(bool p0, address p1, uint256 p2, uint256 p3) internal view
log
function log(bool p0, address p1, uint256 p2, string p3) internal view
log
function log(bool p0, address p1, uint256 p2, bool p3) internal view
log
function log(bool p0, address p1, uint256 p2, address p3) internal view
log
function log(bool p0, address p1, string p2, uint256 p3) internal view
log
function log(bool p0, address p1, string p2, string p3) internal view
log
function log(bool p0, address p1, string p2, bool p3) internal view
log
function log(bool p0, address p1, string p2, address p3) internal view
log
function log(bool p0, address p1, bool p2, uint256 p3) internal view
log
function log(bool p0, address p1, bool p2, string p3) internal view
log
function log(bool p0, address p1, bool p2, bool p3) internal view
log
function log(bool p0, address p1, bool p2, address p3) internal view
log
function log(bool p0, address p1, address p2, uint256 p3) internal view
log
function log(bool p0, address p1, address p2, string p3) internal view
log
function log(bool p0, address p1, address p2, bool p3) internal view
log
function log(bool p0, address p1, address p2, address p3) internal view
log
function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal view
log
function log(address p0, uint256 p1, uint256 p2, string p3) internal view
log
function log(address p0, uint256 p1, uint256 p2, bool p3) internal view
log
function log(address p0, uint256 p1, uint256 p2, address p3) internal view
log
function log(address p0, uint256 p1, string p2, uint256 p3) internal view
log
function log(address p0, uint256 p1, string p2, string p3) internal view
log
function log(address p0, uint256 p1, string p2, bool p3) internal view
log
function log(address p0, uint256 p1, string p2, address p3) internal view
log
function log(address p0, uint256 p1, bool p2, uint256 p3) internal view
log
function log(address p0, uint256 p1, bool p2, string p3) internal view
log
function log(address p0, uint256 p1, bool p2, bool p3) internal view
log
function log(address p0, uint256 p1, bool p2, address p3) internal view
log
function log(address p0, uint256 p1, address p2, uint256 p3) internal view
log
function log(address p0, uint256 p1, address p2, string p3) internal view
log
function log(address p0, uint256 p1, address p2, bool p3) internal view
log
function log(address p0, uint256 p1, address p2, address p3) internal view
log
function log(address p0, string p1, uint256 p2, uint256 p3) internal view
log
function log(address p0, string p1, uint256 p2, string p3) internal view
log
function log(address p0, string p1, uint256 p2, bool p3) internal view
log
function log(address p0, string p1, uint256 p2, address p3) internal view
log
function log(address p0, string p1, string p2, uint256 p3) internal view
log
function log(address p0, string p1, string p2, string p3) internal view
log
function log(address p0, string p1, string p2, bool p3) internal view
log
function log(address p0, string p1, string p2, address p3) internal view
log
function log(address p0, string p1, bool p2, uint256 p3) internal view
log
function log(address p0, string p1, bool p2, string p3) internal view
log
function log(address p0, string p1, bool p2, bool p3) internal view
log
function log(address p0, string p1, bool p2, address p3) internal view
log
function log(address p0, string p1, address p2, uint256 p3) internal view
log
function log(address p0, string p1, address p2, string p3) internal view
log
function log(address p0, string p1, address p2, bool p3) internal view
log
function log(address p0, string p1, address p2, address p3) internal view
log
function log(address p0, bool p1, uint256 p2, uint256 p3) internal view
log
function log(address p0, bool p1, uint256 p2, string p3) internal view
log
function log(address p0, bool p1, uint256 p2, bool p3) internal view
log
function log(address p0, bool p1, uint256 p2, address p3) internal view
log
function log(address p0, bool p1, string p2, uint256 p3) internal view
log
function log(address p0, bool p1, string p2, string p3) internal view
log
function log(address p0, bool p1, string p2, bool p3) internal view
log
function log(address p0, bool p1, string p2, address p3) internal view
log
function log(address p0, bool p1, bool p2, uint256 p3) internal view
log
function log(address p0, bool p1, bool p2, string p3) internal view
log
function log(address p0, bool p1, bool p2, bool p3) internal view
log
function log(address p0, bool p1, bool p2, address p3) internal view
log
function log(address p0, bool p1, address p2, uint256 p3) internal view
log
function log(address p0, bool p1, address p2, string p3) internal view
log
function log(address p0, bool p1, address p2, bool p3) internal view
log
function log(address p0, bool p1, address p2, address p3) internal view
log
function log(address p0, address p1, uint256 p2, uint256 p3) internal view
log
function log(address p0, address p1, uint256 p2, string p3) internal view
log
function log(address p0, address p1, uint256 p2, bool p3) internal view
log
function log(address p0, address p1, uint256 p2, address p3) internal view
log
function log(address p0, address p1, string p2, uint256 p3) internal view
log
function log(address p0, address p1, string p2, string p3) internal view
log
function log(address p0, address p1, string p2, bool p3) internal view
log
function log(address p0, address p1, string p2, address p3) internal view
log
function log(address p0, address p1, bool p2, uint256 p3) internal view
log
function log(address p0, address p1, bool p2, string p3) internal view
log
function log(address p0, address p1, bool p2, bool p3) internal view
log
function log(address p0, address p1, bool p2, address p3) internal view
log
function log(address p0, address p1, address p2, uint256 p3) internal view
log
function log(address p0, address p1, address p2, string p3) internal view
log
function log(address p0, address p1, address p2, bool p3) internal view
log
function log(address p0, address p1, address p2, address p3) internal view
IPRJ
name
function name() external view returns (string)
Returns the name of the token.
symbol
function symbol() external view returns (string)
Returns the symbol of the token, usually a shorter version of the name.
decimals
function decimals() external view returns (uint8)
_Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`).
Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless this function is overridden;
NOTE: This information is only used for display purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}._
totalSupply
function totalSupply() external view returns (uint256)
Returns the amount of tokens in existence.
balanceOf
function balanceOf(address account) external view returns (uint256)
Returns the amount of tokens owned by `account`.
transfer
function transfer(address recipient, uint256 amount) external returns (bool)
_Moves `amount` tokens from the caller's account to `recipient`.
Returns a boolean value indicating whether the operation succeeded.
Emits a {Transfer} event._
allowance
function allowance(address owner, address spender) external view returns (uint256)
_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._
approve
function approve(address spender, uint256 amount) external returns (bool)
_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._
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)
_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._
mint
function mint(uint256 amount) external
mints Project tokens to msg.sender
amount
uint256
- the amount of project tokens to mint
mintTo
function mintTo(address to, uint256 amount) external
mints Project tokens to `to`
to
address
- address of user that receive the Project Token
amount
uint256
- the amount of project tokens to mint
IUSDCTest
name
function name() external view returns (string)
Returns the name of the token.
symbol
function symbol() external view returns (string)
Returns the symbol of the token, usually a shorter version of the name.
decimals
function decimals() external view returns (uint8)
_Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`).
Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless this function is overridden;
NOTE: This information is only used for display purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}._
totalSupply
function totalSupply() external view returns (uint256)
Returns the amount of tokens in existence.
balanceOf
function balanceOf(address account) external view returns (uint256)
Returns the amount of tokens owned by `account`.
transfer
function transfer(address recipient, uint256 amount) external returns (bool)
_Moves `amount` tokens from the caller's account to `recipient`.
Returns a boolean value indicating whether the operation succeeded.
Emits a {Transfer} event._
allowance
function allowance(address owner, address spender) external view returns (uint256)
_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._
approve
function approve(address spender, uint256 amount) external returns (bool)
_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._
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)
_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._
mint
function mint(uint256 amount) external
mints Project tokens to msg.sender
amount
uint256
- the amount of project tokens to mint
mintTo
function mintTo(address to, uint256 amount) external
mints Project tokens to `to`
to
address
- address of user that receive the Project Token
amount
uint256
- the amount of project tokens to mint
SignedSafeMathUpgradeable
_Wrappers over Solidity's arithmetic operations.
NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler now has built in overflow checking._
mul
function mul(int256 a, int256 b) internal pure returns (int256)
_Returns the multiplication of two signed integers, reverting on overflow.
Counterpart to Solidity's `*` operator.
Requirements:
Multiplication cannot overflow._
div
function div(int256 a, int256 b) internal pure returns (int256)
_Returns the integer division of two signed integers. Reverts on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator.
Requirements:
The divisor cannot be zero._
sub
function sub(int256 a, int256 b) internal pure returns (int256)
_Returns the subtraction of two signed integers, reverting on overflow.
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
add
function add(int256 a, int256 b) internal pure returns (int256)
_Returns the addition of two signed integers, reverting on overflow.
Counterpart to Solidity's `+` operator.
Requirements:
Addition cannot overflow._
IBLendingToken
mintTo
function mintTo(address minter, uint256 mintAmount) external returns (uint256 err, uint256 mintedAmount)
Sender supplies assets into the market and receives cTokens in exchange
Accrues interest whether or not the operation succeeds, unless reverted
minter
address
the address of account which earn liquidity
mintAmount
uint256
The amount of the underlying asset to supply to minter return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) return uint minted amount
redeemTo
function redeemTo(address redeemer, uint256 redeemTokens) external returns (uint256)
Sender redeems cTokens in exchange for the underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemer
address
redeemTokens
uint256
The number of cTokens to redeem into underlying
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
redeemUnderlyingTo
function redeemUnderlyingTo(address redeemer, uint256 redeemAmount) external returns (uint256)
Sender redeems cTokens in exchange for a specified amount of underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemer
address
redeemAmount
uint256
The amount of underlying to redeem
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
borrowTo
function borrowTo(address projectToken, address borrower, uint256 borrowAmount) external returns (uint256 borrowError)
repayBorrowTo
function repayBorrowTo(address projectToken, address payer, uint256 repayAmount) external returns (uint256 repayBorrowError, uint256 amountRepayed)
repayBorrowToBorrower
function repayBorrowToBorrower(address projectToken, address payer, address borrower, uint256 repayAmount) external returns (uint256 repayBorrowError, uint256 amountRepayed)
balanceOf
function balanceOf(address owner) external view returns (uint256)
Get the token balance of the `owner`
owner
address
The address of the account to query
[0]
uint256
The number of tokens owned by `owner`
borrowBalanceCurrent
function borrowBalanceCurrent(address account) external returns (uint256)
borrowBalanceStored
function borrowBalanceStored(address account) external view returns (uint256)
totalSupply
function totalSupply() external view returns (uint256)
totalBorrows
function totalBorrows() external view returns (uint256)
exchangeRateStored
function exchangeRateStored() external view returns (uint256)
IPrimaryIndexToken
MODERATOR_ROLE
function MODERATOR_ROLE() external view returns (bytes32)
return keccak("MODERATOR_ROLE")
priceOracle
function priceOracle() external view returns (address)
return address of price oracle with interface of PriceProviderAggregator
projectTokens
function projectTokens(uint256 projectTokenId) external view returns (address)
return address project token in array `projectTokens`
projectTokenId
uint256
- index of project token in array `projectTokens`. Numetates from 0 to array length - 1
projectTokenInfo
function projectTokenInfo(address projectToken) external view returns (struct IPrimaryIndexToken.ProjectTokenInfo)
return info of project token, that declared in struct ProjectTokenInfo
projectToken
address
- address of project token in array `projectTokens`. Numetates from 0 to array length - 1
lendingTokens
function lendingTokens(uint256 lendingTokenId) external view returns (address)
return address lending token in array `lendingTokens`
lendingTokenId
uint256
- index of lending token in array `lendingTokens`. Numetates from 0 to array length - 1
lendingTokenInfo
function lendingTokenInfo(address lendingToken) external view returns (struct IPrimaryIndexToken.LendingTokenInfo)
return info of lending token, that declared in struct LendingTokenInfo
lendingToken
address
- address of project token in array `projectTokens`. Numetates from 0 to array length - 1
totalDepositedProjectToken
function totalDepositedProjectToken(address projectToken) external view returns (uint256)
depositPosition
function depositPosition(address account, address projectToken, address lendingToken) external view returns (struct IPrimaryIndexToken.DepositPosition)
borrowPosition
function borrowPosition(address account, address projectToken, address lendingToken) external view returns (struct IPrimaryIndexToken.BorrowPosition)
totalBorrow
function totalBorrow(address projectToken, address lendingToken) external view returns (uint256)
borrowLimit
function borrowLimit(address projectToken, address lendingToken) external view returns (uint256)
Ratio
struct Ratio {
uint8 numerator;
uint8 denominator;
}
ProjectTokenInfo
struct ProjectTokenInfo {
bool isListed;
bool isDepositPaused;
bool isWithdrawPaused;
struct IPrimaryIndexToken.Ratio loanToValueRatio;
struct IPrimaryIndexToken.Ratio liquidationThresholdFactor;
struct IPrimaryIndexToken.Ratio liquidationIncentive;
}
LendingTokenInfo
struct LendingTokenInfo {
bool isListed;
bool isPaused;
address bLendingToken;
}
DepositPosition
struct DepositPosition {
uint256 depositedProjectTokenAmount;
}
BorrowPosition
struct BorrowPosition {
uint256 loanBody;
uint256 accrual;
}
AddPrjToken
event AddPrjToken(address tokenPrj)
LoanToValueRatioSet
event LoanToValueRatioSet(address tokenPrj, uint8 lvrNumerator, uint8 lvrDenominator)
LiquidationThresholdFactorSet
event LiquidationThresholdFactorSet(address tokenPrj, uint8 ltfNumerator, uint8 ltfDenominator)
Deposit
event Deposit(address who, address tokenPrj, uint256 prjDepositAmount, address beneficiar)
Withdraw
event Withdraw(address who, address tokenPrj, uint256 prjWithdrawAmount, address beneficiar)
Supply
event Supply(address who, address supplyToken, uint256 supplyAmount, address supplyBToken, uint256 amountSupplyBTokenReceived)
Redeem
event Redeem(address who, address redeemToken, address redeemBToken, uint256 redeemAmount)
RedeemUnderlying
event RedeemUnderlying(address who, address redeemToken, address redeemBToken, uint256 redeemAmountUnderlying)
Borrow
event Borrow(address who, address borrowToken, uint256 borrowAmount, address prjAddress, uint256 prjAmount)
RepayBorrow
event RepayBorrow(address who, address borrowToken, uint256 borrowAmount, address prjAddress, bool isPositionFullyRepaid)
Liquidate
event Liquidate(address liquidator, address borrower, address lendingToken, address prjAddress, uint256 amountPrjLiquidated)
initialize
function initialize() external
addProjectToken
function addProjectToken(address _projectToken, uint8 _loanToValueRatioNumerator, uint8 _loanToValueRatioDenominator, uint8 _liquidationTresholdFactorNumerator, uint8 _liquidationTresholdFactorDenominator, uint8 _liquidationIncentiveNumerator, uint8 _liquidationIncentiveDenominator) external
removeProjectToken
function removeProjectToken(uint256 _projectTokenId) external
addLendingToken
function addLendingToken(address _lendingToken, address _bLendingToken, bool _isPaused) external
removeLendingToken
function removeLendingToken(uint256 _lendingTokenId) external
setPriceOracle
function setPriceOracle(address _priceOracle) external
grandModerator
function grandModerator(address newModerator) external
revokeModerator
function revokeModerator(address moderator) external
setBorrowLimit
function setBorrowLimit(address projectToken, address lendingToken, uint256 _borrowLimit) external
setProjectTokenInfo
function setProjectTokenInfo(address _projectToken, uint8 _loanToValueRatioNumerator, uint8 _loanToValueRatioDenominator, uint8 _liquidationTresholdFactorNumerator, uint8 _liquidationTresholdFactorDenominator, uint8 _liquidationIncentiveNumerator, uint8 _liquidationIncentiveDenominator) external
setPausedProjectToken
function setPausedProjectToken(address _projectToken, bool _isDepositPaused, bool _isWithdrawPaused) external
setLendingTokenInfo
function setLendingTokenInfo(address _lendingToken, address _bLendingToken, bool _isPaused) external
setPausedLendingToken
function setPausedLendingToken(address _lendingToken, bool _isPaused) external
deposit
function deposit(address projectToken, address lendingToken, uint256 projectTokenAmount) external
withdraw
function withdraw(address projectToken, address lendingToken, uint256 projectTokenAmount) external
supply
function supply(address lendingToken, uint256 lendingTokenAmount) external
redeem
function redeem(address lendingToken, uint256 bLendingTokenAmount) external
redeemUnderlying
function redeemUnderlying(address lendingToken, uint256 lendingTokenAmount) external
borrow
function borrow(address projectToken, address lendingToken, uint256 lendingTokenAmount) external
repay
function repay(address projectToken, address lendingToken, uint256 lendingTokenAmount) external
liquidate
function liquidate(address account, address projectToken, address lendingToken) external
updateInterestInBorrowPosition
function updateInterestInBorrowPosition(address account, address projectToken, address lendingToken) external
pit
function pit(address account, address projectToken, address lendingToken) external view returns (uint256)
pitRemaining
function pitRemaining(address account, address projectToken, address lendingToken) external view returns (uint256)
liquidationThreshold
function liquidationThreshold(address account, address projectToken, address lendingToken) external view returns (uint256)
totalOutstanding
function totalOutstanding(address account, address projectToken, address lendingToken) external view returns (uint256)
healthFactor
function healthFactor(address account, address projectToken, address lendingToken) external view returns (uint256 numerator, uint256 denominator)
getProjectTokenEvaluation
function getProjectTokenEvaluation(address projectToken, uint256 projectTokenAmount) external view returns (uint256)
lendingTokensLength
function lendingTokensLength() external view returns (uint256)
projectTokensLength
function projectTokensLength() external view returns (uint256)
getPosition
function getPosition(address account, address projectToken, address lendingToken) external view returns (uint256 depositedProjectTokenAmount, uint256 loanBody, uint256 accrual, uint256 healthFactorNumerator, uint256 healthFactorDenominator)
decimals
function decimals() external view returns (uint8)
IBPrimaryIndexToken
mintTo
function mintTo(address minter, uint256 mintAmount) external returns (uint256 err, uint256 mintedAmount)
Sender supplies assets into the market and receives cTokens in exchange
Accrues interest whether or not the operation succeeds, unless reverted
minter
address
the address of account which earn liquidity
mintAmount
uint256
The amount of the underlying asset to supply to minter return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) return uint minted amount
redeemTo
function redeemTo(address redeemer, uint256 redeemTokens) external returns (uint256)
Sender redeems cTokens in exchange for the underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemer
address
redeemTokens
uint256
The number of cTokens to redeem into underlying
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
redeemUnderlyingTo
function redeemUnderlyingTo(uint256 redeemAmount) external returns (uint256)
Sender redeems cTokens in exchange for a specified amount of underlying asset
Accrues interest whether or not the operation succeeds, unless reverted
redeemAmount
uint256
The amount of underlying to redeem
[0]
uint256
uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
balanceOf
function balanceOf(address owner) external view returns (uint256)
Get the token balance of the `owner`
owner
address
The address of the account to query
[0]
uint256
The number of tokens owned by `owner`
IUniswapV2Router02
factory
function factory() external pure returns (address)
WETH
function WETH() external pure returns (address)
addLiquidity
function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)
addLiquidityETH
function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity)
removeLiquidity
function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)
removeLiquidityETH
function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns (uint256 amountToken, uint256 amountETH)
removeLiquidityWithPermit
function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint256 amountA, uint256 amountB)
removeLiquidityETHWithPermit
function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint256 amountToken, uint256 amountETH)
swapExactTokensForTokens
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) external returns (uint256[] amounts)
swapTokensForExactTokens
function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) external returns (uint256[] amounts)
swapExactETHForTokens
function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) external payable returns (uint256[] amounts)
swapTokensForExactETH
function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) external returns (uint256[] amounts)
swapExactTokensForETH
function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) external returns (uint256[] amounts)
swapETHForExactTokens
function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) external payable returns (uint256[] amounts)
quote
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB)
getAmountOut
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns (uint256 amountOut)
getAmountIn
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external pure returns (uint256 amountIn)
getAmountsOut
function getAmountsOut(uint256 amountIn, address[] path) external view returns (uint256[] amounts)
getAmountsIn
function getAmountsIn(uint256 amountOut, address[] path) external view returns (uint256[] amounts)
removeLiquidityETHSupportingFeeOnTransferTokens
function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external returns (uint256 amountETH)
removeLiquidityETHWithPermitSupportingFeeOnTransferTokens
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint256 amountETH)
swapExactTokensForTokensSupportingFeeOnTransferTokens
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) external
swapExactETHForTokensSupportingFeeOnTransferTokens
function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) external payable
swapExactTokensForETHSupportingFeeOnTransferTokens
function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) external
BitMaps
Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
BitMap
struct BitMap {
mapping(uint256 => uint256) _data;
}
get
function get(struct BitMaps.BitMap bitmap, uint256 index) internal view returns (bool)
Returns whether the bit at `index` is set.
setTo
function setTo(struct BitMaps.BitMap bitmap, uint256 index, bool value) internal
Sets the bit at `index` to the boolean `value`.
set
function set(struct BitMaps.BitMap bitmap, uint256 index) internal
Sets the bit at `index`.
unset
function unset(struct BitMaps.BitMap bitmap, uint256 index) internal
Unsets the bit at `index`.
SignedSafeMath
_Wrappers over Solidity's arithmetic operations.
NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler now has built in overflow checking._
mul
function mul(int256 a, int256 b) internal pure returns (int256)
_Returns the multiplication of two signed integers, reverting on overflow.
Counterpart to Solidity's `*` operator.
Requirements:
Multiplication cannot overflow._
div
function div(int256 a, int256 b) internal pure returns (int256)
_Returns the integer division of two signed integers. Reverts on division by zero. The result is rounded towards zero.
Counterpart to Solidity's `/` operator.
Requirements:
The divisor cannot be zero._
sub
function sub(int256 a, int256 b) internal pure returns (int256)
_Returns the subtraction of two signed integers, reverting on overflow.
Counterpart to Solidity's `-` operator.
Requirements:
Subtraction cannot overflow._
add
function add(int256 a, int256 b) internal pure returns (int256)
_Returns the addition of two signed integers, reverting on overflow.
Counterpart to Solidity's `+` operator.
Requirements:
Addition cannot overflow._
Create2Upgradeable
_Helper to make usage of the `CREATE2` EVM opcode easier and safer. `CREATE2` can be used to compute in advance the address where a smart contract will be deployed, which allows for interesting new mechanisms known as 'counterfactual interactions'.
See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more information._
deploy
function deploy(uint256 amount, bytes32 salt, bytes bytecode) internal returns (address)
_Deploys a contract using `CREATE2`. The address where the contract will be deployed can be known in advance via {computeAddress}.
The bytecode for a contract can be obtained from Solidity with `type(contractName).creationCode`.
Requirements:
`bytecode` must not be empty.
`salt` must have not been used for `bytecode` already.
the factory must have a balance of at least `amount`.
if `amount` is non-zero, `bytecode` must have a `payable` constructor._
computeAddress
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address)
Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecodeHash` or `salt` will result in a new destination address.
computeAddress
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address)
Returns the address where a contract will be stored if deployed via {deploy} from a contract located at `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
Clones
_https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for deploying minimal proxy contracts, also known as "clones".
> To simply and cheaply clone contract functionality in an immutable way, this standard specifies > a minimal bytecode implementation that delegates all calls to a known, fixed address.
The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the deterministic method.
Available since v3.4._
clone
function clone(address implementation) internal returns (address instance)
_Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
This function uses the create opcode, which should never revert._
cloneDeterministic
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance)
_Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same `implementation` and `salt` multiple time will revert, since the clones cannot be deployed twice at the same address._
predictDeterministicAddress
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted)
Computes the address of a clone deployed using {Clones-cloneDeterministic}.
predictDeterministicAddress
function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted)
Computes the address of a clone deployed using {Clones-cloneDeterministic}.
IERC1363ReceiverUpgradeable
onTransferReceived
function onTransferReceived(address operator, address from, uint256 value, bytes data) external returns (bytes4)
Handle the receipt of ERC1363 tokens
Any ERC1363 smart contract calls this function on the recipient after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the transfer. Return of other than the magic value MUST result in the transaction being reverted. Note: the token contract address is always the message sender.
operator
address
address The address which called `transferAndCall` or `transferFromAndCall` function
from
address
address The address which are token transferred from
value
uint256
uint256 The amount of tokens transferred
data
bytes
bytes Additional data with no specified format
[0]
bytes4
`bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` unless throwing
IComptroller
isComptroller
function isComptroller() external view returns (bool)
Indicator that this is a Comptroller contract (for inspection)
getAssetsIn
function getAssetsIn(address account) external view returns (address[])
getAccountLiquidity
function getAccountLiquidity(address account) external view returns (uint256, uint256, uint256)
checkMembership
function checkMembership(address account, address cToken) external view returns (bool)
getPrimaryIndexTokenAddress
function getPrimaryIndexTokenAddress() external view returns (address)
enterMarkets
function enterMarkets(address[] cTokens) external returns (uint256[])
enterMarket
function enterMarket(address cToken, address borrower) external returns (uint256)
exitMarket
function exitMarket(address cToken) external returns (uint256)
mintAllowed
function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256)
mintVerify
function mintVerify(address cToken, address minter, uint256 mintAmount, uint256 mintTokens) external
redeemAllowed
function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external returns (uint256)
redeemVerify
function redeemVerify(address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens) external
borrowAllowed
function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external returns (uint256)
borrowVerify
function borrowVerify(address cToken, address borrower, uint256 borrowAmount) external
repayBorrowAllowed
function repayBorrowAllowed(address cToken, address payer, address borrower, uint256 repayAmount) external returns (uint256)
repayBorrowVerify
function repayBorrowVerify(address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex) external
liquidateBorrowAllowed
function liquidateBorrowAllowed(address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount) external returns (uint256)
liquidateBorrowVerify
function liquidateBorrowVerify(address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens) external
seizeAllowed
function seizeAllowed(address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens) external returns (uint256)
seizeVerify
function seizeVerify(address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens) external
transferAllowed
function transferAllowed(address cToken, address src, address dst, uint256 transferTokens) external returns (uint256)
transferVerify
function transferVerify(address cToken, address src, address dst, uint256 transferTokens) external
liquidateCalculateSeizeTokens
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount) external view returns (uint256, uint256)
IERC1363SpenderUpgradeable
onApprovalReceived
function onApprovalReceived(address owner, uint256 value, bytes data) external returns (bytes4)
Handle the approval of ERC1363 tokens
Any ERC1363 smart contract calls this function on the recipient after an `approve`. This function MAY throw to revert and reject the approval. Return of other than the magic value MUST result in the transaction being reverted. Note: the token contract address is always the message sender.
owner
address
address The address which called `approveAndCall` function
value
uint256
uint256 The amount of tokens to be spent
data
bytes
bytes Additional data with no specified format
[0]
bytes4
`bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` unless throwing
ISimplePriceOracle
PricePosted
event PricePosted(address asset, uint256 previousPriceMantissa, uint256 requestedPriceMantissa, uint256 newPriceMantissa)
getUnderlyingPrice
function getUnderlyingPrice(address cToken) external view returns (uint256)
setUnderlyingPrice
function setUnderlyingPrice(address cToken, uint256 underlyingPriceMantissa) external
setDirectPrice
function setDirectPrice(address asset, uint256 price) external
assetPrices
function assetPrices(address asset) external view returns (uint256)
IERC1363Receiver
onTransferReceived
function onTransferReceived(address operator, address from, uint256 value, bytes data) external returns (bytes4)
Handle the receipt of ERC1363 tokens
Any ERC1363 smart contract calls this function on the recipient after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the transfer. Return of other than the magic value MUST result in the transaction being reverted. Note: the token contract address is always the message sender.
operator
address
address The address which called `transferAndCall` or `transferFromAndCall` function
from
address
address The address which are token transferred from
value
uint256
uint256 The amount of tokens transferred
data
bytes
bytes Additional data with no specified format
[0]
bytes4
`bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` unless throwing
BitMapsUpgradeable
Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
BitMap
struct BitMap {
mapping(uint256 => uint256) _data;
}
get
function get(struct BitMapsUpgradeable.BitMap bitmap, uint256 index) internal view returns (bool)
Returns whether the bit at `index` is set.
setTo
function setTo(struct BitMapsUpgradeable.BitMap bitmap, uint256 index, bool value) internal
Sets the bit at `index` to the boolean `value`.
set
function set(struct BitMapsUpgradeable.BitMap bitmap, uint256 index) internal
Sets the bit at `index`.
unset
function unset(struct BitMapsUpgradeable.BitMap bitmap, uint256 index) internal
Unsets the bit at `index`.
ERC1820Implementer
_Implementation of the {IERC1820Implementer} interface.
Contracts may inherit from this and call {registerInterfaceForAddress} to declare their willingness to be implementers. {IERC1820Registry-setInterfaceImplementer} should then be called for the registration to be complete.
_ERC1820_ACCEPT_MAGIC
bytes32 _ERC1820_ACCEPT_MAGIC
_supportedInterfaces
mapping(bytes32 => mapping(address => bool)) _supportedInterfaces
canImplementInterfaceForAddress
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) public view virtual returns (bytes32)
See {IERC1820Implementer-canImplementInterfaceForAddress}.
_registerInterfaceForAddress
function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual
_Declares the contract as willing to be an implementer of `interfaceHash` for `account`.
See {IERC1820Registry-setInterfaceImplementer} and {IERC1820Registry-interfaceHash}._
IERC1820Implementer
Interface for an ERC1820 implementer, as defined in the https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. Used by contracts that will be registered as implementers in the {IERC1820Registry}.
canImplementInterfaceForAddress
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32)
_Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract implements `interfaceHash` for `account`.
See {IERC1820Registry-setInterfaceImplementer}._
Last updated