Rounding in Favor of the Protocol with Integer Division in Solidity
Key Considerations
Example: Rounding in OpenZeppelin's ERC-4626 Implementation
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Math} from "../../utils/math/Math.sol";
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
abstract contract ERC4626 is ERC20, IERC4626 {
// ... (other contract code omitted for brevity)
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
}Explanation
Last updated

