// 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 23: 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;
}
functionappendHead(address[] memory inp, address element) internalpurereturns (address[] memory out) {
uint256 length = inp.length;
out =newaddress[](length +1);
out[0] = element;
for (uint256 i =1; i <= length; ) {
out[i] = inp[i -1];
unchecked {
i++;
}
}
}
/**
* @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(address a, address b, address c) internalpurereturns (address[] memory res) {
res =newaddress[](3);
res[0] = a;
res[1] = b;
res[2] = c;
}
functioncreate(address a, address b, address c, address d) internalpurereturns (address[] memory res) {
res =newaddress[](4);
res[0] = a;
res[1] = b;
res[2] = c;
res[3] = d;
}
functioncreate(address a,
address b,
address c,
address d,
address e
) internalpurereturns (address[] memory res) {
res =newaddress[](5);
res[0] = a;
res[1] = b;
res[2] = c;
res[3] = d;
res[4] = e;
}
functioncreate(uint256 a) internalpurereturns (uint256[] memory res) {
res =newuint256[](1);
res[0] = a;
}
}
Contract Source Code
File 3 of 23: 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;
}
}
// 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 6 of 23: 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 7 of 23: 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);
}
// 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;interfaceIPYieldContractFactory{
eventCreateYieldContract(addressindexed SY, uint256indexed expiry, address PT, address YT);
eventSetExpiryDivisor(uint256 newExpiryDivisor);
eventSetInterestFeeRate(uint256 newInterestFeeRate);
eventSetRewardFeeRate(uint256 newRewardFeeRate);
eventSetTreasury(addressindexed treasury);
functiongetPT(address SY, uint256 expiry) externalviewreturns (address);
functiongetYT(address SY, uint256 expiry) externalviewreturns (address);
functionexpiryDivisor() externalviewreturns (uint96);
functioninterestFeeRate() externalviewreturns (uint128);
functionrewardFeeRate() externalviewreturns (uint128);
functiontreasury() externalviewreturns (address);
functionisPT(address) externalviewreturns (bool);
functionisYT(address) externalviewreturns (bool);
functioncreateYieldContract(address SY,
uint32 expiry,
bool doCacheIndexSameBlock
) externalreturns (address PT, address YT);
}
// 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 14 of 23: 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 15 of 23: InterestManagerYT.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.17;import"../../interfaces/IPYieldToken.sol";
import"../../interfaces/IPPrincipalToken.sol";
import"../../interfaces/IPInterestManagerYT.sol";
import"../../interfaces/IPYieldContractFactory.sol";
import"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import"../libraries/math/PMath.sol";
import"../libraries/TokenHelper.sol";
import"../StandardizedYield/SYUtils.sol";
/*
With YT yielding more SYs overtime, which is allowed to be redeemed by users, the reward distribution should
be based on the amount of SYs that their YT currently represent, plus with their dueInterest.
It has been proven and tested that totalSyRedeemable will not change over time, unless users redeem their interest or redeemPY.
Due to this, it is required to update users' accruedReward STRICTLY BEFORE redeeming their interest.
*/abstractcontractInterestManagerYTisTokenHelper, IPInterestManagerYT{
usingPMathforuint256;
structUserInterest {
uint128 index;
uint128 accrued;
}
mapping(address=> UserInterest) public userInterest;
function_distributeInterest(address user) internal{
_distributeInterestForTwo(user, address(0));
}
function_distributeInterestForTwo(address user1, address user2) internal{
uint256 index = _getInterestIndex();
if (user1 !=address(0) && user1 !=address(this)) _distributeInterestPrivate(user1, index);
if (user2 !=address(0) && user2 !=address(this)) _distributeInterestPrivate(user2, index);
}
function_doTransferOutInterest(address user,
address SY,
address factory
) internalreturns (uint256 interestAmount) {
address treasury = IPYieldContractFactory(factory).treasury();
uint256 feeRate = IPYieldContractFactory(factory).interestFeeRate();
uint256 interestPreFee = userInterest[user].accrued;
userInterest[user].accrued =0;
uint256 feeAmount = interestPreFee.mulDown(feeRate);
interestAmount = interestPreFee - feeAmount;
_transferOut(SY, treasury, feeAmount);
_transferOut(SY, user, interestAmount);
emit CollectInterestFee(feeAmount);
}
// should only be callable from `_distributeInterestForTwo` & make sure user != address(0) && user != address(this)function_distributeInterestPrivate(address user, uint256 currentIndex) private{
assert(user !=address(0) && user !=address(this));
uint256 prevIndex = userInterest[user].index;
if (prevIndex == currentIndex) return;
if (prevIndex ==0) {
userInterest[user].index = currentIndex.Uint128();
return;
}
uint256 principal = _YTbalance(user);
uint256 interestFromYT = (principal * (currentIndex - prevIndex)).divDown(prevIndex * currentIndex);
userInterest[user].accrued += interestFromYT.Uint128();
userInterest[user].index = currentIndex.Uint128();
}
function_getInterestIndex() internalvirtualreturns (uint256 index);
function_YTbalance(address user) internalviewvirtualreturns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later// This program is free software: you can redistribute it and/or modify// it under the terms of the GNU General Public License as published by// the Free Software Foundation, either version 3 of the License, or// (at your option) any later version.// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU General Public License for more details.// You should have received a copy of the GNU General Public License// along with this program. If not, see <http://www.gnu.org/licenses/>.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;
}
functionrawDivUp(int256 a, int256 b) internalpurereturns (int256) {
return (a + b -1) / b;
}
functionslipUp(uint256 a, uint256 factor) internalpurereturns (uint256) {
return mulDown(a, ONE + factor);
}
functionslipDown(uint256 a, uint256 factor) internalpurereturns (uint256) {
return mulDown(a, ONE - factor);
}
// @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);
}
}
Contract Source Code
File 18 of 23: PendleERC20.sol
// 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);
}
}
Contract Source Code
File 19 of 23: PendleYieldToken.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.17;import"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import"../../interfaces/IStandardizedYield.sol";
import"../../interfaces/IPYieldToken.sol";
import"../../interfaces/IPPrincipalToken.sol";
import"../libraries/math/PMath.sol";
import"../libraries/ArrayLib.sol";
import"../../interfaces/IPYieldContractFactory.sol";
import"../StandardizedYield/SYUtils.sol";
import"../libraries/Errors.sol";
import"../libraries/MiniHelpers.sol";
import"../RewardManager/RewardManagerAbstract.sol";
import"../erc20/PendleERC20.sol";
import"./InterestManagerYT.sol";
/**
Invariance to maintain:
- 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
*/contractPendleYieldTokenisIPYieldToken, PendleERC20, RewardManagerAbstract, InterestManagerYT{
usingPMathforuint256;
usingSafeERC20forIERC20;
usingArrayLibforuint256[];
structPostExpiryData {
uint128 firstPYIndex;
uint128 totalSyInterestForTreasury;
mapping(address=>uint256) firstRewardIndex;
mapping(address=>uint256) userRewardOwed;
}
addresspublicimmutable SY;
addresspublicimmutable PT;
addresspublicimmutable factory;
uint256publicimmutable expiry;
boolpublicimmutable doCacheIndexSameBlock;
uint256public syReserve;
uint128public pyIndexLastUpdatedBlock;
uint128internal _pyIndexStored;
PostExpiryData public postExpiry;
modifierupdateData() {
if (isExpired()) _setPostExpiryData();
_;
_updateSyReserve();
}
modifiernotExpired() {
if (isExpired()) revert Errors.YCExpired();
_;
}
/**
* @param _doCacheIndexSameBlock if true, the PY index is cached for each block, and thus is
* constant for all txs within the same block. Otherwise, the PY index is recalculated for
* every tx.
*/constructor(address _SY,
address _PT,
stringmemory _name,
stringmemory _symbol,
uint8 __decimals,
uint256 _expiry,
bool _doCacheIndexSameBlock
) PendleERC20(_name, _symbol, __decimals) {
SY = _SY;
PT = _PT;
expiry = _expiry;
factory =msg.sender;
doCacheIndexSameBlock = _doCacheIndexSameBlock;
}
/**
* @notice Tokenize SY into PT + YT of equal qty. Every unit of asset of SY will create 1 PT + 1 YT
* @dev SY must be transferred to this contract prior to calling
*/functionmintPY(address receiverPT,
address receiverYT
) externalnonReentrantnotExpiredupdateDatareturns (uint256 amountPYOut) {
address[] memory receiverPTs =newaddress[](1);
address[] memory receiverYTs =newaddress[](1);
uint256[] memory amountSyToMints =newuint256[](1);
(receiverPTs[0], receiverYTs[0], amountSyToMints[0]) = (receiverPT, receiverYT, _getFloatingSyAmount());
uint256[] memory amountPYOuts = _mintPY(receiverPTs, receiverYTs, amountSyToMints);
amountPYOut = amountPYOuts[0];
}
/// @notice Tokenize SY into PT + YT for multiple receivers. See `mintPY()` for more detailsfunctionmintPYMulti(address[] calldata receiverPTs,
address[] calldata receiverYTs,
uint256[] calldata amountSyToMints
) externalnonReentrantnotExpiredupdateDatareturns (uint256[] memory amountPYOuts) {
uint256 length = receiverPTs.length;
if (length ==0) revert Errors.ArrayEmpty();
if (receiverYTs.length!= length || amountSyToMints.length!= length) revert Errors.ArrayLengthMismatch();
uint256 totalSyToMint = amountSyToMints.sum();
if (totalSyToMint > _getFloatingSyAmount())
revert Errors.YieldContractInsufficientSy(totalSyToMint, _getFloatingSyAmount());
amountPYOuts = _mintPY(receiverPTs, receiverYTs, amountSyToMints);
}
/**
* @notice converts PT(+YT) tokens into SY, but interests & rewards are not redeemed at the
* same time
* @dev PT/YT must be transferred to this contract prior to calling
*/functionredeemPY(address receiver) externalnonReentrantupdateDatareturns (uint256 amountSyOut) {
address[] memory receivers =newaddress[](1);
uint256[] memory amounts =newuint256[](1);
(receivers[0], amounts[0]) = (receiver, _getAmountPYToRedeem());
uint256[] memory amountSyOuts;
amountSyOuts = _redeemPY(receivers, amounts);
amountSyOut = amountSyOuts[0];
}
/**
* @notice redeems PT(+YT) for multiple users. See `redeemPY()`
* @dev PT/YT must be transferred to this contract prior to calling
* @dev fails if unable to redeem the total PY amount in `amountPYToRedeems`
*/functionredeemPYMulti(address[] calldata receivers,
uint256[] calldata amountPYToRedeems
) externalnonReentrantupdateDatareturns (uint256[] memory amountSyOuts) {
if (receivers.length!= amountPYToRedeems.length) revert Errors.ArrayLengthMismatch();
if (receivers.length==0) revert Errors.ArrayEmpty();
amountSyOuts = _redeemPY(receivers, amountPYToRedeems);
}
/**
* @notice Redeems interests and rewards for `user`
* @param redeemInterest will only transfer out interest for user if true
* @param redeemRewards will only transfer out rewards for user if true
* @dev With YT yielding interest in the form of SY, which is redeemable by users, the reward
* distribution should be based on the amount of SYs that their YT currently represent, plus
* their dueInterest. It has been proven and tested that _rewardSharesUser will not change over
* time, unless users redeem their dueInterest or redeemPY. Due to this, it is required to
* update users' accruedReward STRICTLY BEFORE transferring out their interest.
*/functionredeemDueInterestAndRewards(address user,
bool redeemInterest,
bool redeemRewards
) externalnonReentrantupdateDatareturns (uint256 interestOut, uint256[] memory rewardsOut) {
if (!redeemInterest &&!redeemRewards) revert Errors.YCNothingToRedeem();
// if redeemRewards == true, this line must be here for obvious reason// if redeemInterest == true, this line must be here because of the reason above
_updateAndDistributeRewards(user);
if (redeemRewards) {
rewardsOut = _doTransferOutRewards(user, user);
emit RedeemRewards(user, rewardsOut);
} else {
address[] memory tokens = getRewardTokens();
rewardsOut =newuint256[](tokens.length);
}
if (redeemInterest) {
_distributeInterest(user);
interestOut = _doTransferOutInterest(user, SY, factory);
emit RedeemInterest(user, interestOut);
} else {
interestOut =0;
}
}
/**
* @dev All rewards and interests accrued post-expiry goes to the treasury.
* Reverts if called pre-expiry.
*/functionredeemInterestAndRewardsPostExpiryForTreasury()
externalnonReentrantupdateDatareturns (uint256 interestOut, uint256[] memory rewardsOut)
{
if (!isExpired()) revert Errors.YCNotExpired();
address treasury = IPYieldContractFactory(factory).treasury();
address[] memory tokens = getRewardTokens();
rewardsOut =newuint256[](tokens.length);
_redeemExternalReward();
for (uint256 i =0; i < tokens.length; i++) {
rewardsOut[i] = _selfBalance(tokens[i]) - postExpiry.userRewardOwed[tokens[i]];
emit CollectRewardFee(tokens[i], rewardsOut[i]);
}
_transferOut(tokens, treasury, rewardsOut);
interestOut = postExpiry.totalSyInterestForTreasury;
postExpiry.totalSyInterestForTreasury =0;
_transferOut(SY, treasury, interestOut);
emit CollectInterestFee(interestOut);
}
/// @notice updates and returns the reward indexesfunctionrewardIndexesCurrent() externaloverridenonReentrantreturns (uint256[] memory) {
return IStandardizedYield(SY).rewardIndexesCurrent();
}
/**
* @notice updates and returns the current PY index
* @dev this function maximizes the current PY index with the previous index, guaranteeing
* non-decreasing PY index
* @dev if `doCacheIndexSameBlock` is true, PY index only updates at most once per block,
* and has no state changes on the second call onwards (within the same block).
* @dev see `pyIndexStored()` for view function for cached value.
*/functionpyIndexCurrent() publicnonReentrantreturns (uint256 currentIndex) {
currentIndex = _pyIndexCurrent();
}
/// @notice returns the last-updated PY indexfunctionpyIndexStored() publicviewreturns (uint256) {
return _pyIndexStored;
}
/**
* @notice do a final rewards redeeming, and sets post-expiry data
* @dev has no effect if called pre-expiry
*/functionsetPostExpiryData() externalnonReentrant{
if (isExpired()) {
_setPostExpiryData();
}
}
/**
* @notice returns the current data post-expiry, if exists
* @dev reverts if post-expiry data not set (see `setPostExpiryData()`)
* @return firstPYIndex the earliest PY index post-expiry
* @return totalSyInterestForTreasury current amount of SY interests post-expiry for treasury
* @return firstRewardIndexes the earliest reward indices post-expiry, for each reward token
* @return userRewardOwed amount of unclaimed user rewards, for each reward token
*/functiongetPostExpiryData()
externalviewreturns (uint256 firstPYIndex,
uint256 totalSyInterestForTreasury,
uint256[] memory firstRewardIndexes,
uint256[] memory userRewardOwed
)
{
if (postExpiry.firstPYIndex ==0) revert Errors.YCPostExpiryDataNotSet();
firstPYIndex = postExpiry.firstPYIndex;
totalSyInterestForTreasury = postExpiry.totalSyInterestForTreasury;
address[] memory tokens = getRewardTokens();
firstRewardIndexes =newuint256[](tokens.length);
userRewardOwed =newuint256[](tokens.length);
for (uint256 i =0; i < tokens.length; ++i) {
firstRewardIndexes[i] = postExpiry.firstRewardIndex[tokens[i]];
userRewardOwed[i] = postExpiry.userRewardOwed[tokens[i]];
}
}
function_mintPY(address[] memory receiverPTs,
address[] memory receiverYTs,
uint256[] memory amountSyToMints
) internalreturns (uint256[] memory amountPYOuts) {
amountPYOuts =newuint256[](amountSyToMints.length);
uint256 index = _pyIndexCurrent();
for (uint256 i =0; i < amountSyToMints.length; i++) {
amountPYOuts[i] = _calcPYToMint(amountSyToMints[i], index);
_mint(receiverYTs[i], amountPYOuts[i]);
IPPrincipalToken(PT).mintByYT(receiverPTs[i], amountPYOuts[i]);
emit Mint(msg.sender, receiverPTs[i], receiverYTs[i], amountSyToMints[i], amountPYOuts[i]);
}
}
functionisExpired() publicviewreturns (bool) {
return MiniHelpers.isCurrentlyExpired(expiry);
}
function_redeemPY(address[] memory receivers,
uint256[] memory amountPYToRedeems
) internalreturns (uint256[] memory amountSyOuts) {
uint256 totalAmountPYToRedeem = amountPYToRedeems.sum();
IPPrincipalToken(PT).burnByYT(address(this), totalAmountPYToRedeem);
if (!isExpired()) _burn(address(this), totalAmountPYToRedeem);
uint256 index = _pyIndexCurrent();
uint256 totalSyInterestPostExpiry;
amountSyOuts =newuint256[](receivers.length);
for (uint256 i =0; i < receivers.length; i++) {
uint256 syInterestPostExpiry;
(amountSyOuts[i], syInterestPostExpiry) = _calcSyRedeemableFromPY(amountPYToRedeems[i], index);
_transferOut(SY, receivers[i], amountSyOuts[i]);
totalSyInterestPostExpiry += syInterestPostExpiry;
emit Burn(msg.sender, receivers[i], amountPYToRedeems[i], amountSyOuts[i]);
}
if (totalSyInterestPostExpiry !=0) {
postExpiry.totalSyInterestForTreasury += totalSyInterestPostExpiry.Uint128();
}
}
function_calcPYToMint(uint256 amountSy, uint256 indexCurrent) internalpurereturns (uint256 amountPY) {
// doesn't matter before or after expiry, since mintPY is only allowed before expiryreturn SYUtils.syToAsset(indexCurrent, amountSy);
}
function_calcSyRedeemableFromPY(uint256 amountPY,
uint256 indexCurrent
) internalviewreturns (uint256 syToUser, uint256 syInterestPostExpiry) {
syToUser = SYUtils.assetToSy(indexCurrent, amountPY);
if (isExpired()) {
uint256 totalSyRedeemable = SYUtils.assetToSy(postExpiry.firstPYIndex, amountPY);
syInterestPostExpiry = totalSyRedeemable - syToUser;
}
}
function_getAmountPYToRedeem() internalviewreturns (uint256) {
if (!isExpired()) return PMath.min(_selfBalance(PT), balanceOf(address(this)));
elsereturn _selfBalance(PT);
}
function_updateSyReserve() internalvirtual{
syReserve = _selfBalance(SY);
}
function_getFloatingSyAmount() internalviewreturns (uint256 amount) {
amount = _selfBalance(SY) - syReserve;
if (amount ==0) revert Errors.YCNoFloatingSy();
}
function_setPostExpiryData() internal{
PostExpiryData storage local = postExpiry;
if (local.firstPYIndex !=0) return; // already set
_redeemExternalReward(); // do a final redeem. All the future reward income will belong to the treasury
local.firstPYIndex = _pyIndexCurrent().Uint128();
address[] memory rewardTokens = IStandardizedYield(SY).getRewardTokens();
uint256[] memory rewardIndexes = IStandardizedYield(SY).rewardIndexesCurrent();
for (uint256 i =0; i < rewardTokens.length; i++) {
local.firstRewardIndex[rewardTokens[i]] = rewardIndexes[i];
local.userRewardOwed[rewardTokens[i]] = _selfBalance(rewardTokens[i]);
}
}
/*///////////////////////////////////////////////////////////////
INTEREST-RELATED
//////////////////////////////////////////////////////////////*/function_getInterestIndex() internalvirtualoverridereturns (uint256 index) {
if (isExpired()) index = postExpiry.firstPYIndex;
else index = _pyIndexCurrent();
}
function_pyIndexCurrent() internalreturns (uint256 currentIndex) {
if (doCacheIndexSameBlock && pyIndexLastUpdatedBlock ==block.number) return _pyIndexStored;
uint128 index128 = PMath.max(IStandardizedYield(SY).exchangeRate(), _pyIndexStored).Uint128();
currentIndex = index128;
_pyIndexStored = index128;
pyIndexLastUpdatedBlock =uint128(block.number);
emit NewInterestIndex(currentIndex);
}
function_YTbalance(address user) internalviewoverridereturns (uint256) {
return balanceOf(user);
}
/*///////////////////////////////////////////////////////////////
REWARDS-RELATED
//////////////////////////////////////////////////////////////*/functiongetRewardTokens() publicviewreturns (address[] memory) {
return IStandardizedYield(SY).getRewardTokens();
}
function_doTransferOutRewards(address user,
address receiver
) internalvirtualoverridereturns (uint256[] memory rewardAmounts) {
address[] memory tokens = getRewardTokens();
if (isExpired()) {
// post-expiry, all incoming rewards will go to the treasury// hence, we can save users one _redeemExternal herefor (uint256 i =0; i < tokens.length; i++) {
uint256 owed = postExpiry.userRewardOwed[tokens[i]];
uint256 accrued = userReward[tokens[i]][user].accrued;
postExpiry.userRewardOwed[tokens[i]] = (owed < accrued) ? 0 : owed - accrued;
}
rewardAmounts = __doTransferOutRewardsLocal(tokens, user, receiver, false);
} else {
rewardAmounts = __doTransferOutRewardsLocal(tokens, user, receiver, true);
}
}
function__doTransferOutRewardsLocal(address[] memory tokens,
address user,
address receiver,
bool allowedToRedeemExternalReward
) internalreturns (uint256[] memory rewardAmounts) {
address treasury = IPYieldContractFactory(factory).treasury();
uint256 feeRate = IPYieldContractFactory(factory).rewardFeeRate();
bool redeemExternalThisRound;
rewardAmounts =newuint256[](tokens.length);
for (uint256 i =0; i < tokens.length; i++) {
uint256 rewardPreFee = userReward[tokens[i]][user].accrued;
userReward[tokens[i]][user].accrued =0;
uint256 feeAmount = rewardPreFee.mulDown(feeRate);
rewardAmounts[i] = rewardPreFee - feeAmount;
if (!redeemExternalThisRound && allowedToRedeemExternalReward) {
if (_selfBalance(tokens[i]) < rewardPreFee) {
_redeemExternalReward();
redeemExternalThisRound =true;
}
}
_transferOut(tokens[i], treasury, feeAmount);
_transferOut(tokens[i], receiver, rewardAmounts[i]);
emit CollectRewardFee(tokens[i], feeAmount);
}
}
function_redeemExternalReward() internalvirtualoverride{
IStandardizedYield(SY).claimRewards(address(this));
}
/// @dev effectively returning the amount of SY generating rewards for this userfunction_rewardSharesUser(address user) internalviewvirtualoverridereturns (uint256) {
uint256 index = userInterest[user].index;
if (index ==0) return0;
return SYUtils.assetToSy(index, balanceOf(user)) + userInterest[user].accrued;
}
function_updateRewardIndex() internaloverridereturns (address[] memory tokens, uint256[] memory indexes) {
tokens = getRewardTokens();
if (isExpired()) {
indexes =newuint256[](tokens.length);
for (uint256 i =0; i < tokens.length; i++) indexes[i] = postExpiry.firstRewardIndex[tokens[i]];
} else {
indexes = IStandardizedYield(SY).rewardIndexesCurrent();
}
}
//solhint-disable-next-line orderingfunction_beforeTokenTransfer(addressfrom, address to, uint256) internaloverride{
if (isExpired()) _setPostExpiryData();
_updateAndDistributeRewardsForTwo(from, to);
_distributeInterestForTwo(from, to);
}
}
Contract Source Code
File 20 of 23: 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 || index ==0) 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 23 of 23: 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);
}
}