diff --git a/contracts/IERC4626.sol b/contracts/IERC4626.sol new file mode 100644 index 000000000..a162fc1b1 --- /dev/null +++ b/contracts/IERC4626.sol @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT +// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol) + +pragma solidity 0.8.15; + +/** + * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in + * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626]. + */ +interface IERC4626 { + event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares); + + event Withdraw( + address indexed sender, + address indexed receiver, + address indexed owner, + uint256 assets, + uint256 shares + ); + + /// @dev Returns decimals of the Vault shares. + function decimals() external view returns (uint8); + + /** + * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing. + * + * - MUST be an ERC-20 token contract. + * - MUST NOT revert. + */ + function asset() external view returns (address assetTokenAddress); + + /** + * @dev Returns the total amount of the underlying asset that is “managed” by Vault. + * + * - SHOULD include any compounding that occurs from yield. + * - MUST be inclusive of any fees that are charged against assets in the Vault. + * - MUST NOT revert. + */ + function totalAssets() external view returns (uint256 totalManagedAssets); + + /** + * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal + * scenario where all the conditions are met. + * + * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. + * - MUST NOT revert. + * + * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the + * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and + * from. + */ + function convertToShares(uint256 assets) external view returns (uint256 shares); + + /** + * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal + * scenario where all the conditions are met. + * + * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. + * - MUST NOT show any variations depending on the caller. + * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. + * - MUST NOT revert. + * + * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the + * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and + * from. + */ + function convertToAssets(uint256 shares) external view returns (uint256 assets); + + /** + * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, + * through a deposit call. + * + * - MUST return a limited value if receiver is subject to some deposit limit. + * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited. + * - MUST NOT revert. + */ + function maxDeposit(address receiver) external view returns (uint256 maxAssets); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given + * current on-chain conditions. + * + * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit + * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called + * in the same transaction. + * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the + * deposit would be accepted, regardless if the user has enough tokens approved, etc. + * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in + * share price or some other type of condition, meaning the depositor will lose assets by depositing. + */ + function previewDeposit(uint256 assets) external view returns (uint256 shares); + + /** + * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens. + * + * - MUST emit the Deposit event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + * deposit execution, and are accounted for during deposit. + * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not + * approving enough underlying tokens to the Vault contract, etc). + * + * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. + */ + function deposit(uint256 assets, address receiver) external returns (uint256 shares); + + /** + * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. + * - MUST return a limited value if receiver is subject to some mint limit. + * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. + * - MUST NOT revert. + */ + function maxMint(address receiver) external view returns (uint256 maxShares); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given + * current on-chain conditions. + * + * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call + * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the + * same transaction. + * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint + * would be accepted, regardless if the user has enough tokens approved, etc. + * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in + * share price or some other type of condition, meaning the depositor will lose assets by minting. + */ + function previewMint(uint256 shares) external view returns (uint256 assets); + + /** + * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens. + * + * - MUST emit the Deposit event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint + * execution, and are accounted for during mint. + * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not + * approving enough underlying tokens to the Vault contract, etc). + * + * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. + */ + function mint(uint256 shares, address receiver) external returns (uint256 assets); + + /** + * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the + * Vault, through a withdraw call. + * + * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. + * - MUST NOT revert. + */ + function maxWithdraw(address owner) external view returns (uint256 maxAssets); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, + * given current on-chain conditions. + * + * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw + * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if + * called + * in the same transaction. + * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though + * the withdrawal would be accepted, regardless if the user has enough shares, etc. + * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in + * share price or some other type of condition, meaning the depositor will lose assets by depositing. + */ + function previewWithdraw(uint256 assets) external view returns (uint256 shares); + + /** + * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver. + * + * - MUST emit the Withdraw event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + * withdraw execution, and are accounted for during withdraw. + * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner + * not having enough shares, etc). + * + * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. + * Those methods should be performed separately. + */ + function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); + + /** + * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, + * through a redeem call. + * + * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. + * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. + * - MUST NOT revert. + */ + function maxRedeem(address owner) external view returns (uint256 maxShares); + + /** + * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, + * given current on-chain conditions. + * + * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call + * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the + * same transaction. + * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the + * redemption would be accepted, regardless if the user has enough shares, etc. + * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. + * - MUST NOT revert. + * + * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in + * share price or some other type of condition, meaning the depositor will lose assets by redeeming. + */ + function previewRedeem(uint256 shares) external view returns (uint256 assets); + + /** + * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver. + * + * - MUST emit the Withdraw event. + * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the + * redeem execution, and are accounted for during redeem. + * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner + * not having enough shares, etc). + * + * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed. + * Those methods should be performed separately. + */ + function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); +} \ No newline at end of file diff --git a/contracts/pricefeeds/PriceFeedWith4626Support.sol b/contracts/pricefeeds/PriceFeedWith4626Support.sol new file mode 100644 index 000000000..13861f06d --- /dev/null +++ b/contracts/pricefeeds/PriceFeedWith4626Support.sol @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: BUSL-1.1 +pragma solidity 0.8.15; + +import "../vendor/@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; +import "../IERC4626.sol"; +import "../IPriceFeed.sol"; + +/** + * @title Price feed for ERC4626 assets + * @notice A custom price feed that calculates the price for an ERC4626 asset + * @author Compound + */ +contract PriceFeedWith4626Support is IPriceFeed { + /** Custom errors **/ + error BadDecimals(); + error InvalidInt256(); + + /// @notice Version of the price feed + uint public constant override version = 1; + + /// @notice Description of the price feed + string public override description; + + /// @notice Number of decimals for returned prices + uint8 public immutable override decimals; + + /// @notice Number of decimals for the 4626 rate provider + uint8 rateProviderDecimals; + + /// @notice Number of decimals for the underlying asset + uint8 underlyingDecimals; + + /// @notice 4626 rate provider + address public immutable rateProvider; + + /// @notice Chainlink oracle for the underlying asset + address public immutable underlyingPriceFeed; + + /// @notice Combined scale of the two underlying price feeds + int public immutable combinedScale; + + /// @notice Scale of this price feed + int public immutable priceFeedScale; + + /** + * @notice Construct a new 4626 price feed + * @param rateProvider_ The address of the 4626 rate provider + * @param underlyingPriceFeed_ The address of the underlying asset price feed to fetch prices from + * @param decimals_ The number of decimals for the returned prices + **/ + constructor(address rateProvider_, address underlyingPriceFeed_, uint8 decimals_, string memory description_) { + rateProvider = rateProvider_; + underlyingPriceFeed = underlyingPriceFeed_; + rateProviderDecimals = IERC4626(rateProvider_).decimals(); + underlyingDecimals = AggregatorV3Interface(underlyingPriceFeed_).decimals(); + combinedScale = signed256(10 ** (rateProviderDecimals + underlyingDecimals)); + description = description_; + + if (decimals_ > 18) revert BadDecimals(); + decimals = decimals_; + priceFeedScale = int256(10 ** decimals); + } + + /** + * @notice Get the latest price for the underlying asset + * @return roundId Round id from the underlying asset price feed + * @return answer Latest price for the underlying asset + * @return startedAt Timestamp when the round was started; passed on from the underlying asset price feed + * @return updatedAt Timestamp when the round was last updated; passed on from the underlying asset price feed + * @return answeredInRound Round id in which the answer was computed; passed on from the underlying asset price feed + **/ + function latestRoundData() override external view returns (uint80, int256, uint256, uint256, uint80) { + uint256 rate = IERC4626(rateProvider).convertToAssets(10**rateProviderDecimals); + (uint80 roundId_, int256 underlyingPrice, uint256 startedAt_, uint256 updatedAt_, uint80 answeredInRound_) = AggregatorV3Interface(underlyingPriceFeed).latestRoundData(); + + // We return the round data of the underlying asset price feed because of its shorter heartbeat (1hr vs 24hr) + if (rate <= 0 || underlyingPrice <= 0) return (roundId_, 0, startedAt_, updatedAt_, answeredInRound_); + + int256 price = signed256(rate) * underlyingPrice * priceFeedScale / combinedScale; + return (roundId_, price, startedAt_, updatedAt_, answeredInRound_); + } + + function signed256(uint256 n) internal pure returns (int256) { + if (n > uint256(type(int256).max)) revert InvalidInt256(); + return int256(n); + } +} \ No newline at end of file diff --git a/deployments/mainnet/usdt/migrations/1727445522_add_sfrax_collateral.ts b/deployments/mainnet/usdt/migrations/1727445522_add_sfrax_collateral.ts new file mode 100644 index 000000000..c8e1f0fa2 --- /dev/null +++ b/deployments/mainnet/usdt/migrations/1727445522_add_sfrax_collateral.ts @@ -0,0 +1,128 @@ +import { expect } from 'chai'; +import { DeploymentManager } from '../../../../plugins/deployment_manager/DeploymentManager'; +import { migration } from '../../../../plugins/deployment_manager/Migration'; +import { exp, proposal } from '../../../../src/deploy'; + +const SFRAX_ADDRESS = '0xA663B02CF0a4b149d2aD41910CB81e23e1c41c32'; +const SFRAX_TO_FRAX_PRICE_FEED_ADDRESS = '0xA663B02CF0a4b149d2aD41910CB81e23e1c41c32'; +const FRAX_TO_USD_PRICE_FEED_ADDRESS = '0xB9E1E3A9feFf48998E45Fa90847ed4D467E8BcfD'; + +let priceFeedAddress: string; + +export default migration('1727445522_add_sfrax_collateral', { + async prepare(deploymentManager: DeploymentManager) { + const _sFRAXPriceFeed = await deploymentManager.deploy( + 'sFRAX:priceFeed', + 'pricefeeds/PriceFeedWith4626Support.sol', + [ + SFRAX_TO_FRAX_PRICE_FEED_ADDRESS, // sFRAX / FRAX price feed + FRAX_TO_USD_PRICE_FEED_ADDRESS, // FRAX / USD price feed + 8, // decimals + 'sFRAX / USD price feed', // description + ] + ); + return { sFRAXPriceFeedAddress: _sFRAXPriceFeed.address }; + }, + + enact: async (deploymentManager: DeploymentManager, _, { sFRAXPriceFeedAddress }) => { + const trace = deploymentManager.tracer(); + + const sFRAX = await deploymentManager.existing( + 'sFRAX', + SFRAX_ADDRESS, + 'mainnet', + 'contracts/ERC20.sol:ERC20' + ); + const sFRAXPriceFeed = await deploymentManager.existing( + 'sFRAX:priceFeed', + sFRAXPriceFeedAddress, + 'mainnet' + ); + priceFeedAddress = sFRAXPriceFeed.address; + const { + governor, + comet, + cometAdmin, + configurator + } = await deploymentManager.getContracts(); + + const newAssetConfig = { + asset: sFRAX.address, + priceFeed: sFRAXPriceFeed.address, + decimals: await sFRAX.decimals(), + borrowCollateralFactor: exp(0.88, 18), + liquidateCollateralFactor: exp(0.90, 18), + liquidationFactor: exp(0.95, 18), + supplyCap: exp(10_000_000, 18), + }; + + const mainnetActions = [ + // 1. Add sFRAX as asset + { + contract: configurator, + signature: 'addAsset(address,(address,address,uint8,uint64,uint64,uint64,uint128))', + args: [comet.address, newAssetConfig], + }, + // 2. Deploy and upgrade to a new version of Comet + { + contract: cometAdmin, + signature: 'deployAndUpgradeTo(address,address)', + args: [configurator.address, comet.address], + }, + ]; + + const description = '# Add sFRAX as collateral into cUSDTv3 on Ethereum\n\n## Proposal summary\n\nCompound Growth Program [AlphaGrowth] proposes to add sFRAX into cUSDTv3 on Ethereum network. This proposal takes the governance steps recommended and necessary to update a Compound III USDT market on Ethereum. Simulations have confirmed the market’s readiness, as much as possible, using the [Comet scenario suite](https://github.com/compound-finance/comet/tree/main/scenario). The new parameters include setting the risk parameters based off of the [recommendations from Gauntlet](https://www.comp.xyz/t/add-sfrax-as-collateral-to-usdt-markets-on-ethereum-mainnet/5615/3).\n\nFurther detailed information can be found on the corresponding [proposal pull request](https://github.com/compound-finance/comet/pull/932) and [forum discussion](https://www.comp.xyz/t/add-sfrax-as-collateral-to-usdt-markets-on-ethereum-mainnet/5615).\n\n\n## Proposal Actions\n\nThe first proposal action adds sFRAX asset as collateral with corresponding configurations.\n\nThe second action deploys and upgrades Comet to a new version.'; + const txn = await deploymentManager.retry(async () => + trace( + await governor.propose(...(await proposal(mainnetActions, description))) + ) + ); + + const event = txn.events.find( + (event) => event.event === 'ProposalCreated' + ); + const [proposalId] = event.args; + trace(`Created proposal ${proposalId}.`); + }, + + async enacted(): Promise { + return false; + }, + + async verify(deploymentManager: DeploymentManager) { + const { comet, configurator } = await deploymentManager.getContracts(); + + const sFRAXAssetIndex = Number(await comet.numAssets()) - 1; + + const sFRAXAssetConfig = { + asset: SFRAX_ADDRESS, + priceFeed: priceFeedAddress, + decimals: 18, + borrowCollateralFactor: exp(0.88, 18), + liquidateCollateralFactor: exp(0.90, 18), + liquidationFactor: exp(0.95, 18), + supplyCap: exp(10_000_000, 18), + }; + + // 1. Compare proposed asset config with Comet asset info + const sFRAXAssetInfo = await comet.getAssetInfoByAddress(SFRAX_ADDRESS); + expect(sFRAXAssetIndex).to.be.equal(sFRAXAssetInfo.offset); + expect(sFRAXAssetConfig.asset).to.be.equal(sFRAXAssetInfo.asset); + expect(sFRAXAssetConfig.priceFeed).to.be.equal(sFRAXAssetInfo.priceFeed); + expect(exp(1, sFRAXAssetConfig.decimals)).to.be.equal(sFRAXAssetInfo.scale); + expect(sFRAXAssetConfig.borrowCollateralFactor).to.be.equal(sFRAXAssetInfo.borrowCollateralFactor); + expect(sFRAXAssetConfig.liquidateCollateralFactor).to.be.equal(sFRAXAssetInfo.liquidateCollateralFactor); + expect(sFRAXAssetConfig.liquidationFactor).to.be.equal(sFRAXAssetInfo.liquidationFactor); + expect(sFRAXAssetConfig.supplyCap).to.be.equal(sFRAXAssetInfo.supplyCap); + + // 2. Compare proposed asset config with Configurator asset config + const configuratorSFRAXAssetConfig = (await configurator.getConfiguration(comet.address)).assetConfigs[sFRAXAssetIndex]; + expect(sFRAXAssetConfig.asset).to.be.equal(configuratorSFRAXAssetConfig.asset); + expect(sFRAXAssetConfig.priceFeed).to.be.equal(configuratorSFRAXAssetConfig.priceFeed); + expect(sFRAXAssetConfig.decimals).to.be.equal(configuratorSFRAXAssetConfig.decimals); + expect(sFRAXAssetConfig.borrowCollateralFactor).to.be.equal(configuratorSFRAXAssetConfig.borrowCollateralFactor); + expect(sFRAXAssetConfig.liquidateCollateralFactor).to.be.equal(configuratorSFRAXAssetConfig.liquidateCollateralFactor); + expect(sFRAXAssetConfig.liquidationFactor).to.be.equal(configuratorSFRAXAssetConfig.liquidationFactor); + expect(sFRAXAssetConfig.supplyCap).to.be.equal(configuratorSFRAXAssetConfig.supplyCap); + }, +}); \ No newline at end of file diff --git a/scenario/SupplyScenario.ts b/scenario/SupplyScenario.ts index f9075208b..7082f87a6 100644 --- a/scenario/SupplyScenario.ts +++ b/scenario/SupplyScenario.ts @@ -300,7 +300,7 @@ scenario( const utilization = await comet.getUtilization(); const borrowRate = (await comet.getBorrowRate(utilization)).toBigInt(); - expectApproximately(await albert.getCometBaseBalance(), -999n * scale, getInterest(999n * scale, borrowRate, 1n) + 1n); + expectApproximately(await albert.getCometBaseBalance(), -999n * scale, getInterest(999n * scale, borrowRate, 1n) + 2n); // Albert repays 1000 units of base borrow await baseAsset.approve(albert, comet.address);