// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/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.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 48: ArrayLib.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.0;libraryArrayLib{
functionsum(uint256[] memory input) internalpurereturns (uint256) {
uint256 value =0;
for (uint256 i =0; i < input.length; ) {
value += input[i];
unchecked {
i++;
}
}
return value;
}
/// @notice return index of the element if found, else return uint256.maxfunctionfind(address[] memory array, address element) internalpurereturns (uint256 index) {
uint256 length = array.length;
for (uint256 i =0; i < length; ) {
if (array[i] == element) return i;
unchecked {
i++;
}
}
returntype(uint256).max;
}
functionappend(address[] memory inp, address element) internalpurereturns (address[] memory out) {
uint256 length = inp.length;
out =newaddress[](length +1);
for (uint256 i =0; i < length; ) {
out[i] = inp[i];
unchecked {
i++;
}
}
out[length] = element;
}
/**
* @dev This function assumes a and b each contains unidentical elements
* @param a array of addresses a
* @param b array of addresses b
* @return out Concatenation of a and b containing unidentical elements
*/functionmerge(address[] memory a, address[] memory b) internalpurereturns (address[] memory out) {
unchecked {
uint256 countUnidenticalB =0;
bool[] memory isUnidentical =newbool[](b.length);
for (uint256 i =0; i < b.length; ++i) {
if (!contains(a, b[i])) {
countUnidenticalB++;
isUnidentical[i] =true;
}
}
out =newaddress[](a.length+ countUnidenticalB);
for (uint256 i =0; i < a.length; ++i) {
out[i] = a[i];
}
uint256 id = a.length;
for (uint256 i =0; i < b.length; ++i) {
if (isUnidentical[i]) {
out[id++] = b[i];
}
}
}
}
// various version of containsfunctioncontains(address[] memory array, address element) internalpurereturns (bool) {
uint256 length = array.length;
for (uint256 i =0; i < length; ) {
if (array[i] == element) returntrue;
unchecked {
i++;
}
}
returnfalse;
}
functioncontains(bytes4[] memory array, bytes4 element) internalpurereturns (bool) {
uint256 length = array.length;
for (uint256 i =0; i < length; ) {
if (array[i] == element) returntrue;
unchecked {
i++;
}
}
returnfalse;
}
functioncreate(address a) internalpurereturns (address[] memory res) {
res =newaddress[](1);
res[0] = a;
}
functioncreate(address a, address b) internalpurereturns (address[] memory res) {
res =newaddress[](2);
res[0] = a;
res[1] = b;
}
functioncreate(uint256 a) internalpurereturns (uint256[] memory res) {
res =newuint256[](1);
res[0] = a;
}
}
Contract Source Code
File 3 of 48: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 4 of 48: Counters.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)pragmasolidity ^0.8.0;/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/libraryCounters{
structCounter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add// this feature: see https://github.com/ethereum/solidity/issues/4637uint256 _value; // default: 0
}
functioncurrent(Counter storage counter) internalviewreturns (uint256) {
return counter._value;
}
functionincrement(Counter storage counter) internal{
unchecked {
counter._value +=1;
}
}
functiondecrement(Counter storage counter) internal{
uint256 value = counter._value;
require(value >0, "Counter: decrement overflow");
unchecked {
counter._value = value -1;
}
}
functionreset(Counter storage counter) internal{
counter._value =0;
}
}
Contract Source Code
File 5 of 48: ECDSA.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)pragmasolidity ^0.8.0;import"../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/libraryECDSA{
enumRecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function_throwError(RecoverError error) privatepure{
if (error == RecoverError.NoError) {
return; // no error: do nothing
} elseif (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} elseif (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} elseif (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash, bytesmemory signature) internalpurereturns (address, RecoverError) {
if (signature.length==65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly./// @solidity memory-safe-assemblyassembly {
r :=mload(add(signature, 0x20))
s :=mload(add(signature, 0x40))
v :=byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/functionrecover(bytes32 hash, bytesmemory signature) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash, bytes32 r, bytes32 vs) internalpurereturns (address, RecoverError) {
bytes32 s = vs &bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v =uint8((uint256(vs) >>255) +27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/functionrecover(bytes32 hash, bytes32 r, bytes32 vs) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internalpurereturns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most// signatures from current libraries generate a unique signature with an s-value in the lower half order.//// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept// these malleable signatures as well.if (uint256(s) >0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer addressaddress signer =ecrecover(hash, v, r, s);
if (signer ==address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/functionrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytes32 hash) internalpurereturns (bytes32 message) {
// 32 is the length in bytes of hash,// enforced by the type signature above/// @solidity memory-safe-assemblyassembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message :=keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytesmemory s) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/functiontoTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internalpurereturns (bytes32 data) {
/// @solidity memory-safe-assemblyassembly {
let ptr :=mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data :=keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/functiontoDataWithIntendedValidatorHash(address validator, bytesmemory data) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
Contract Source Code
File 6 of 48: EIP712.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)pragmasolidity ^0.8.8;import"./ECDSA.sol";
import"../ShortStrings.sol";
import"../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* _Available since v3.4._
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
*/abstractcontractEIP712isIERC5267{
usingShortStringsfor*;
bytes32privateconstant _TYPE_HASH =keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to// invalidate the cached domain separator if the chain id changes.bytes32privateimmutable _cachedDomainSeparator;
uint256privateimmutable _cachedChainId;
addressprivateimmutable _cachedThis;
bytes32privateimmutable _hashedName;
bytes32privateimmutable _hashedVersion;
ShortString privateimmutable _name;
ShortString privateimmutable _version;
stringprivate _nameFallback;
stringprivate _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/constructor(stringmemory name, stringmemory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName =keccak256(bytes(name));
_hashedVersion =keccak256(bytes(version));
_cachedChainId =block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis =address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/function_domainSeparatorV4() internalviewreturns (bytes32) {
if (address(this) == _cachedThis &&block.chainid== _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function_buildDomainSeparator() privateviewreturns (bytes32) {
returnkeccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/function_hashTypedDataV4(bytes32 structHash) internalviewvirtualreturns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {EIP-5267}.
*
* _Available since v4.9._
*/functioneip712Domain()
publicviewvirtualoverridereturns (bytes1 fields,
stringmemory name,
stringmemory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_name.toStringWithFallback(_nameFallback),
_version.toStringWithFallback(_versionFallback),
block.chainid,
address(this),
bytes32(0),
newuint256[](0)
);
}
}
Contract Source Code
File 7 of 48: ERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)pragmasolidity ^0.8.0;import"./IERC20.sol";
import"./extensions/IERC20Metadata.sol";
import"../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of 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}.
*/contractERC20isContext, IERC20, IERC20Metadata{
mapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256)) private _allowances;
uint256private _totalSupply;
stringprivate _name;
stringprivate _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/functiondecimals() publicviewvirtualoverridereturns (uint8) {
return18;
}
/**
* @dev See {IERC20-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/functionbalanceOf(address account) publicviewvirtualoverridereturns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/functiontransfer(address to, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
returntrue;
}
/**
* @dev See {IERC20-allowance}.
*/functionallowance(address owner, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionapprove(address spender, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
returntrue;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/functiontransferFrom(addressfrom, address to, uint256 amount) publicvirtualoverridereturns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
returntrue;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionincreaseAllowance(address spender, uint256 addedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
returntrue;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/functiondecreaseAllowance(address spender, uint256 subtractedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
returntrue;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/function_transfer(addressfrom, address to, uint256 amount) internalvirtual{
require(from!=address(0), "ERC20: transfer from the zero address");
require(to !=address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/function_mint(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/function_burn(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/function_approve(address owner, address spender, uint256 amount) internalvirtual{
require(owner !=address(0), "ERC20: approve from the zero address");
require(spender !=address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/function_spendAllowance(address owner, address spender, uint256 amount) internalvirtual{
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance !=type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom, address to, uint256 amount) internalvirtual{}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_afterTokenTransfer(addressfrom, address to, uint256 amount) internalvirtual{}
}
Contract Source Code
File 8 of 48: ERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol)pragmasolidity ^0.8.0;import"./IERC20Permit.sol";
import"../ERC20.sol";
import"../../../utils/cryptography/ECDSA.sol";
import"../../../utils/cryptography/EIP712.sol";
import"../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/abstractcontractERC20PermitisERC20, IERC20Permit, EIP712{
usingCountersforCounters.Counter;
mapping(address=> Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcasebytes32privateconstant _PERMIT_TYPEHASH =keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
* However, to ensure consistency with the upgradeable transpiler, we will continue
* to reserve a slot.
* @custom:oz-renamed-from _PERMIT_TYPEHASH
*/// solhint-disable-next-line var-name-mixedcasebytes32private _PERMIT_TYPEHASH_DEPRECATED_SLOT;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/constructor(stringmemory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtualoverride{
require(block.timestamp<= deadline, "ERC20Permit: expired deadline");
bytes32 structHash =keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/functionnonces(address owner) publicviewvirtualoverridereturns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewoverridereturns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/function_useNonce(address owner) internalvirtualreturns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) externalreturns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 amount) externalreturns (bool);
}
Contract Source Code
File 11 of 48: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 12 of 48: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/interfaceIERC20Permit{
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/functionnonces(address owner) externalviewreturns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
Contract Source Code
File 13 of 48: IERC5267.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)pragmasolidity ^0.8.0;interfaceIERC5267{
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/eventEIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/functioneip712Domain()
externalviewreturns (bytes1 fields,
stringmemory name,
stringmemory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
Contract Source Code
File 14 of 48: IPGauge.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.0;interfaceIPGauge{
functiontotalActiveSupply() externalviewreturns (uint256);
functionactiveBalance(address user) externalviewreturns (uint256);
// only available for newer factories. please check the verified contractseventRedeemRewards(addressindexed user, uint256[] rewardsOut);
}
// SPDX-License-Identifier: GPL-3.0-or-later/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/pragmasolidity ^0.8.0;import"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
interfaceIStandardizedYieldisIERC20Metadata{
/// @dev Emitted when any base tokens is deposited to mint shareseventDeposit(addressindexed caller,
addressindexed receiver,
addressindexed tokenIn,
uint256 amountDeposited,
uint256 amountSyOut
);
/// @dev Emitted when any shares are redeemed for base tokenseventRedeem(addressindexed caller,
addressindexed receiver,
addressindexed tokenOut,
uint256 amountSyToRedeem,
uint256 amountTokenOut
);
/// @dev check `assetInfo()` for more informationenumAssetType {
TOKEN,
LIQUIDITY
}
/// @dev Emitted when (`user`) claims their rewardseventClaimRewards(addressindexed user, address[] rewardTokens, uint256[] rewardAmounts);
/**
* @notice mints an amount of shares by depositing a base token.
* @param receiver shares recipient address
* @param tokenIn address of the base tokens to mint shares
* @param amountTokenToDeposit amount of base tokens to be transferred from (`msg.sender`)
* @param minSharesOut reverts if amount of shares minted is lower than this
* @return amountSharesOut amount of shares minted
* @dev Emits a {Deposit} event
*
* Requirements:
* - (`tokenIn`) must be a valid base token.
*/functiondeposit(address receiver,
address tokenIn,
uint256 amountTokenToDeposit,
uint256 minSharesOut
) externalpayablereturns (uint256 amountSharesOut);
/**
* @notice redeems an amount of base tokens by burning some shares
* @param receiver recipient address
* @param amountSharesToRedeem amount of shares to be burned
* @param tokenOut address of the base token to be redeemed
* @param minTokenOut reverts if amount of base token redeemed is lower than this
* @param burnFromInternalBalance if true, burns from balance of `address(this)`, otherwise burns from `msg.sender`
* @return amountTokenOut amount of base tokens redeemed
* @dev Emits a {Redeem} event
*
* Requirements:
* - (`tokenOut`) must be a valid base token.
*/functionredeem(address receiver,
uint256 amountSharesToRedeem,
address tokenOut,
uint256 minTokenOut,
bool burnFromInternalBalance
) externalreturns (uint256 amountTokenOut);
/**
* @notice exchangeRate * syBalance / 1e18 must return the asset balance of the account
* @notice vice-versa, if a user uses some amount of tokens equivalent to X asset, the amount of sy
he can mint must be X * exchangeRate / 1e18
* @dev SYUtils's assetToSy & syToAsset should be used instead of raw multiplication
& division
*/functionexchangeRate() externalviewreturns (uint256 res);
/**
* @notice claims reward for (`user`)
* @param user the user receiving their rewards
* @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens`
* @dev
* Emits a `ClaimRewards` event
* See {getRewardTokens} for list of reward tokens
*/functionclaimRewards(address user) externalreturns (uint256[] memory rewardAmounts);
/**
* @notice get the amount of unclaimed rewards for (`user`)
* @param user the user to check for
* @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens`
*/functionaccruedRewards(address user) externalviewreturns (uint256[] memory rewardAmounts);
functionrewardIndexesCurrent() externalreturns (uint256[] memory indexes);
functionrewardIndexesStored() externalviewreturns (uint256[] memory indexes);
/**
* @notice returns the list of reward token addresses
*/functiongetRewardTokens() externalviewreturns (address[] memory);
/**
* @notice returns the address of the underlying yield token
*/functionyieldToken() externalviewreturns (address);
/**
* @notice returns all tokens that can mint this SY
*/functiongetTokensIn() externalviewreturns (address[] memory res);
/**
* @notice returns all tokens that can be redeemed by this SY
*/functiongetTokensOut() externalviewreturns (address[] memory res);
functionisValidTokenIn(address token) externalviewreturns (bool);
functionisValidTokenOut(address token) externalviewreturns (bool);
functionpreviewDeposit(address tokenIn,
uint256 amountTokenToDeposit
) externalviewreturns (uint256 amountSharesOut);
functionpreviewRedeem(address tokenOut,
uint256 amountSharesToRedeem
) externalviewreturns (uint256 amountTokenOut);
/**
* @notice This function contains information to interpret what the asset is
* @return assetType the type of the asset (0 for ERC20 tokens, 1 for AMM liquidity tokens,
2 for bridged yield bearing tokens like wstETH, rETH on Arbi whose the underlying asset doesn't exist on the chain)
* @return assetAddress the address of the asset
* @return assetDecimals the decimals of the asset
*/functionassetInfo() externalviewreturns (AssetType assetType, address assetAddress, uint8 assetDecimals);
}
Contract Source Code
File 26 of 48: IWETH.sol
// SPDX-License-Identifier: GPL-3.0-or-later/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/pragmasolidity ^0.8.0;import"@openzeppelin/contracts/token/ERC20/IERC20.sol";
interfaceIWETHisIERC20{
eventDeposit(addressindexed dst, uint256 wad);
eventWithdrawal(addressindexed src, uint256 wad);
functiondeposit() externalpayable;
functionwithdraw(uint256 wad) external;
}
Contract Source Code
File 27 of 48: LogExpMath.sol
// SPDX-License-Identifier: GPL-3.0-or-later// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to// permit persons to whom the Software is furnished to do so, subject to the following conditions:// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the// Software.// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.pragmasolidity ^0.8.0;/* solhint-disable *//**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/libraryLogExpMath{
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying// two numbers, and multiply by ONE when dividing them.// All arguments and return values are 18 decimal fixed point numbers.int256constant ONE_18 =1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the// case of ln36, 36 decimals.int256constant ONE_20 =1e20;
int256constant ONE_36 =1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.//// Because internally the result will be stored using 20 decimals, the largest possible result is// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.// The smallest possible result is 10^(-18), which makes largest negative argument// ln(10^(-18)) = -41.446531673892822312.// We use 130.0 and -41.0 to have some safety margin.int256constant MAX_NATURAL_EXPONENT =130e18;
int256constant MIN_NATURAL_EXPONENT =-41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point// 256 bit integer.int256constant LN_36_LOWER_BOUND = ONE_18 -1e17;
int256constant LN_36_UPPER_BOUND = ONE_18 +1e17;
uint256constant MILD_EXPONENT_BOUND =2**254/uint256(ONE_20);
// 18 decimal constantsint256constant x0 =128000000000000000000; // 2ˆ7int256constant a0 =38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)int256constant x1 =64000000000000000000; // 2ˆ6int256constant a1 =6235149080811616882910000000; // eˆ(x1) (no decimals)// 20 decimal constantsint256constant x2 =3200000000000000000000; // 2ˆ5int256constant a2 =7896296018268069516100000000000000; // eˆ(x2)int256constant x3 =1600000000000000000000; // 2ˆ4int256constant a3 =888611052050787263676000000; // eˆ(x3)int256constant x4 =800000000000000000000; // 2ˆ3int256constant a4 =298095798704172827474000; // eˆ(x4)int256constant x5 =400000000000000000000; // 2ˆ2int256constant a5 =5459815003314423907810; // eˆ(x5)int256constant x6 =200000000000000000000; // 2ˆ1int256constant a6 =738905609893065022723; // eˆ(x6)int256constant x7 =100000000000000000000; // 2ˆ0int256constant a7 =271828182845904523536; // eˆ(x7)int256constant x8 =50000000000000000000; // 2ˆ-1int256constant a8 =164872127070012814685; // eˆ(x8)int256constant x9 =25000000000000000000; // 2ˆ-2int256constant a9 =128402541668774148407; // eˆ(x9)int256constant x10 =12500000000000000000; // 2ˆ-3int256constant a10 =113314845306682631683; // eˆ(x10)int256constant x11 =6250000000000000000; // 2ˆ-4int256constant a11 =106449445891785942956; // eˆ(x11)/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/functionexp(int256 x) internalpurereturns (int256) {
unchecked {
require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "Invalid exponent");
if (x <0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).// Fixed point division requires multiplying by ONE_18.return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the// decomposition.// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this// decomposition, which will be lower than the smallest x_n.// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.// We mutate x by subtracting x_n, making it the remainder of the decomposition.// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause// intermediate overflows. Instead we store them as plain integers, with 0 decimals.// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the// decomposition.// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct// it and compute the accumulated product.int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} elseif (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN =1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the// smaller terms.
x *=100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point// one. Recall that fixed point multiplication requires dividing by ONE_20.int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.int256 term; // Each term in the sum, where the nth term is (x^n / n!).// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) /2;
seriesSum += term;
term = ((term * x) / ONE_20) /3;
seriesSum += term;
term = ((term * x) / ONE_20) /4;
seriesSum += term;
term = ((term * x) / ONE_20) /5;
seriesSum += term;
term = ((term * x) / ONE_20) /6;
seriesSum += term;
term = ((term * x) / ONE_20) /7;
seriesSum += term;
term = ((term * x) / ONE_20) /8;
seriesSum += term;
term = ((term * x) / ONE_20) /9;
seriesSum += term;
term = ((term * x) / ONE_20) /10;
seriesSum += term;
term = ((term * x) / ONE_20) /11;
seriesSum += term;
term = ((term * x) / ONE_20) /12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),// and then drop two digits to return an 18 decimal value.return (((product * seriesSum) / ONE_20) * firstAN) /100;
}
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/functionln(int256 a) internalpurereturns (int256) {
unchecked {
// The real natural logarithm is not defined for negative numbers or zero.require(a >0, "out of bounds");
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
}
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/functionpow(uint256 x, uint256 y) internalpurereturns (uint256) {
unchecked {
if (y ==0) {
// We solve the 0^0 indetermination by making it equal one.returnuint256(ONE_18);
}
if (x ==0) {
return0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to// arrive at that r`esult. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means// x^y = exp(y * ln(x)).// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.require(x <2**255, "x out of bounds");
int256 x_int256 =int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.require(y < MILD_EXPONENT_BOUND, "y out of bounds");
int256 y_int256 =int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^yrequire(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
"product out of bounds"
);
returnuint256(exp(logx_times_y));
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/function_ln(int256 a) privatepurereturns (int256) {
unchecked {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.// Fixed point division requires multiplying by ONE_18.return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this// decomposition, which will be lower than the smallest a_n.// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.// We mutate a by subtracting a_n, making it the remainder of the decomposition.// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by// ONE_18 to convert them to fixed point.// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide// by it and compute the accumulated sum.int256 sum =0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *=100;
a *=100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series// that converges rapidly for values of `a` close to one - the same one used in ln_36.// Let z = (a - 1) / (a + 1).// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires// division by ONE_20.int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) termint256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial zint256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num /3;
num = (num * z_squared) / ONE_20;
seriesSum += num /5;
num = (num * z_squared) / ONE_20;
seriesSum += num /7;
num = (num * z_squared) / ONE_20;
seriesSum += num /9;
num = (num * z_squared) / ONE_20;
seriesSum += num /11;
// 6 Taylor terms are sufficient for 36 decimal precision.// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *=2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal// value.return (sum + seriesSum) /100;
}
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/function_ln_36(int256 x) privatepurereturns (int256) {
unchecked {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits// worthwhile.// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires// division by ONE_36.int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) termint256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial zint256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num /3;
num = (num * z_squared) / ONE_36;
seriesSum += num /5;
num = (num * z_squared) / ONE_36;
seriesSum += num /7;
num = (num * z_squared) / ONE_36;
seriesSum += num /9;
num = (num * z_squared) / ONE_36;
seriesSum += num /11;
num = (num * z_squared) / ONE_36;
seriesSum += num /13;
num = (num * z_squared) / ONE_36;
seriesSum += num /15;
// 8 Taylor terms are sufficient for 36 decimal precision.// All that remains is multiplying by 2 (non fixed point).return seriesSum *2;
}
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)pragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
enumRounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/functionaverage(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b) / 2 can overflow.return (a & b) + (a ^ b) /2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/functionceilDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.return a ==0 ? 0 : (a -1) / b +1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator) internalpurereturns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256// variables such that product = prod1 * 2^256 + prod0.uint256 prod0; // Least significant 256 bits of the productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(x, y, not(0))
prod0 :=mul(x, y)
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.if (prod1 ==0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.// The surrounding unchecked block does not change this fact.// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////// 512 by 256 division.///////////////////////////////////////////////// Make division exact by subtracting the remainder from [prod1 prod0].uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder :=mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 :=sub(prod1, gt(remainder, prod0))
prod0 :=sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.// See https://cs.stackexchange.com/q/138556/92363.// Does not overflow because the denominator cannot be zero at this stage in the function.uint256 twos = denominator & (~denominator +1);
assembly {
// Divide denominator by twos.
denominator :=div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 :=div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos :=add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for// four bits. That is, denominator * inv = 1 mod 2^4.uint256 inverse = (3* denominator) ^2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works// in modular arithmetic, doubling the correct bits in each step.
inverse *=2- denominator * inverse; // inverse mod 2^8
inverse *=2- denominator * inverse; // inverse mod 2^16
inverse *=2- denominator * inverse; // inverse mod 2^32
inverse *=2- denominator * inverse; // inverse mod 2^64
inverse *=2- denominator * inverse; // inverse mod 2^128
inverse *=2- denominator * inverse; // inverse mod 2^256// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internalpurereturns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up &&mulmod(x, y, denominator) >0) {
result +=1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/functionsqrt(uint256 a) internalpurereturns (uint256) {
if (a ==0) {
return0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.//// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.//// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`//// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.uint256 result =1<< (log2(a) >>1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision// into the expected uint128 result.unchecked {
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/functionsqrt(uint256 a, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=128;
}
if (value >>64>0) {
value >>=64;
result +=64;
}
if (value >>32>0) {
value >>=32;
result +=32;
}
if (value >>16>0) {
value >>=16;
result +=16;
}
if (value >>8>0) {
value >>=8;
result +=8;
}
if (value >>4>0) {
value >>=4;
result +=4;
}
if (value >>2>0) {
value >>=2;
result +=2;
}
if (value >>1>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result =log2(value);
return result + (rounding == Rounding.Up &&1<< result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >=10**64) {
value /=10**64;
result +=64;
}
if (value >=10**32) {
value /=10**32;
result +=32;
}
if (value >=10**16) {
value /=10**16;
result +=16;
}
if (value >=10**8) {
value /=10**8;
result +=8;
}
if (value >=10**4) {
value /=10**4;
result +=4;
}
if (value >=10**2) {
value /=10**2;
result +=2;
}
if (value >=10**1) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up &&10** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/functionlog256(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=16;
}
if (value >>64>0) {
value >>=64;
result +=8;
}
if (value >>32>0) {
value >>=32;
result +=4;
}
if (value >>16>0) {
value >>=16;
result +=2;
}
if (value >>8>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog256(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up &&1<< (result <<3) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.0;import"../libraries/Errors.sol";
/// Adapted from UniswapV3's OraclelibraryOracleLib{
structObservation {
uint32 blockTimestamp;
uint216 lnImpliedRateCumulative;
bool initialized;
// 1 SLOT = 256 bits
}
functiontransform(
Observation memory last,
uint32 blockTimestamp,
uint96 lnImpliedRate
) publicpurereturns (Observation memory) {
return
Observation({
blockTimestamp: blockTimestamp,
lnImpliedRateCumulative: last.lnImpliedRateCumulative +uint216(lnImpliedRate) *
(blockTimestamp - last.blockTimestamp),
initialized: true
});
}
functioninitialize(
Observation[65535] storageself,
uint32 time
) publicreturns (uint16 cardinality, uint16 cardinalityNext) {
self[0] = Observation({blockTimestamp: time, lnImpliedRateCumulative: 0, initialized: true});
return (1, 1);
}
functionwrite(
Observation[65535] storageself,
uint16 index,
uint32 blockTimestamp,
uint96 lnImpliedRate,
uint16 cardinality,
uint16 cardinalityNext
) publicreturns (uint16 indexUpdated, uint16 cardinalityUpdated) {
Observation memory last =self[index];
// early return if we've already written an observation this blockif (last.blockTimestamp == blockTimestamp) return (index, cardinality);
// if the conditions are right, we can bump the cardinalityif (cardinalityNext > cardinality && index == (cardinality -1)) {
cardinalityUpdated = cardinalityNext;
} else {
cardinalityUpdated = cardinality;
}
indexUpdated = (index +1) % cardinalityUpdated;
self[indexUpdated] = transform(last, blockTimestamp, lnImpliedRate);
}
functiongrow(Observation[65535] storageself, uint16 current, uint16 next) publicreturns (uint16) {
if (current ==0) revert Errors.OracleUninitialized();
// no-op if the passed next value isn't greater than the current next valueif (next <= current) return current;
// store in each slot to prevent fresh SSTOREs in swaps// this data will not be used because the initialized boolean is still falsefor (uint16 i = current; i != next; ) {
self[i].blockTimestamp =1;
unchecked {
++i;
}
}
return next;
}
functionbinarySearch(
Observation[65535] storageself,
uint32 target,
uint16 index,
uint16 cardinality
) publicviewreturns (Observation memory beforeOrAt, Observation memory atOrAfter) {
uint256 l = (index +1) % cardinality; // oldest observationuint256 r = l + cardinality -1; // newest observationuint256 i;
while (true) {
i = (l + r) /2;
beforeOrAt =self[i % cardinality];
// we've landed on an uninitialized observation, keep searching higher (more recently)if (!beforeOrAt.initialized) {
l = i +1;
continue;
}
atOrAfter =self[(i +1) % cardinality];
bool targetAtOrAfter = beforeOrAt.blockTimestamp <= target;
// check if we've found the answer!if (targetAtOrAfter && target <= atOrAfter.blockTimestamp) break;
if (!targetAtOrAfter) r = i -1;
else l = i +1;
}
}
functiongetSurroundingObservations(
Observation[65535] storageself,
uint32 target,
uint96 lnImpliedRate,
uint16 index,
uint16 cardinality
) publicviewreturns (Observation memory beforeOrAt, Observation memory atOrAfter) {
// optimistically set before to the newest observation
beforeOrAt =self[index];
// if the target is chronologically at or after the newest observation, we can early returnif (beforeOrAt.blockTimestamp <= target) {
if (beforeOrAt.blockTimestamp == target) {
// if newest observation equals target, we're in the same block, so we can ignore atOrAfterreturn (beforeOrAt, atOrAfter);
} else {
// otherwise, we need to transformreturn (beforeOrAt, transform(beforeOrAt, target, lnImpliedRate));
}
}
// now, set beforeOrAt to the oldest observation
beforeOrAt =self[(index +1) % cardinality];
if (!beforeOrAt.initialized) beforeOrAt =self[0];
// ensure that the target is chronologically at or after the oldest observationif (target < beforeOrAt.blockTimestamp) revert Errors.OracleTargetTooOld(target, beforeOrAt.blockTimestamp);
// if we've reached this point, we have to binary searchreturn binarySearch(self, target, index, cardinality);
}
functionobserveSingle(
Observation[65535] storageself,
uint32 time,
uint32 secondsAgo,
uint96 lnImpliedRate,
uint16 index,
uint16 cardinality
) publicviewreturns (uint216 lnImpliedRateCumulative) {
if (secondsAgo ==0) {
Observation memory last =self[index];
if (last.blockTimestamp != time) {
return transform(last, time, lnImpliedRate).lnImpliedRateCumulative;
}
return last.lnImpliedRateCumulative;
}
uint32 target = time - secondsAgo;
(Observation memory beforeOrAt, Observation memory atOrAfter) = getSurroundingObservations(
self,
target,
lnImpliedRate,
index,
cardinality
);
if (target == beforeOrAt.blockTimestamp) {
// we're at the left boundaryreturn beforeOrAt.lnImpliedRateCumulative;
} elseif (target == atOrAfter.blockTimestamp) {
// we're at the right boundaryreturn atOrAfter.lnImpliedRateCumulative;
} else {
// we're in the middlereturn (beforeOrAt.lnImpliedRateCumulative +uint216(
(uint256(atOrAfter.lnImpliedRateCumulative - beforeOrAt.lnImpliedRateCumulative) *
(target - beforeOrAt.blockTimestamp)) / (atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp)
));
}
}
functionobserve(
Observation[65535] storageself,
uint32 time,
uint32[] memory secondsAgos,
uint96 lnImpliedRate,
uint16 index,
uint16 cardinality
) publicviewreturns (uint216[] memory lnImpliedRateCumulative) {
if (cardinality ==0) revert Errors.OracleZeroCardinality();
lnImpliedRateCumulative =newuint216[](secondsAgos.length);
for (uint256 i =0; i < lnImpliedRateCumulative.length; ++i) {
lnImpliedRateCumulative[i] = observeSingle(self, time, secondsAgos[i], lnImpliedRate, index, cardinality);
}
}
}
Contract Source Code
File 32 of 48: PMath.sol
// SPDX-License-Identifier: GPL-3.0-or-later// This program is free software: you can redistribute it and/or modify// it under the terms of the GNU General Public License as published by// the Free Software Foundation, either version 3 of the License, or// (at your option) any later version.// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU General Public License for more details.// You should have received a copy of the GNU General Public License// along with this program. If not, see <http://www.gnu.org/licenses/>.pragmasolidity ^0.8.0;/* solhint-disable private-vars-leading-underscore, reason-string */libraryPMath{
uint256internalconstant ONE =1e18; // 18 decimal placesint256internalconstant IONE =1e18; // 18 decimal placesfunctionsubMax0(uint256 a, uint256 b) internalpurereturns (uint256) {
unchecked {
return (a >= b ? a - b : 0);
}
}
functionsubNoNeg(int256 a, int256 b) internalpurereturns (int256) {
require(a >= b, "negative");
return a - b; // no unchecked since if b is very negative, a - b might overflow
}
functionmulDown(uint256 a, uint256 b) internalpurereturns (uint256) {
uint256 product = a * b;
unchecked {
return product / ONE;
}
}
functionmulDown(int256 a, int256 b) internalpurereturns (int256) {
int256 product = a * b;
unchecked {
return product / IONE;
}
}
functiondivDown(uint256 a, uint256 b) internalpurereturns (uint256) {
uint256 aInflated = a * ONE;
unchecked {
return aInflated / b;
}
}
functiondivDown(int256 a, int256 b) internalpurereturns (int256) {
int256 aInflated = a * IONE;
unchecked {
return aInflated / b;
}
}
functionrawDivUp(uint256 a, uint256 b) internalpurereturns (uint256) {
return (a + b -1) / b;
}
// @author Uniswapfunctionsqrt(uint256 y) internalpurereturns (uint256 z) {
if (y >3) {
z = y;
uint256 x = y /2+1;
while (x < z) {
z = x;
x = (y / x + x) /2;
}
} elseif (y !=0) {
z =1;
}
}
functionsquare(uint256 x) internalpurereturns (uint256) {
return x * x;
}
functionsquareDown(uint256 x) internalpurereturns (uint256) {
return mulDown(x, x);
}
functionabs(int256 x) internalpurereturns (uint256) {
returnuint256(x >0 ? x : -x);
}
functionneg(int256 x) internalpurereturns (int256) {
return x * (-1);
}
functionneg(uint256 x) internalpurereturns (int256) {
return Int(x) * (-1);
}
functionmax(uint256 x, uint256 y) internalpurereturns (uint256) {
return (x > y ? x : y);
}
functionmax(int256 x, int256 y) internalpurereturns (int256) {
return (x > y ? x : y);
}
functionmin(uint256 x, uint256 y) internalpurereturns (uint256) {
return (x < y ? x : y);
}
functionmin(int256 x, int256 y) internalpurereturns (int256) {
return (x < y ? x : y);
}
/*///////////////////////////////////////////////////////////////
SIGNED CASTS
//////////////////////////////////////////////////////////////*/functionInt(uint256 x) internalpurereturns (int256) {
require(x <=uint256(type(int256).max));
returnint256(x);
}
functionInt128(int256 x) internalpurereturns (int128) {
require(type(int128).min<= x && x <=type(int128).max);
returnint128(x);
}
functionInt128(uint256 x) internalpurereturns (int128) {
return Int128(Int(x));
}
/*///////////////////////////////////////////////////////////////
UNSIGNED CASTS
//////////////////////////////////////////////////////////////*/functionUint(int256 x) internalpurereturns (uint256) {
require(x >=0);
returnuint256(x);
}
functionUint32(uint256 x) internalpurereturns (uint32) {
require(x <=type(uint32).max);
returnuint32(x);
}
functionUint64(uint256 x) internalpurereturns (uint64) {
require(x <=type(uint64).max);
returnuint64(x);
}
functionUint112(uint256 x) internalpurereturns (uint112) {
require(x <=type(uint112).max);
returnuint112(x);
}
functionUint96(uint256 x) internalpurereturns (uint96) {
require(x <=type(uint96).max);
returnuint96(x);
}
functionUint128(uint256 x) internalpurereturns (uint128) {
require(x <=type(uint128).max);
returnuint128(x);
}
functionUint192(uint256 x) internalpurereturns (uint192) {
require(x <=type(uint192).max);
returnuint192(x);
}
functionisAApproxB(uint256 a, uint256 b, uint256 eps) internalpurereturns (bool) {
return mulDown(b, ONE - eps) <= a && a <= mulDown(b, ONE + eps);
}
functionisAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internalpurereturns (bool) {
return a >= b && a <= mulDown(b, ONE + eps);
}
functionisASmallerApproxB(uint256 a, uint256 b, uint256 eps) internalpurereturns (bool) {
return a <= b && a >= mulDown(b, ONE - eps);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)pragmasolidity ^0.8.0;import"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import"@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Pendle's ERC20 implementation, modified from @openzeppelin implementation
* Changes are:
* - comes with built-in reentrancy protection, storage-packed with totalSupply variable
* - delete increaseAllowance / decreaseAllowance
* - add nonReentrancy protection to transfer / transferFrom functions
* - allow decimals to be passed in
* - block self-transfer by default
*/// solhint-disablecontractPendleERC20isContext, IERC20, IERC20Metadata{
uint8privateconstant _NOT_ENTERED =1;
uint8privateconstant _ENTERED =2;
mapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256)) private _allowances;
uint248private _totalSupply;
uint8private _status;
stringprivate _name;
stringprivate _symbol;
uint8publicimmutable decimals;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/modifiernonReentrant() {
// On the first call to nonReentrant, _notEntered will be truerequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Sets the values for {name}, {symbol} and {decimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/constructor(stringmemory name_, stringmemory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
decimals = decimals_;
_status = _NOT_ENTERED;
}
/**
* @dev Returns the name of the token.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC20-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/functionbalanceOf(address account) publicviewvirtualoverridereturns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/functiontransfer(address to, uint256 amount) externalvirtualoverridenonReentrantreturns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
returntrue;
}
/**
* @dev See {IERC20-allowance}.
*/functionallowance(address owner, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionapprove(address spender, uint256 amount) externalvirtualoverridereturns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
returntrue;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) externalvirtualoverridenonReentrantreturns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
returntrue;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/function_transfer(addressfrom, address to, uint256 amount) internalvirtual{
require(from!=address(0), "ERC20: transfer from the zero address");
require(to !=address(0), "ERC20: transfer to the zero address");
require(from!= to, "ERC20: transfer to self");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/function_mint(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += toUint248(amount);
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/function_burn(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= toUint248(amount);
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/function_approve(address owner, address spender, uint256 amount) internalvirtual{
require(owner !=address(0), "ERC20: approve from the zero address");
require(spender !=address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/function_spendAllowance(address owner, address spender, uint256 amount) internalvirtual{
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance !=type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom, address to, uint256 amount) internalvirtual{}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_afterTokenTransfer(addressfrom, address to, uint256 amount) internalvirtual{}
functiontoUint248(uint256 x) internalvirtualreturns (uint248) {
require(x <=type(uint248).max); // signed, lim = bit-1returnuint248(x);
}
}
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.0;import"../../interfaces/IPGauge.sol";
import"../../interfaces/IPVeToken.sol";
import"../../interfaces/IPGaugeController.sol";
import"../../interfaces/IStandardizedYield.sol";
import"../RewardManager/RewardManager.sol";
/**
Invariants to maintain:
- before any changes to active balance, updateAndDistributeRewards() must be called
*/abstractcontractPendleGaugeisRewardManager, IPGauge{
usingPMathforuint256;
usingSafeERC20forIERC20;
usingArrayLibforaddress[];
addressprivateimmutable SY;
uint256internalconstant TOKENLESS_PRODUCTION =40;
addressinternalimmutable PENDLE;
IPVeToken internalimmutable vePENDLE;
addressinternalimmutable gaugeController;
uint256public totalActiveSupply;
mapping(address=>uint256) public activeBalance;
constructor(address _SY, address _vePendle, address _gaugeController) {
SY = _SY;
vePENDLE = IPVeToken(_vePendle);
gaugeController = _gaugeController;
PENDLE = IPGaugeController(gaugeController).pendle();
}
/**
* @dev Since rewardShares is based on activeBalance, user's activeBalance must be updated AFTER
rewards is updated
* @dev It's intended to have user's activeBalance updated when rewards is redeemed
*/function_redeemRewards(address user) internalvirtualreturns (uint256[] memory rewardsOut) {
_updateAndDistributeRewards(user);
_updateUserActiveBalance(user);
rewardsOut = _doTransferOutRewards(user, user);
emit RedeemRewards(user, rewardsOut);
}
function_updateUserActiveBalance(address user) internalvirtual{
_updateUserActiveBalanceForTwo(user, address(0));
}
function_updateUserActiveBalanceForTwo(address user1, address user2) internalvirtual{
if (user1 !=address(0) && user1 !=address(this)) _updateUserActiveBalancePrivate(user1);
if (user2 !=address(0) && user2 !=address(this)) _updateUserActiveBalancePrivate(user2);
}
/**
* @dev should only be callable from `_updateUserActiveBalanceForTwo` to guarantee user != address(0) && user != address(this)
*/function_updateUserActiveBalancePrivate(address user) private{
assert(user !=address(0) && user !=address(this));
uint256 lpBalance = _stakedBalance(user);
uint256 veBoostedLpBalance = _calcVeBoostedLpBalance(user, lpBalance);
uint256 newActiveBalance = PMath.min(veBoostedLpBalance, lpBalance);
totalActiveSupply = totalActiveSupply - activeBalance[user] + newActiveBalance;
activeBalance[user] = newActiveBalance;
}
function_calcVeBoostedLpBalance(address user, uint256 lpBalance) internalvirtualreturns (uint256) {
(uint256 vePendleSupply, uint256 vePendleBalance) = vePENDLE.totalSupplyAndBalanceCurrent(user);
// Inspired by Curve's Gaugeuint256 veBoostedLpBalance = (lpBalance * TOKENLESS_PRODUCTION) /100;
if (vePendleSupply >0) {
veBoostedLpBalance +=
(((_totalStaked() * vePendleBalance) / vePendleSupply) * (100- TOKENLESS_PRODUCTION)) /100;
}
return veBoostedLpBalance;
}
function_redeemExternalReward() internalvirtualoverride{
IStandardizedYield(SY).claimRewards(address(this));
IPGaugeController(gaugeController).redeemMarketReward();
}
function_stakedBalance(address user) internalviewvirtualreturns (uint256);
function_totalStaked() internalviewvirtualreturns (uint256);
function_rewardSharesTotal() internalviewvirtualoverridereturns (uint256) {
return totalActiveSupply;
}
function_rewardSharesUser(address user) internalviewvirtualoverridereturns (uint256) {
return activeBalance[user];
}
function_getRewardTokens() internalviewvirtualoverridereturns (address[] memory) {
address[] memory SYRewards = IStandardizedYield(SY).getRewardTokens();
if (SYRewards.contains(PENDLE)) return SYRewards;
return SYRewards.append(PENDLE);
}
function_beforeTokenTransfer(addressfrom, address to, uint256) internalvirtual{
_updateAndDistributeRewardsForTwo(from, to);
}
function_afterTokenTransfer(addressfrom, address to, uint256) internalvirtual{
_updateUserActiveBalanceForTwo(from, to);
}
}
Contract Source Code
File 37 of 48: PendleMarketV3.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.17;import"../../../interfaces/IPMarketV3.sol";
import"../../../interfaces/IPMarketFactoryV3.sol";
import"../../../interfaces/IPMarketSwapCallback.sol";
import"../../erc20/PendleERC20Permit.sol";
import"../PendleGauge.sol";
import"../OracleLib.sol";
/**
Invariance to maintain:
- Internal balances totalPt & totalSy not interfered by people transferring tokens in directly
- address(0) & address(this) should never have any rewards & activeBalance accounting done. This is
guaranteed by address(0) & address(this) check in each updateForTwo function
*/contractPendleMarketV3isPendleERC20Permit, PendleGauge, IPMarketV3{
usingPMathforuint256;
usingPMathforint256;
usingMarketMathCoreforMarketState;
usingSafeERC20forIERC20;
usingPYIndexLibforIPYieldToken;
usingOracleLibforOracleLib.Observation[65535];
structMarketStorage {
int128 totalPt;
int128 totalSy;
// 1 SLOT = 256 bitsuint96 lastLnImpliedRate;
uint16 observationIndex;
uint16 observationCardinality;
uint16 observationCardinalityNext;
// 1 SLOT = 144 bits
}
stringprivateconstant NAME ="Pendle Market";
stringprivateconstant SYMBOL ="PENDLE-LPT";
IPPrincipalToken internalimmutable PT;
IStandardizedYield internalimmutable SY;
IPYieldToken internalimmutable YT;
addresspublicimmutable factory;
uint256publicimmutable expiry;
int256internalimmutable scalarRoot;
int256internalimmutable initialAnchor;
uint80internalimmutable lnFeeRateRoot;
MarketStorage public _storage;
OracleLib.Observation[65535] public observations;
modifiernotExpired() {
if (isExpired()) revert Errors.MarketExpired();
_;
}
constructor(address _PT,
int256 _scalarRoot,
int256 _initialAnchor,
uint80 _lnFeeRateRoot,
address _vePendle,
address _gaugeController
) PendleERC20Permit(NAME, SYMBOL, 18) PendleGauge(IPPrincipalToken(_PT).SY(), _vePendle, _gaugeController) {
PT = IPPrincipalToken(_PT);
SY = IStandardizedYield(PT.SY());
YT = IPYieldToken(PT.YT());
(_storage.observationCardinality, _storage.observationCardinalityNext) = observations.initialize(
uint32(block.timestamp)
);
if (_scalarRoot <=0) revert Errors.MarketScalarRootBelowZero(_scalarRoot);
scalarRoot = _scalarRoot;
initialAnchor = _initialAnchor;
lnFeeRateRoot = _lnFeeRateRoot;
expiry = IPPrincipalToken(_PT).expiry();
factory =msg.sender;
}
/**
* @notice PendleMarket allows users to provide in PT & SY in exchange for LPs, which
* will grant LP holders more exchange fee over time
* @dev will mint as much LP as possible such that the corresponding SY and PT used do
* not exceed `netSyDesired` and `netPtDesired`, respectively
* @dev PT and SY should be transferred to this contract prior to calling
* @dev will revert if PT is expired
*/functionmint(address receiver,
uint256 netSyDesired,
uint256 netPtDesired
) externalnonReentrantnotExpiredreturns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed) {
MarketState memory market = readState(msg.sender);
PYIndex index = YT.newIndex();
uint256 lpToReserve;
(lpToReserve, netLpOut, netSyUsed, netPtUsed) = market.addLiquidity(
netSyDesired,
netPtDesired,
block.timestamp
);
// initializing the marketif (lpToReserve !=0) {
market.setInitialLnImpliedRate(index, initialAnchor, block.timestamp);
_mint(address(1), lpToReserve);
}
_mint(receiver, netLpOut);
_writeState(market);
if (_selfBalance(SY) < market.totalSy.Uint())
revert Errors.MarketInsufficientSyReceived(_selfBalance(SY), market.totalSy.Uint());
if (_selfBalance(PT) < market.totalPt.Uint())
revert Errors.MarketInsufficientPtReceived(_selfBalance(PT), market.totalPt.Uint());
emit Mint(receiver, netLpOut, netSyUsed, netPtUsed);
}
/**
* @notice LP Holders can burn their LP to receive back SY & PT proportionally
* to their share of the market
*/functionburn(address receiverSy,
address receiverPt,
uint256 netLpToBurn
) externalnonReentrantreturns (uint256 netSyOut, uint256 netPtOut) {
MarketState memory market = readState(msg.sender);
_burn(address(this), netLpToBurn);
(netSyOut, netPtOut) = market.removeLiquidity(netLpToBurn);
if (receiverSy !=address(this)) IERC20(SY).safeTransfer(receiverSy, netSyOut);
if (receiverPt !=address(this)) IERC20(PT).safeTransfer(receiverPt, netPtOut);
_writeState(market);
emit Burn(receiverSy, receiverPt, netLpToBurn, netSyOut, netPtOut);
}
/**
* @notice Pendle Market allows swaps between PT & SY it is holding. This function
* aims to swap an exact amount of PT to SY.
* @dev steps working of this contract
- The outcome amount of SY will be precomputed by MarketMathLib
- Release the calculated amount of SY to receiver
- Callback to msg.sender if data.length > 0
- Ensure exactPtIn amount of PT has been transferred to this address
* @dev will revert if PT is expired
* @param data bytes data to be sent in the callback (if any)
*/functionswapExactPtForSy(address receiver,
uint256 exactPtIn,
bytescalldata data
) externalnonReentrantnotExpiredreturns (uint256 netSyOut, uint256 netSyFee) {
MarketState memory market = readState(msg.sender);
uint256 netSyToReserve;
(netSyOut, netSyFee, netSyToReserve) = market.swapExactPtForSy(YT.newIndex(), exactPtIn, block.timestamp);
if (receiver !=address(this)) IERC20(SY).safeTransfer(receiver, netSyOut);
IERC20(SY).safeTransfer(market.treasury, netSyToReserve);
_writeState(market);
if (data.length>0) {
IPMarketSwapCallback(msg.sender).swapCallback(exactPtIn.neg(), netSyOut.Int(), data);
}
if (_selfBalance(PT) < market.totalPt.Uint())
revert Errors.MarketInsufficientPtReceived(_selfBalance(PT), market.totalPt.Uint());
emit Swap(msg.sender, receiver, exactPtIn.neg(), netSyOut.Int(), netSyFee, netSyToReserve);
}
/**
* @notice Pendle Market allows swaps between PT & SY it is holding. This function
* aims to swap SY for an exact amount of PT.
* @dev steps working of this function
- The exact outcome amount of PT will be transferred to receiver
- Callback to msg.sender if data.length > 0
- Ensure the calculated required amount of SY is transferred to this address
* @dev will revert if PT is expired
* @param data bytes data to be sent in the callback (if any)
*/functionswapSyForExactPt(address receiver,
uint256 exactPtOut,
bytescalldata data
) externalnonReentrantnotExpiredreturns (uint256 netSyIn, uint256 netSyFee) {
MarketState memory market = readState(msg.sender);
uint256 netSyToReserve;
(netSyIn, netSyFee, netSyToReserve) = market.swapSyForExactPt(YT.newIndex(), exactPtOut, block.timestamp);
if (receiver !=address(this)) IERC20(PT).safeTransfer(receiver, exactPtOut);
IERC20(SY).safeTransfer(market.treasury, netSyToReserve);
_writeState(market);
if (data.length>0) {
IPMarketSwapCallback(msg.sender).swapCallback(exactPtOut.Int(), netSyIn.neg(), data);
}
// have received enough SYif (_selfBalance(SY) < market.totalSy.Uint())
revert Errors.MarketInsufficientSyReceived(_selfBalance(SY), market.totalSy.Uint());
emit Swap(msg.sender, receiver, exactPtOut.Int(), netSyIn.neg(), netSyFee, netSyToReserve);
}
/// @notice forces balances to match reservesfunctionskim() externalnonReentrant{
MarketState memory market = readState(msg.sender);
uint256 excessPt = _selfBalance(PT) - market.totalPt.Uint();
uint256 excessSy = _selfBalance(SY) - market.totalSy.Uint();
if (excessPt !=0) IERC20(PT).safeTransfer(market.treasury, excessPt);
if (excessSy !=0) IERC20(SY).safeTransfer(market.treasury, excessSy);
}
/**
* @notice redeems the user's reward
* @return amount of reward token redeemed, in the same order as `getRewardTokens()`
*/functionredeemRewards(address user) externalnonReentrantreturns (uint256[] memory) {
return _redeemRewards(user);
}
/// @notice returns the list of reward tokensfunctiongetRewardTokens() externalviewreturns (address[] memory) {
return _getRewardTokens();
}
/*///////////////////////////////////////////////////////////////
ORACLE
//////////////////////////////////////////////////////////////*/functionobserve(uint32[] memory secondsAgos) externalviewreturns (uint216[] memory lnImpliedRateCumulative) {
return
observations.observe(
uint32(block.timestamp),
secondsAgos,
_storage.lastLnImpliedRate,
_storage.observationIndex,
_storage.observationCardinality
);
}
functionincreaseObservationsCardinalityNext(uint16 cardinalityNext) externalnonReentrant{
uint16 cardinalityNextOld = _storage.observationCardinalityNext;
uint16 cardinalityNextNew = observations.grow(cardinalityNextOld, cardinalityNext);
if (cardinalityNextOld != cardinalityNextNew) {
_storage.observationCardinalityNext = cardinalityNextNew;
emit IncreaseObservationCardinalityNext(cardinalityNextOld, cardinalityNextNew);
}
}
/*///////////////////////////////////////////////////////////////
READ/WRITE STATES
//////////////////////////////////////////////////////////////*//**
* @notice read the state of the market from storage into memory for gas-efficient manipulation
*/functionreadState(address router) publicviewreturns (MarketState memory market) {
market.totalPt = _storage.totalPt;
market.totalSy = _storage.totalSy;
market.totalLp = totalSupply().Int();
uint80 overriddenFee;
(market.treasury, overriddenFee, market.reserveFeePercent) = IPMarketFactoryV3(factory).getMarketConfig(
address(this),
router
);
market.lnFeeRateRoot = overriddenFee ==0 ? lnFeeRateRoot : overriddenFee;
market.scalarRoot = scalarRoot;
market.expiry = expiry;
market.lastLnImpliedRate = _storage.lastLnImpliedRate;
}
/// @notice write back the state of the market from memory to storagefunction_writeState(MarketState memory market) internal{
uint96 lastLnImpliedRate96 = market.lastLnImpliedRate.Uint96();
int128 totalPt128 = market.totalPt.Int128();
int128 totalSy128 = market.totalSy.Int128();
(uint16 observationIndex, uint16 observationCardinality) = observations.write(
_storage.observationIndex,
uint32(block.timestamp),
_storage.lastLnImpliedRate,
_storage.observationCardinality,
_storage.observationCardinalityNext
);
_storage.totalPt = totalPt128;
_storage.totalSy = totalSy128;
_storage.lastLnImpliedRate = lastLnImpliedRate96;
_storage.observationIndex = observationIndex;
_storage.observationCardinality = observationCardinality;
emit UpdateImpliedRate(block.timestamp, market.lastLnImpliedRate);
}
functiongetNonOverrideLnFeeRateRoot() externalviewreturns (uint80) {
return lnFeeRateRoot;
}
/*///////////////////////////////////////////////////////////////
TRIVIAL FUNCTIONS
//////////////////////////////////////////////////////////////*/functionreadTokens() externalviewreturns (IStandardizedYield _SY, IPPrincipalToken _PT, IPYieldToken _YT) {
_SY = SY;
_PT = PT;
_YT = YT;
}
functionisExpired() publicviewreturns (bool) {
return MiniHelpers.isCurrentlyExpired(expiry);
}
/*///////////////////////////////////////////////////////////////
PENDLE GAUGE - RELATED
//////////////////////////////////////////////////////////////*/function_stakedBalance(address user) internalviewoverridereturns (uint256) {
return balanceOf(user);
}
function_totalStaked() internalviewoverridereturns (uint256) {
return totalSupply();
}
// solhint-disable-next-line orderingfunction_beforeTokenTransfer(addressfrom,
address to,
uint256 amount
) internaloverride(PendleERC20, PendleGauge) {
PendleGauge._beforeTokenTransfer(from, to, amount);
}
// solhint-disable-next-line orderingfunction_afterTokenTransfer(addressfrom, address to, uint256 amount) internaloverride(PendleERC20, PendleGauge) {
PendleGauge._afterTokenTransfer(from, to, amount);
}
}
Contract Source Code
File 38 of 48: RewardManager.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.0;import"./RewardManagerAbstract.sol";
/// NOTE: This RewardManager is used with SY & YTv2 & PendleMarket. For YTv1, it will use RewardManagerAbstract/// NOTE: RewardManager must not have duplicated rewardTokensabstractcontractRewardManagerisRewardManagerAbstract{
usingPMathforuint256;
usingArrayLibforuint256[];
uint256public lastRewardBlock;
mapping(address=> RewardState) public rewardState;
function_updateRewardIndex()
internalvirtualoverridereturns (address[] memory tokens, uint256[] memory indexes)
{
tokens = _getRewardTokens();
indexes =newuint256[](tokens.length);
if (tokens.length==0) return (tokens, indexes);
if (lastRewardBlock !=block.number) {
// if we have not yet update the index for this block
lastRewardBlock =block.number;
uint256 totalShares = _rewardSharesTotal();
_redeemExternalReward();
for (uint256 i =0; i < tokens.length; ++i) {
address token = tokens[i];
// the entire token balance of the contract must be the rewards of the contract
RewardState memory _state = rewardState[token];
(uint256 lastBalance, uint256 index) = (_state.lastBalance, _state.index);
uint256 accrued = _selfBalance(tokens[i]) - lastBalance;
if (index ==0) index = INITIAL_REWARD_INDEX;
if (totalShares !=0) index += accrued.divDown(totalShares);
rewardState[token] = RewardState({
index: index.Uint128(),
lastBalance: (lastBalance + accrued).Uint128()
});
indexes[i] = index;
}
} else {
for (uint256 i =0; i < tokens.length; i++) {
indexes[i] = rewardState[tokens[i]].index;
}
}
}
/// @dev this function doesn't need redeemExternal since redeemExternal is bundled in updateRewardIndex/// @dev this function also has to update rewardState.lastBalancefunction_doTransferOutRewards(address user,
address receiver
) internalvirtualoverridereturns (uint256[] memory rewardAmounts) {
address[] memory tokens = _getRewardTokens();
rewardAmounts =newuint256[](tokens.length);
for (uint256 i =0; i < tokens.length; i++) {
rewardAmounts[i] = userReward[tokens[i]][user].accrued;
if (rewardAmounts[i] !=0) {
userReward[tokens[i]][user].accrued =0;
rewardState[tokens[i]].lastBalance -= rewardAmounts[i].Uint128();
_transferOut(tokens[i], receiver, rewardAmounts[i]);
}
}
}
function_getRewardTokens() internalviewvirtualreturns (address[] memory);
function_rewardSharesTotal() internalviewvirtualreturns (uint256);
}
Contract Source Code
File 39 of 48: RewardManagerAbstract.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.0;import"../../interfaces/IRewardManager.sol";
import"../libraries/ArrayLib.sol";
import"../libraries/TokenHelper.sol";
import"../libraries/math/PMath.sol";
import"./RewardManagerAbstract.sol";
/// NOTE: RewardManager must not have duplicated rewardTokensabstractcontractRewardManagerAbstractisIRewardManager, TokenHelper{
usingPMathforuint256;
uint256internalconstant INITIAL_REWARD_INDEX =1;
structRewardState {
uint128 index;
uint128 lastBalance;
}
structUserReward {
uint128 index;
uint128 accrued;
}
// [token] => [user] => (index,accrued)mapping(address=>mapping(address=> UserReward)) public userReward;
function_updateAndDistributeRewards(address user) internalvirtual{
_updateAndDistributeRewardsForTwo(user, address(0));
}
function_updateAndDistributeRewardsForTwo(address user1, address user2) internalvirtual{
(address[] memory tokens, uint256[] memory indexes) = _updateRewardIndex();
if (tokens.length==0) return;
if (user1 !=address(0) && user1 !=address(this)) _distributeRewardsPrivate(user1, tokens, indexes);
if (user2 !=address(0) && user2 !=address(this)) _distributeRewardsPrivate(user2, tokens, indexes);
}
// should only be callable from `_updateAndDistributeRewardsForTwo` to guarantee user != address(0) && user != address(this)function_distributeRewardsPrivate(address user, address[] memory tokens, uint256[] memory indexes) private{
assert(user !=address(0) && user !=address(this));
uint256 userShares = _rewardSharesUser(user);
for (uint256 i =0; i < tokens.length; ++i) {
address token = tokens[i];
uint256 index = indexes[i];
uint256 userIndex = userReward[token][user].index;
if (userIndex ==0) {
userIndex = INITIAL_REWARD_INDEX.Uint128();
}
if (userIndex == index) continue;
uint256 deltaIndex = index - userIndex;
uint256 rewardDelta = userShares.mulDown(deltaIndex);
uint256 rewardAccrued = userReward[token][user].accrued + rewardDelta;
userReward[token][user] = UserReward({index: index.Uint128(), accrued: rewardAccrued.Uint128()});
}
}
function_updateRewardIndex() internalvirtualreturns (address[] memory tokens, uint256[] memory indexes);
function_redeemExternalReward() internalvirtual;
function_doTransferOutRewards(address user,
address receiver
) internalvirtualreturns (uint256[] memory rewardAmounts);
function_rewardSharesUser(address user) internalviewvirtualreturns (uint256);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
import"../extensions/IERC20Permit.sol";
import"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/functionsafeApprove(IERC20 token, address spender, uint256 value) internal{
// safeApprove should only be called when setting an initial allowance,// or when resetting it to zero. To increase and decrease it, use// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'require(
(value ==0) || (token.allowance(address(this), spender) ==0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/functionsafePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal{
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore +1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory data) private{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that// the target address contains contract code and also asserts for success in the low-level call.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length==0||abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false// and not revert is the subcall reverts.
(bool success, bytesmemory returndata) =address(token).call(data);
return
success && (returndata.length==0||abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
Contract Source Code
File 42 of 48: ShortStrings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)pragmasolidity ^0.8.8;import"./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |// | length | 0x BB |type ShortString isbytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/libraryShortStrings{
// Used as an identifier for strings longer than 31 bytes.bytes32privateconstant _FALLBACK_SENTINEL =0x00000000000000000000000000000000000000000000000000000000000000FF;
errorStringTooLong(string str);
errorInvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/functiontoShortString(stringmemory str) internalpurereturns (ShortString) {
bytesmemory bstr =bytes(str);
if (bstr.length>31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/functiontoString(ShortString sstr) internalpurereturns (stringmemory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.stringmemory str =newstring(32);
/// @solidity memory-safe-assemblyassembly {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/functionbyteLength(ShortString sstr) internalpurereturns (uint256) {
uint256 result =uint256(ShortString.unwrap(sstr)) &0xFF;
if (result >31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/functiontoShortStringWithFallback(stringmemory value, stringstorage store) internalreturns (ShortString) {
if (bytes(value).length<32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value= value;
return ShortString.wrap(_FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/functiontoStringWithFallback(ShortString value, stringstorage store) internalpurereturns (stringmemory) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/functionbyteLengthWithFallback(ShortString value, stringstorage store) internalviewreturns (uint256) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return byteLength(value);
} else {
returnbytes(store).length;
}
}
}
Contract Source Code
File 43 of 48: SignedMath.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)pragmasolidity ^0.8.0;/**
* @dev Standard signed math utilities missing in the Solidity language.
*/librarySignedMath{
/**
* @dev Returns the largest of two signed numbers.
*/functionmax(int256 a, int256 b) internalpurereturns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/functionmin(int256 a, int256 b) internalpurereturns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/functionaverage(int256 a, int256 b) internalpurereturns (int256) {
// Formula from the book "Hacker's Delight"int256 x = (a & b) + ((a ^ b) >>1);
return x + (int256(uint256(x) >>255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/functionabs(int256 n) internalpurereturns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`returnuint256(n >=0 ? n : -n);
}
}
}
Contract Source Code
File 44 of 48: StorageSlot.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.pragmasolidity ^0.8.0;/**
* @dev 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:
* ```solidity
* 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`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/libraryStorageSlot{
structAddressSlot {
address value;
}
structBooleanSlot {
bool value;
}
structBytes32Slot {
bytes32 value;
}
structUint256Slot {
uint256 value;
}
structStringSlot {
string value;
}
structBytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/functiongetAddressSlot(bytes32 slot) internalpurereturns (AddressSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/functiongetBooleanSlot(bytes32 slot) internalpurereturns (BooleanSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/functiongetBytes32Slot(bytes32 slot) internalpurereturns (Bytes32Slot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/functiongetUint256Slot(bytes32 slot) internalpurereturns (Uint256Slot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/functiongetStringSlot(bytes32 slot) internalpurereturns (StringSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/functiongetStringSlot(stringstorage store) internalpurereturns (StringSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/functiongetBytesSlot(bytes32 slot) internalpurereturns (BytesSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/functiongetBytesSlot(bytesstorage store) internalpurereturns (BytesSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= store.slot
}
}
}
Contract Source Code
File 45 of 48: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)pragmasolidity ^0.8.0;import"./math/Math.sol";
import"./math/SignedMath.sol";
/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _SYMBOLS ="0123456789abcdef";
uint8privateconstant _ADDRESS_LENGTH =20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
uint256 length = Math.log10(value) +1;
stringmemory buffer =newstring(length);
uint256 ptr;
/// @solidity memory-safe-assemblyassembly {
ptr :=add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assemblyassembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /=10;
if (value ==0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/functiontoString(int256 value) internalpurereturns (stringmemory) {
returnstring(abi.encodePacked(value <0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
return toHexString(value, Math.log256(value) +1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/functiontoHexString(address addr) internalpurereturns (stringmemory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/functionequal(stringmemory a, stringmemory b) internalpurereturns (bool) {
returnkeccak256(bytes(a)) ==keccak256(bytes(b));
}
}
Contract Source Code
File 46 of 48: TokenHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.0;import"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import"../../interfaces/IWETH.sol";
abstractcontractTokenHelper{
usingSafeERC20forIERC20;
addressinternalconstant NATIVE =address(0);
uint256internalconstant LOWER_BOUND_APPROVAL =type(uint96).max/2; // some tokens use 96 bits for approvalfunction_transferIn(address token, addressfrom, uint256 amount) internal{
if (token == NATIVE) require(msg.value== amount, "eth mismatch");
elseif (amount !=0) IERC20(token).safeTransferFrom(from, address(this), amount);
}
function_transferFrom(IERC20 token, addressfrom, address to, uint256 amount) internal{
if (amount !=0) token.safeTransferFrom(from, to, amount);
}
function_transferOut(address token, address to, uint256 amount) internal{
if (amount ==0) return;
if (token == NATIVE) {
(bool success, ) = to.call{value: amount}("");
require(success, "eth send failed");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
function_transferOut(address[] memory tokens, address to, uint256[] memory amounts) internal{
uint256 numTokens = tokens.length;
require(numTokens == amounts.length, "length mismatch");
for (uint256 i =0; i < numTokens; ) {
_transferOut(tokens[i], to, amounts[i]);
unchecked {
i++;
}
}
}
function_selfBalance(address token) internalviewreturns (uint256) {
return (token == NATIVE) ? address(this).balance : IERC20(token).balanceOf(address(this));
}
function_selfBalance(IERC20 token) internalviewreturns (uint256) {
return token.balanceOf(address(this));
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token/// @dev PLS PAY ATTENTION to tokens that requires the approval to be set to 0 before changing itfunction_safeApprove(address token, address to, uint256 value) internal{
(bool success, bytesmemory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), "Safe Approve");
}
function_safeApproveInf(address token, address to) internal{
if (token == NATIVE) return;
if (IERC20(token).allowance(address(this), to) < LOWER_BOUND_APPROVAL) {
_safeApprove(token, to, 0);
_safeApprove(token, to, type(uint256).max);
}
}
function_wrap_unwrap_ETH(address tokenIn, address tokenOut, uint256 netTokenIn) internal{
if (tokenIn == NATIVE) IWETH(tokenOut).deposit{value: netTokenIn}();
else IWETH(tokenIn).withdraw(netTokenIn);
}
}
Contract Source Code
File 47 of 48: draft-EIP712.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/draft-EIP712.sol)pragmasolidity ^0.8.0;// EIP-712 is Final as of 2022-08-11. This file is deprecated.import"./EIP712.sol";
Contract Source Code
File 48 of 48: draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/draft-ERC20Permit.sol)pragmasolidity ^0.8.0;// EIP-2612 is Final as of 2022-11-01. This file is deprecated.import"./ERC20Permit.sol";