编译器
0.8.24+commit.e11b9ed9
文件 1 的 23:Address.sol
pragma solidity ^0.8.1;
library Address {
function isContract(address account) internal view returns (bool) {
return account.code.length > 0;
}
function sendValue(address payable 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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
文件 2 的 23:ArrayLib.sol
pragma solidity ^0.8.0;
library ArrayLib {
function sum(uint256[] memory input) internal pure returns (uint256) {
uint256 value = 0;
for (uint256 i = 0; i < input.length; ) {
value += input[i];
unchecked {
i++;
}
}
return value;
}
function find(address[] memory array, address element) internal pure returns (uint256 index) {
uint256 length = array.length;
for (uint256 i = 0; i < length; ) {
if (array[i] == element) return i;
unchecked {
i++;
}
}
return type(uint256).max;
}
function append(address[] memory inp, address element) internal pure returns (address[] memory out) {
uint256 length = inp.length;
out = new address[](length + 1);
for (uint256 i = 0; i < length; ) {
out[i] = inp[i];
unchecked {
i++;
}
}
out[length] = element;
}
function appendHead(address[] memory inp, address element) internal pure returns (address[] memory out) {
uint256 length = inp.length;
out = new address[](length + 1);
out[0] = element;
for (uint256 i = 1; i <= length; ) {
out[i] = inp[i - 1];
unchecked {
i++;
}
}
}
function merge(address[] memory a, address[] memory b) internal pure returns (address[] memory out) {
unchecked {
uint256 countUnidenticalB = 0;
bool[] memory isUnidentical = new bool[](b.length);
for (uint256 i = 0; i < b.length; ++i) {
if (!contains(a, b[i])) {
countUnidenticalB++;
isUnidentical[i] = true;
}
}
out = new address[](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];
}
}
}
}
function contains(address[] memory array, address element) internal pure returns (bool) {
uint256 length = array.length;
for (uint256 i = 0; i < length; ) {
if (array[i] == element) return true;
unchecked {
i++;
}
}
return false;
}
function contains(bytes4[] memory array, bytes4 element) internal pure returns (bool) {
uint256 length = array.length;
for (uint256 i = 0; i < length; ) {
if (array[i] == element) return true;
unchecked {
i++;
}
}
return false;
}
function create(address a) internal pure returns (address[] memory res) {
res = new address[](1);
res[0] = a;
}
function create(address a, address b) internal pure returns (address[] memory res) {
res = new address[](2);
res[0] = a;
res[1] = b;
}
function create(address a, address b, address c) internal pure returns (address[] memory res) {
res = new address[](3);
res[0] = a;
res[1] = b;
res[2] = c;
}
function create(address a, address b, address c, address d) internal pure returns (address[] memory res) {
res = new address[](4);
res[0] = a;
res[1] = b;
res[2] = c;
res[3] = d;
}
function create(
address a,
address b,
address c,
address d,
address e
) internal pure returns (address[] memory res) {
res = new address[](5);
res[0] = a;
res[1] = b;
res[2] = c;
res[3] = d;
res[4] = e;
}
function create(uint256 a) internal pure returns (uint256[] memory res) {
res = new uint256[](1);
res[0] = a;
}
}
文件 3 的 23:Context.sol
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
文件 4 的 23:Errors.sol
pragma solidity ^0.8.0;
library Errors {
error BulkInsufficientSyForTrade(uint256 currentAmount, uint256 requiredAmount);
error BulkInsufficientTokenForTrade(uint256 currentAmount, uint256 requiredAmount);
error BulkInSufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut);
error BulkInSufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut);
error BulkInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance);
error BulkNotMaintainer();
error BulkNotAdmin();
error BulkSellerAlreadyExisted(address token, address SY, address bulk);
error BulkSellerInvalidToken(address token, address SY);
error BulkBadRateTokenToSy(uint256 actualRate, uint256 currentRate, uint256 eps);
error BulkBadRateSyToToken(uint256 actualRate, uint256 currentRate, uint256 eps);
error ApproxFail();
error ApproxParamsInvalid(uint256 guessMin, uint256 guessMax, uint256 eps);
error ApproxBinarySearchInputInvalid(
uint256 approxGuessMin,
uint256 approxGuessMax,
uint256 minGuessMin,
uint256 maxGuessMax
);
error MarketExpired();
error MarketZeroAmountsInput();
error MarketZeroAmountsOutput();
error MarketZeroLnImpliedRate();
error MarketInsufficientPtForTrade(int256 currentAmount, int256 requiredAmount);
error MarketInsufficientPtReceived(uint256 actualBalance, uint256 requiredBalance);
error MarketInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance);
error MarketZeroTotalPtOrTotalAsset(int256 totalPt, int256 totalAsset);
error MarketExchangeRateBelowOne(int256 exchangeRate);
error MarketProportionMustNotEqualOne();
error MarketRateScalarBelowZero(int256 rateScalar);
error MarketScalarRootBelowZero(int256 scalarRoot);
error MarketProportionTooHigh(int256 proportion, int256 maxProportion);
error OracleUninitialized();
error OracleTargetTooOld(uint32 target, uint32 oldest);
error OracleZeroCardinality();
error MarketFactoryExpiredPt();
error MarketFactoryInvalidPt();
error MarketFactoryMarketExists();
error MarketFactoryLnFeeRateRootTooHigh(uint80 lnFeeRateRoot, uint256 maxLnFeeRateRoot);
error MarketFactoryOverriddenFeeTooHigh(uint80 overriddenFee, uint256 marketLnFeeRateRoot);
error MarketFactoryReserveFeePercentTooHigh(uint8 reserveFeePercent, uint8 maxReserveFeePercent);
error MarketFactoryZeroTreasury();
error MarketFactoryInitialAnchorTooLow(int256 initialAnchor, int256 minInitialAnchor);
error MFNotPendleMarket(address addr);
error RouterInsufficientLpOut(uint256 actualLpOut, uint256 requiredLpOut);
error RouterInsufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut);
error RouterInsufficientPtOut(uint256 actualPtOut, uint256 requiredPtOut);
error RouterInsufficientYtOut(uint256 actualYtOut, uint256 requiredYtOut);
error RouterInsufficientPYOut(uint256 actualPYOut, uint256 requiredPYOut);
error RouterInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut);
error RouterInsufficientSyRepay(uint256 actualSyRepay, uint256 requiredSyRepay);
error RouterInsufficientPtRepay(uint256 actualPtRepay, uint256 requiredPtRepay);
error RouterNotAllSyUsed(uint256 netSyDesired, uint256 netSyUsed);
error RouterTimeRangeZero();
error RouterCallbackNotPendleMarket(address caller);
error RouterInvalidAction(bytes4 selector);
error RouterInvalidFacet(address facet);
error RouterKyberSwapDataZero();
error SimulationResults(bool success, bytes res);
error YCExpired();
error YCNotExpired();
error YieldContractInsufficientSy(uint256 actualSy, uint256 requiredSy);
error YCNothingToRedeem();
error YCPostExpiryDataNotSet();
error YCNoFloatingSy();
error YCFactoryInvalidExpiry();
error YCFactoryYieldContractExisted();
error YCFactoryZeroExpiryDivisor();
error YCFactoryZeroTreasury();
error YCFactoryInterestFeeRateTooHigh(uint256 interestFeeRate, uint256 maxInterestFeeRate);
error YCFactoryRewardFeeRateTooHigh(uint256 newRewardFeeRate, uint256 maxRewardFeeRate);
error SYInvalidTokenIn(address token);
error SYInvalidTokenOut(address token);
error SYZeroDeposit();
error SYZeroRedeem();
error SYInsufficientSharesOut(uint256 actualSharesOut, uint256 requiredSharesOut);
error SYInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut);
error SYQiTokenMintFailed(uint256 errCode);
error SYQiTokenRedeemFailed(uint256 errCode);
error SYQiTokenRedeemRewardsFailed(uint256 rewardAccruedType0, uint256 rewardAccruedType1);
error SYQiTokenBorrowRateTooHigh(uint256 borrowRate, uint256 borrowRateMax);
error SYCurveInvalidPid();
error SYCurve3crvPoolNotFound();
error SYApeDepositAmountTooSmall(uint256 amountDeposited);
error SYBalancerInvalidPid();
error SYInvalidRewardToken(address token);
error SYStargateRedeemCapExceeded(uint256 amountLpDesired, uint256 amountLpRedeemable);
error SYBalancerReentrancy();
error NotFromTrustedRemote(uint16 srcChainId, bytes path);
error ApxETHNotEnoughBuffer();
error VCInactivePool(address pool);
error VCPoolAlreadyActive(address pool);
error VCZeroVePendle(address user);
error VCExceededMaxWeight(uint256 totalWeight, uint256 maxWeight);
error VCEpochNotFinalized(uint256 wTime);
error VCPoolAlreadyAddAndRemoved(address pool);
error VEInvalidNewExpiry(uint256 newExpiry);
error VEExceededMaxLockTime();
error VEInsufficientLockTime();
error VENotAllowedReduceExpiry();
error VEZeroAmountLocked();
error VEPositionNotExpired();
error VEZeroPosition();
error VEZeroSlope(uint128 bias, uint128 slope);
error VEReceiveOldSupply(uint256 msgTime);
error GCNotPendleMarket(address caller);
error GCNotVotingController(address caller);
error InvalidWTime(uint256 wTime);
error ExpiryInThePast(uint256 expiry);
error ChainNotSupported(uint256 chainId);
error FDTotalAmountFundedNotMatch(uint256 actualTotalAmount, uint256 expectedTotalAmount);
error FDEpochLengthMismatch();
error FDInvalidPool(address pool);
error FDPoolAlreadyExists(address pool);
error FDInvalidNewFinishedEpoch(uint256 oldFinishedEpoch, uint256 newFinishedEpoch);
error FDInvalidStartEpoch(uint256 startEpoch);
error FDInvalidWTimeFund(uint256 lastFunded, uint256 wTime);
error FDFutureFunding(uint256 lastFunded, uint256 currentWTime);
error BDInvalidEpoch(uint256 epoch, uint256 startTime);
error MsgNotFromSendEndpoint(uint16 srcChainId, bytes path);
error MsgNotFromReceiveEndpoint(address sender);
error InsufficientFeeToSendMsg(uint256 currentFee, uint256 requiredFee);
error ApproxDstExecutionGasNotSet();
error InvalidRetryData();
error ArrayLengthMismatch();
error ArrayEmpty();
error ArrayOutOfBounds();
error ZeroAddress();
error FailedToSendEther();
error InvalidMerkleProof();
error OnlyLayerZeroEndpoint();
error OnlyYT();
error OnlyYCFactory();
error OnlyWhitelisted();
error SAInsufficientTokenIn(address tokenIn, uint256 amountExpected, uint256 amountActual);
error UnsupportedSelector(uint256 aggregatorType, bytes4 selector);
}
文件 5 的 23:IERC20.sol
pragma solidity ^0.8.0;
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
文件 6 的 23:IERC20Metadata.sol
pragma solidity ^0.8.0;
import "../IERC20.sol";
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
文件 7 的 23:IERC20Permit.sol
pragma solidity ^0.8.0;
interface IERC20Permit {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
文件 8 的 23:IPInterestManagerYT.sol
pragma solidity ^0.8.0;
interface IPInterestManagerYT {
event CollectInterestFee(uint256 amountInterestFee);
function userInterest(address user) external view returns (uint128 lastPYIndex, uint128 accruedInterest);
}
文件 9 的 23:IPPrincipalToken.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
interface IPPrincipalToken is IERC20Metadata {
function burnByYT(address user, uint256 amount) external;
function mintByYT(address user, uint256 amount) external;
function initialize(address _YT) external;
function SY() external view returns (address);
function YT() external view returns (address);
function factory() external view returns (address);
function expiry() external view returns (uint256);
function isExpired() external view returns (bool);
}
文件 10 的 23:IPYieldContractFactory.sol
pragma solidity ^0.8.0;
interface IPYieldContractFactory {
event CreateYieldContract(address indexed SY, uint256 indexed expiry, address PT, address YT);
event SetExpiryDivisor(uint256 newExpiryDivisor);
event SetInterestFeeRate(uint256 newInterestFeeRate);
event SetRewardFeeRate(uint256 newRewardFeeRate);
event SetTreasury(address indexed treasury);
function getPT(address SY, uint256 expiry) external view returns (address);
function getYT(address SY, uint256 expiry) external view returns (address);
function expiryDivisor() external view returns (uint96);
function interestFeeRate() external view returns (uint128);
function rewardFeeRate() external view returns (uint128);
function treasury() external view returns (address);
function isPT(address) external view returns (bool);
function isYT(address) external view returns (bool);
function createYieldContract(
address SY,
uint32 expiry,
bool doCacheIndexSameBlock
) external returns (address PT, address YT);
}
文件 11 的 23:IPYieldToken.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IRewardManager.sol";
import "./IPInterestManagerYT.sol";
interface IPYieldToken is IERC20Metadata, IRewardManager, IPInterestManagerYT {
event NewInterestIndex(uint256 indexed newIndex);
event Mint(
address indexed caller,
address indexed receiverPT,
address indexed receiverYT,
uint256 amountSyToMint,
uint256 amountPYOut
);
event Burn(address indexed caller, address indexed receiver, uint256 amountPYToRedeem, uint256 amountSyOut);
event RedeemRewards(address indexed user, uint256[] amountRewardsOut);
event RedeemInterest(address indexed user, uint256 interestOut);
event CollectRewardFee(address indexed rewardToken, uint256 amountRewardFee);
function mintPY(address receiverPT, address receiverYT) external returns (uint256 amountPYOut);
function redeemPY(address receiver) external returns (uint256 amountSyOut);
function redeemPYMulti(
address[] calldata receivers,
uint256[] calldata amountPYToRedeems
) external returns (uint256[] memory amountSyOuts);
function redeemDueInterestAndRewards(
address user,
bool redeemInterest,
bool redeemRewards
) external returns (uint256 interestOut, uint256[] memory rewardsOut);
function rewardIndexesCurrent() external returns (uint256[] memory);
function pyIndexCurrent() external returns (uint256);
function pyIndexStored() external view returns (uint256);
function getRewardTokens() external view returns (address[] memory);
function SY() external view returns (address);
function PT() external view returns (address);
function factory() external view returns (address);
function expiry() external view returns (uint256);
function isExpired() external view returns (bool);
function doCacheIndexSameBlock() external view returns (bool);
function pyIndexLastUpdatedBlock() external view returns (uint128);
}
文件 12 的 23:IRewardManager.sol
pragma solidity ^0.8.0;
interface IRewardManager {
function userReward(address token, address user) external view returns (uint128 index, uint128 accrued);
}
文件 13 的 23:IStandardizedYield.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
interface IStandardizedYield is IERC20Metadata {
event Deposit(
address indexed caller,
address indexed receiver,
address indexed tokenIn,
uint256 amountDeposited,
uint256 amountSyOut
);
event Redeem(
address indexed caller,
address indexed receiver,
address indexed tokenOut,
uint256 amountSyToRedeem,
uint256 amountTokenOut
);
enum AssetType {
TOKEN,
LIQUIDITY
}
event ClaimRewards(address indexed user, address[] rewardTokens, uint256[] rewardAmounts);
function deposit(
address receiver,
address tokenIn,
uint256 amountTokenToDeposit,
uint256 minSharesOut
) external payable returns (uint256 amountSharesOut);
function redeem(
address receiver,
uint256 amountSharesToRedeem,
address tokenOut,
uint256 minTokenOut,
bool burnFromInternalBalance
) external returns (uint256 amountTokenOut);
function exchangeRate() external view returns (uint256 res);
function claimRewards(address user) external returns (uint256[] memory rewardAmounts);
function accruedRewards(address user) external view returns (uint256[] memory rewardAmounts);
function rewardIndexesCurrent() external returns (uint256[] memory indexes);
function rewardIndexesStored() external view returns (uint256[] memory indexes);
function getRewardTokens() external view returns (address[] memory);
function yieldToken() external view returns (address);
function getTokensIn() external view returns (address[] memory res);
function getTokensOut() external view returns (address[] memory res);
function isValidTokenIn(address token) external view returns (bool);
function isValidTokenOut(address token) external view returns (bool);
function previewDeposit(
address tokenIn,
uint256 amountTokenToDeposit
) external view returns (uint256 amountSharesOut);
function previewRedeem(
address tokenOut,
uint256 amountSharesToRedeem
) external view returns (uint256 amountTokenOut);
function assetInfo() external view returns (AssetType assetType, address assetAddress, uint8 assetDecimals);
}
文件 14 的 23:IWETH.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function deposit() external payable;
function withdraw(uint256 wad) external;
}
文件 15 的 23:InterestManagerYT.sol
pragma solidity ^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";
abstract contract InterestManagerYT is TokenHelper, IPInterestManagerYT {
using PMath for uint256;
struct UserInterest {
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
) internal returns (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);
}
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() internal virtual returns (uint256 index);
function _YTbalance(address user) internal view virtual returns (uint256);
}
文件 16 的 23:MiniHelpers.sol
pragma solidity ^0.8.0;
library MiniHelpers {
function isCurrentlyExpired(uint256 expiry) internal view returns (bool) {
return (expiry <= block.timestamp);
}
function isExpired(uint256 expiry, uint256 blockTime) internal pure returns (bool) {
return (expiry <= blockTime);
}
function isTimeInThePast(uint256 timestamp) internal view returns (bool) {
return (timestamp <= block.timestamp);
}
}
文件 17 的 23:PMath.sol
pragma solidity ^0.8.0;
library PMath {
uint256 internal constant ONE = 1e18;
int256 internal constant IONE = 1e18;
function subMax0(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return (a >= b ? a - b : 0);
}
}
function subNoNeg(int256 a, int256 b) internal pure returns (int256) {
require(a >= b, "negative");
return a - b;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
unchecked {
return product / ONE;
}
}
function mulDown(int256 a, int256 b) internal pure returns (int256) {
int256 product = a * b;
unchecked {
return product / IONE;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 aInflated = a * ONE;
unchecked {
return aInflated / b;
}
}
function divDown(int256 a, int256 b) internal pure returns (int256) {
int256 aInflated = a * IONE;
unchecked {
return aInflated / b;
}
}
function rawDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
function rawDivUp(int256 a, int256 b) internal pure returns (int256) {
return (a + b - 1) / b;
}
function slipUp(uint256 a, uint256 factor) internal pure returns (uint256) {
return mulDown(a, ONE + factor);
}
function slipDown(uint256 a, uint256 factor) internal pure returns (uint256) {
return mulDown(a, ONE - factor);
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function square(uint256 x) internal pure returns (uint256) {
return x * x;
}
function squareDown(uint256 x) internal pure returns (uint256) {
return mulDown(x, x);
}
function abs(int256 x) internal pure returns (uint256) {
return uint256(x > 0 ? x : -x);
}
function neg(int256 x) internal pure returns (int256) {
return x * (-1);
}
function neg(uint256 x) internal pure returns (int256) {
return Int(x) * (-1);
}
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return (x > y ? x : y);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return (x > y ? x : y);
}
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return (x < y ? x : y);
}
function min(int256 x, int256 y) internal pure returns (int256) {
return (x < y ? x : y);
}
function Int(uint256 x) internal pure returns (int256) {
require(x <= uint256(type(int256).max));
return int256(x);
}
function Int128(int256 x) internal pure returns (int128) {
require(type(int128).min <= x && x <= type(int128).max);
return int128(x);
}
function Int128(uint256 x) internal pure returns (int128) {
return Int128(Int(x));
}
function Uint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function Uint32(uint256 x) internal pure returns (uint32) {
require(x <= type(uint32).max);
return uint32(x);
}
function Uint64(uint256 x) internal pure returns (uint64) {
require(x <= type(uint64).max);
return uint64(x);
}
function Uint112(uint256 x) internal pure returns (uint112) {
require(x <= type(uint112).max);
return uint112(x);
}
function Uint96(uint256 x) internal pure returns (uint96) {
require(x <= type(uint96).max);
return uint96(x);
}
function Uint128(uint256 x) internal pure returns (uint128) {
require(x <= type(uint128).max);
return uint128(x);
}
function Uint192(uint256 x) internal pure returns (uint192) {
require(x <= type(uint192).max);
return uint192(x);
}
function isAApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
return mulDown(b, ONE - eps) <= a && a <= mulDown(b, ONE + eps);
}
function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
return a >= b && a <= mulDown(b, ONE + eps);
}
function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
return a <= b && a >= mulDown(b, ONE - eps);
}
}
文件 18 的 23:PendleERC20.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
contract PendleERC20 is Context, IERC20, IERC20Metadata {
uint8 private constant _NOT_ENTERED = 1;
uint8 private constant _ENTERED = 2;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint248 private _totalSupply;
uint8 private _status;
string private _name;
string private _symbol;
uint8 public immutable decimals;
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
constructor(string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
decimals = decimals_;
_status = _NOT_ENTERED;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address to, uint256 amount) external virtual override nonReentrant returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) external virtual override nonReentrant returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
function _transfer(address from, address to, uint256 amount) internal virtual {
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);
}
function _mint(address account, uint256 amount) internal virtual {
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);
}
function _burn(address account, uint256 amount) internal virtual {
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);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
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);
}
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
function toUint248(uint256 x) internal virtual returns (uint248) {
require(x <= type(uint248).max);
return uint248(x);
}
}
文件 19 的 23:PendleYieldToken.sol
pragma solidity ^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";
contract PendleYieldToken is IPYieldToken, PendleERC20, RewardManagerAbstract, InterestManagerYT {
using PMath for uint256;
using SafeERC20 for IERC20;
using ArrayLib for uint256[];
struct PostExpiryData {
uint128 firstPYIndex;
uint128 totalSyInterestForTreasury;
mapping(address => uint256) firstRewardIndex;
mapping(address => uint256) userRewardOwed;
}
address public immutable SY;
address public immutable PT;
address public immutable factory;
uint256 public immutable expiry;
bool public immutable doCacheIndexSameBlock;
uint256 public syReserve;
uint128 public pyIndexLastUpdatedBlock;
uint128 internal _pyIndexStored;
PostExpiryData public postExpiry;
modifier updateData() {
if (isExpired()) _setPostExpiryData();
_;
_updateSyReserve();
}
modifier notExpired() {
if (isExpired()) revert Errors.YCExpired();
_;
}
constructor(
address _SY,
address _PT,
string memory _name,
string memory _symbol,
uint8 __decimals,
uint256 _expiry,
bool _doCacheIndexSameBlock
) PendleERC20(_name, _symbol, __decimals) {
SY = _SY;
PT = _PT;
expiry = _expiry;
factory = msg.sender;
doCacheIndexSameBlock = _doCacheIndexSameBlock;
}
function mintPY(
address receiverPT,
address receiverYT
) external nonReentrant notExpired updateData returns (uint256 amountPYOut) {
address[] memory receiverPTs = new address[](1);
address[] memory receiverYTs = new address[](1);
uint256[] memory amountSyToMints = new uint256[](1);
(receiverPTs[0], receiverYTs[0], amountSyToMints[0]) = (receiverPT, receiverYT, _getFloatingSyAmount());
uint256[] memory amountPYOuts = _mintPY(receiverPTs, receiverYTs, amountSyToMints);
amountPYOut = amountPYOuts[0];
}
function mintPYMulti(
address[] calldata receiverPTs,
address[] calldata receiverYTs,
uint256[] calldata amountSyToMints
) external nonReentrant notExpired updateData returns (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);
}
function redeemPY(address receiver) external nonReentrant updateData returns (uint256 amountSyOut) {
address[] memory receivers = new address[](1);
uint256[] memory amounts = new uint256[](1);
(receivers[0], amounts[0]) = (receiver, _getAmountPYToRedeem());
uint256[] memory amountSyOuts;
amountSyOuts = _redeemPY(receivers, amounts);
amountSyOut = amountSyOuts[0];
}
function redeemPYMulti(
address[] calldata receivers,
uint256[] calldata amountPYToRedeems
) external nonReentrant updateData returns (uint256[] memory amountSyOuts) {
if (receivers.length != amountPYToRedeems.length) revert Errors.ArrayLengthMismatch();
if (receivers.length == 0) revert Errors.ArrayEmpty();
amountSyOuts = _redeemPY(receivers, amountPYToRedeems);
}
function redeemDueInterestAndRewards(
address user,
bool redeemInterest,
bool redeemRewards
) external nonReentrant updateData returns (uint256 interestOut, uint256[] memory rewardsOut) {
if (!redeemInterest && !redeemRewards) revert Errors.YCNothingToRedeem();
_updateAndDistributeRewards(user);
if (redeemRewards) {
rewardsOut = _doTransferOutRewards(user, user);
emit RedeemRewards(user, rewardsOut);
} else {
address[] memory tokens = getRewardTokens();
rewardsOut = new uint256[](tokens.length);
}
if (redeemInterest) {
_distributeInterest(user);
interestOut = _doTransferOutInterest(user, SY, factory);
emit RedeemInterest(user, interestOut);
} else {
interestOut = 0;
}
}
function redeemInterestAndRewardsPostExpiryForTreasury()
external
nonReentrant
updateData
returns (uint256 interestOut, uint256[] memory rewardsOut)
{
if (!isExpired()) revert Errors.YCNotExpired();
address treasury = IPYieldContractFactory(factory).treasury();
address[] memory tokens = getRewardTokens();
rewardsOut = new uint256[](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);
}
function rewardIndexesCurrent() external override nonReentrant returns (uint256[] memory) {
return IStandardizedYield(SY).rewardIndexesCurrent();
}
function pyIndexCurrent() public nonReentrant returns (uint256 currentIndex) {
currentIndex = _pyIndexCurrent();
}
function pyIndexStored() public view returns (uint256) {
return _pyIndexStored;
}
function setPostExpiryData() external nonReentrant {
if (isExpired()) {
_setPostExpiryData();
}
}
function getPostExpiryData()
external
view
returns (
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 = new uint256[](tokens.length);
userRewardOwed = new uint256[](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
) internal returns (uint256[] memory amountPYOuts) {
amountPYOuts = new uint256[](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]);
}
}
function isExpired() public view returns (bool) {
return MiniHelpers.isCurrentlyExpired(expiry);
}
function _redeemPY(
address[] memory receivers,
uint256[] memory amountPYToRedeems
) internal returns (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 = new uint256[](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) internal pure returns (uint256 amountPY) {
return SYUtils.syToAsset(indexCurrent, amountSy);
}
function _calcSyRedeemableFromPY(
uint256 amountPY,
uint256 indexCurrent
) internal view returns (uint256 syToUser, uint256 syInterestPostExpiry) {
syToUser = SYUtils.assetToSy(indexCurrent, amountPY);
if (isExpired()) {
uint256 totalSyRedeemable = SYUtils.assetToSy(postExpiry.firstPYIndex, amountPY);
syInterestPostExpiry = totalSyRedeemable - syToUser;
}
}
function _getAmountPYToRedeem() internal view returns (uint256) {
if (!isExpired()) return PMath.min(_selfBalance(PT), balanceOf(address(this)));
else return _selfBalance(PT);
}
function _updateSyReserve() internal virtual {
syReserve = _selfBalance(SY);
}
function _getFloatingSyAmount() internal view returns (uint256 amount) {
amount = _selfBalance(SY) - syReserve;
if (amount == 0) revert Errors.YCNoFloatingSy();
}
function _setPostExpiryData() internal {
PostExpiryData storage local = postExpiry;
if (local.firstPYIndex != 0) return;
_redeemExternalReward();
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]);
}
}
function _getInterestIndex() internal virtual override returns (uint256 index) {
if (isExpired()) index = postExpiry.firstPYIndex;
else index = _pyIndexCurrent();
}
function _pyIndexCurrent() internal returns (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) internal view override returns (uint256) {
return balanceOf(user);
}
function getRewardTokens() public view returns (address[] memory) {
return IStandardizedYield(SY).getRewardTokens();
}
function _doTransferOutRewards(
address user,
address receiver
) internal virtual override returns (uint256[] memory rewardAmounts) {
address[] memory tokens = getRewardTokens();
if (isExpired()) {
for (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
) internal returns (uint256[] memory rewardAmounts) {
address treasury = IPYieldContractFactory(factory).treasury();
uint256 feeRate = IPYieldContractFactory(factory).rewardFeeRate();
bool redeemExternalThisRound;
rewardAmounts = new uint256[](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() internal virtual override {
IStandardizedYield(SY).claimRewards(address(this));
}
function _rewardSharesUser(address user) internal view virtual override returns (uint256) {
uint256 index = userInterest[user].index;
if (index == 0) return 0;
return SYUtils.assetToSy(index, balanceOf(user)) + userInterest[user].accrued;
}
function _updateRewardIndex() internal override returns (address[] memory tokens, uint256[] memory indexes) {
tokens = getRewardTokens();
if (isExpired()) {
indexes = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) indexes[i] = postExpiry.firstRewardIndex[tokens[i]];
} else {
indexes = IStandardizedYield(SY).rewardIndexesCurrent();
}
}
function _beforeTokenTransfer(address from, address to, uint256) internal override {
if (isExpired()) _setPostExpiryData();
_updateAndDistributeRewardsForTwo(from, to);
_distributeInterestForTwo(from, to);
}
}
文件 20 的 23:RewardManagerAbstract.sol
pragma solidity ^0.8.0;
import "../../interfaces/IRewardManager.sol";
import "../libraries/ArrayLib.sol";
import "../libraries/TokenHelper.sol";
import "../libraries/math/PMath.sol";
import "./RewardManagerAbstract.sol";
abstract contract RewardManagerAbstract is IRewardManager, TokenHelper {
using PMath for uint256;
uint256 internal constant INITIAL_REWARD_INDEX = 1;
struct RewardState {
uint128 index;
uint128 lastBalance;
}
struct UserReward {
uint128 index;
uint128 accrued;
}
mapping(address => mapping(address => UserReward)) public userReward;
function _updateAndDistributeRewards(address user) internal virtual {
_updateAndDistributeRewardsForTwo(user, address(0));
}
function _updateAndDistributeRewardsForTwo(address user1, address user2) internal virtual {
(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);
}
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() internal virtual returns (address[] memory tokens, uint256[] memory indexes);
function _redeemExternalReward() internal virtual;
function _doTransferOutRewards(
address user,
address receiver
) internal virtual returns (uint256[] memory rewardAmounts);
function _rewardSharesUser(address user) internal view virtual returns (uint256);
}
文件 21 的 23:SYUtils.sol
pragma solidity ^0.8.0;
library SYUtils {
uint256 internal constant ONE = 1e18;
function syToAsset(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) {
return (syAmount * exchangeRate) / ONE;
}
function syToAssetUp(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) {
return (syAmount * exchangeRate + ONE - 1) / ONE;
}
function assetToSy(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) {
return (assetAmount * ONE) / exchangeRate;
}
function assetToSyUp(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) {
return (assetAmount * ONE + exchangeRate - 1) / exchangeRate;
}
}
文件 22 的 23:SafeERC20.sol
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
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));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
function safeDecreaseAllowance(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));
}
}
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
function safePermit(
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");
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
文件 23 的 23:TokenHelper.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/IWETH.sol";
abstract contract TokenHelper {
using SafeERC20 for IERC20;
address internal constant NATIVE = address(0);
uint256 internal constant LOWER_BOUND_APPROVAL = type(uint96).max / 2;
function _transferIn(address token, address from, uint256 amount) internal {
if (token == NATIVE) require(msg.value == amount, "eth mismatch");
else if (amount != 0) IERC20(token).safeTransferFrom(from, address(this), amount);
}
function _transferFrom(IERC20 token, address from, 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) internal view returns (uint256) {
return (token == NATIVE) ? address(this).balance : IERC20(token).balanceOf(address(this));
}
function _selfBalance(IERC20 token) internal view returns (uint256) {
return token.balanceOf(address(this));
}
function _safeApprove(address token, address to, uint256 value) internal {
(bool success, bytes memory 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);
}
}
{
"compilationTarget": {
"contracts/pendle/contracts/core/YieldContracts/PendleYieldToken.sol": "PendleYieldToken"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 1000000
},
"remappings": [],
"viaIR": true
}
[{"inputs":[{"internalType":"address","name":"_SY","type":"address"},{"internalType":"address","name":"_PT","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint8","name":"__decimals","type":"uint8"},{"internalType":"uint256","name":"_expiry","type":"uint256"},{"internalType":"bool","name":"_doCacheIndexSameBlock","type":"bool"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ArrayEmpty","type":"error"},{"inputs":[],"name":"ArrayLengthMismatch","type":"error"},{"inputs":[],"name":"YCExpired","type":"error"},{"inputs":[],"name":"YCNoFloatingSy","type":"error"},{"inputs":[],"name":"YCNotExpired","type":"error"},{"inputs":[],"name":"YCNothingToRedeem","type":"error"},{"inputs":[],"name":"YCPostExpiryDataNotSet","type":"error"},{"inputs":[{"internalType":"uint256","name":"actualSy","type":"uint256"},{"internalType":"uint256","name":"requiredSy","type":"uint256"}],"name":"YieldContractInsufficientSy","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountPYToRedeem","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountSyOut","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amountInterestFee","type":"uint256"}],"name":"CollectInterestFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"rewardToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountRewardFee","type":"uint256"}],"name":"CollectRewardFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"receiverPT","type":"address"},{"indexed":true,"internalType":"address","name":"receiverYT","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountSyToMint","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountPYOut","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"newIndex","type":"uint256"}],"name":"NewInterestIndex","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"interestOut","type":"uint256"}],"name":"RedeemInterest","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"amountRewardsOut","type":"uint256[]"}],"name":"RedeemRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"PT","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SY","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"doCacheIndexSameBlock","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"expiry","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPostExpiryData","outputs":[{"internalType":"uint256","name":"firstPYIndex","type":"uint256"},{"internalType":"uint256","name":"totalSyInterestForTreasury","type":"uint256"},{"internalType":"uint256[]","name":"firstRewardIndexes","type":"uint256[]"},{"internalType":"uint256[]","name":"userRewardOwed","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRewardTokens","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isExpired","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiverPT","type":"address"},{"internalType":"address","name":"receiverYT","type":"address"}],"name":"mintPY","outputs":[{"internalType":"uint256","name":"amountPYOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"receiverPTs","type":"address[]"},{"internalType":"address[]","name":"receiverYTs","type":"address[]"},{"internalType":"uint256[]","name":"amountSyToMints","type":"uint256[]"}],"name":"mintPYMulti","outputs":[{"internalType":"uint256[]","name":"amountPYOuts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"postExpiry","outputs":[{"internalType":"uint128","name":"firstPYIndex","type":"uint128"},{"internalType":"uint128","name":"totalSyInterestForTreasury","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pyIndexCurrent","outputs":[{"internalType":"uint256","name":"currentIndex","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pyIndexLastUpdatedBlock","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pyIndexStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"bool","name":"redeemInterest","type":"bool"},{"internalType":"bool","name":"redeemRewards","type":"bool"}],"name":"redeemDueInterestAndRewards","outputs":[{"internalType":"uint256","name":"interestOut","type":"uint256"},{"internalType":"uint256[]","name":"rewardsOut","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"redeemInterestAndRewardsPostExpiryForTreasury","outputs":[{"internalType":"uint256","name":"interestOut","type":"uint256"},{"internalType":"uint256[]","name":"rewardsOut","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"redeemPY","outputs":[{"internalType":"uint256","name":"amountSyOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"receivers","type":"address[]"},{"internalType":"uint256[]","name":"amountPYToRedeems","type":"uint256[]"}],"name":"redeemPYMulti","outputs":[{"internalType":"uint256[]","name":"amountSyOuts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardIndexesCurrent","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"setPostExpiryData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"syReserve","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userInterest","outputs":[{"internalType":"uint128","name":"index","type":"uint128"},{"internalType":"uint128","name":"accrued","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"userReward","outputs":[{"internalType":"uint128","name":"index","type":"uint128"},{"internalType":"uint128","name":"accrued","type":"uint128"}],"stateMutability":"view","type":"function"}]