-
Notifications
You must be signed in to change notification settings - Fork 2
feat: add PriceUtils #657
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: add PriceUtils #657
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # EditorConfig http://EditorConfig.org | ||
|
|
||
| # top-most EditorConfig file | ||
| root = true | ||
|
|
||
| # All files | ||
| [*] | ||
| charset = utf-8 | ||
| end_of_line = lf | ||
| indent_size = 2 | ||
| indent_style = space | ||
| insert_final_newline = true | ||
| trim_trailing_whitespace = true | ||
|
|
||
| [*.sol] | ||
| indent_size = 4 | ||
|
|
||
| [*.tree] | ||
| indent_size = 1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| image: "gitpod/workspace-bun" | ||
|
|
||
| tasks: | ||
| - name: "Install dependencies" | ||
| before: | | ||
| curl -L https://foundry.paradigm.xyz | bash | ||
| source ~/.bashrc | ||
| foundryup | ||
| init: "bun install" | ||
|
|
||
| vscode: | ||
| extensions: | ||
| - "esbenp.prettier-vscode" | ||
| - "NomicFoundation.hardhat-solidity" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "plugins": ["prettier"], | ||
| "rules": { | ||
| "prettier/prettier": "error" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| MIT License | ||
|
|
||
| Copyright (c) 2025 Oazo Apps Limited | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy of this software and | ||
| associated documentation files (the "Software"), to deal in the Software without restriction, | ||
| including without limitation the rights to use, copy, modify, merge, publish, distribute, | ||
| sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all copies or substantial | ||
| portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT | ||
| NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | ||
| NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES | ||
| OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | ||
| CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| # Prices library for Solidity | ||
|
|
||
| This library handles prices in base/quote notation where a price represents how much quote asset is | ||
| needed to buy one unit of the base asset. This is represented as BASE/QUOTE. For example, a price of | ||
| 2000 USDC per ETH would be represented as ETH/USDC = 2000. | ||
|
|
||
| ### Features | ||
|
|
||
| The library abstracts the complexisty of handling prices for bases and quotes with different | ||
| decimals and provides a simple interface for price manipulation and calculations. | ||
|
|
||
| - Custom `Price` type that holds the ratio of base to quote | ||
| - Free function `toPrice` to create Price instances | ||
| - Custom `Price` functions: `invert()` and `quote(amount)` | ||
| - Custom `uint256` functions: `mul(Price)`, `div(Price)` | ||
|
|
||
| ### Caveats | ||
|
|
||
| Understand that the nomenclature of base and quote is the inverse of the mathematical ratio. For | ||
| example, if the price is 2000 USDC per ETH, the mathematical ratio is 1 ETH / 2000 USDC = 0.0005, | ||
| but the base/quote representation is ETH/USDC = 2000. | ||
|
|
||
| In this library, when quoting an amount using a price, we mean converting an amount of the quote | ||
| asset to the equivalent amount of the base asset using the price. For example, if we have a price of | ||
| 2000 USDC per ETH (ETH/USDC = 2000), and we want to quote 4000 USDC, we would get 2 ETH. | ||
|
|
||
| This is the same as multiplying the quote amount by the price using `.mul()` on a `uint256` type. | ||
|
|
||
| ## Usage Examples | ||
|
|
||
| ```solidity | ||
| // SPDX-License-Identifier: BUSL-1.1 | ||
| pragma solidity 0.8.28; | ||
|
|
||
| import '../contracts/PriceUtils.sol'; | ||
|
|
||
| contract PriceExample { | ||
| using PriceUtils for Price; | ||
| using PriceUtils for uint256; | ||
|
|
||
| function quoteAmount() public pure { | ||
| uint256 baseAmount = 1e6; // USDC | ||
| uint256 quoteAmount = 2e18; // ETH | ||
|
|
||
| Price memory priceUSDC_ETH = toPrice(baseAmount, quoteAmount); | ||
|
|
||
| uint256 inputQuoteAmount = 10e18; // 10 ETH | ||
|
|
||
| uint256 outputAmountUSDC = priceUSDC_ETH.quote(inputQuoteAmount); // 5e6 USDC | ||
| } | ||
|
|
||
| function chainPrices() public pure { | ||
| uint256 priceABase = 10000e9; // SUMR | ||
| uint256 priceAQuote = 1e8; // WBTC | ||
|
|
||
| uint256 priceBBase = 1e8; // WBTC | ||
| uint256 priceBQuote = 100000e6; // USDC | ||
|
|
||
| Price memory priceA = toPrice(priceABase, priceAQuote); | ||
| Price memory priceB = toPrice(priceBBase, priceBQuote); | ||
|
|
||
| uint256 inputAmount = 200000e6; // USDC | ||
|
|
||
| uint256 outputAmount = inputAmount.mul(priceB).mul(priceA); // 20000e9 SUMR | ||
| } | ||
| } | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| // SPDX-License-Identifier: MIT | ||
| pragma solidity 0.8.28; | ||
|
|
||
| import {UNIT} from "@prb/math/src/Common.sol"; | ||
|
|
||
| // Default number of decimals of the PRB library, used to convert prices to the correct | ||
| // decimals when converting amounts | ||
| uint256 constant DEFAULT_DECIMALS = UNIT; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| // SPDX-License-Identifier: MIT | ||
| pragma solidity 0.8.28; | ||
|
|
||
| import {ud} from "@prb/math/src/UD60x18.sol"; | ||
|
|
||
| import {Price} from "./Types.sol"; | ||
| import {DEFAULT_DECIMALS} from "./Constants.sol"; | ||
|
|
||
| /** | ||
| @notice Creates a Price type from a base and quote amount | ||
|
|
||
| @param baseAmount The amount of the base asset with the given decimals | ||
| @param quoteAmount The amount of the quote asset with the given decimals | ||
|
|
||
| @return The resulting Price type | ||
| */ | ||
| function toPrice( | ||
| uint256 baseAmount, | ||
| uint256 quoteAmount | ||
| ) pure returns (Price memory) { | ||
| return Price({baseAmount: ud(baseAmount), quoteAmount: ud(quoteAmount)}); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| // SPDX-License-Identifier: MIT | ||
| pragma solidity 0.8.28; | ||
|
|
||
| /** | ||
| @notice Normalizes an amount from its original decimals to the target decimals | ||
| @param amount The amount to normalize | ||
| @param amountDecimals The number of decimals of the amount | ||
| @param targetDecimals The target number of decimals | ||
|
|
||
| @return The normalized amount | ||
| */ | ||
| function _normalizeAmount( | ||
| uint256 amount, | ||
| uint8 amountDecimals, | ||
| uint8 targetDecimals | ||
| ) pure returns (uint256) { | ||
| if (amountDecimals > targetDecimals) { | ||
| uint8 exp = amountDecimals - targetDecimals; | ||
| return amount / (10 ** exp); | ||
| } else if (amountDecimals < targetDecimals) { | ||
| uint8 exp = targetDecimals - amountDecimals; | ||
| return amount * (10 ** exp); | ||
| } else { | ||
| return amount; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| // SPDX-License-Identifier: MIT | ||
| pragma solidity 0.8.28; | ||
|
|
||
| import "./Types.sol"; | ||
| import "./Constants.sol"; | ||
| import "./Constructor.sol"; | ||
| import "./Utils.sol"; | ||
| import "./Helpers.sol"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| // SPDX-License-Identifier: MIT | ||
| pragma solidity 0.8.28; | ||
|
|
||
| import {UD60x18, ud, intoUint256} from "@prb/math/src/UD60x18.sol"; | ||
|
|
||
| /** | ||
| The price structure holds the base/quote ratio as well as the decimals of both assets | ||
| to allow for proper conversions between amounts of base and quote assets. | ||
| */ | ||
| struct Price { | ||
| UD60x18 baseAmount; // Amount of base asset | ||
| UD60x18 quoteAmount; // Amount of quote asset | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| // SPDX-License-Identifier: AGPL-3.0-or-later | ||
| pragma solidity 0.8.28; | ||
|
|
||
| import {UD60x18, ud, intoUint256} from "@prb/math/src/UD60x18.sol"; | ||
| import {Price} from "./Types.sol"; | ||
| import {toPrice} from "./Constructor.sol"; | ||
|
|
||
| /** | ||
| @title PriceUtils | ||
|
|
||
| @author Roberto Cano <robercano> | ||
|
|
||
| @notice Utility library to manage prices in Solidity. The prices use the convention of base and quote assets, | ||
| where the price is expressed as how much quote asset is needed to buy one unit of the base asset. | ||
|
|
||
| In this sense a typical listed price of ETH/USD = 2000 means that 2000 USD (quote) are needed to buy 1 ETH (base). | ||
|
|
||
| This is contrary to the mathematical convention of price = base/quote, but it is more aligned with how prices are | ||
| typically represented in financial markets. | ||
|
|
||
| An example of this is a price of ETH/USD = 2000, which means that the price is 2000 USD per ETH, which would be represented | ||
| mathematically as 1/2000 = 0.0005 ETH per USD. | ||
| */ | ||
| library PriceUtils { | ||
| using PriceUtils for Price; | ||
|
|
||
| /** | ||
| @notice Inverts a given Price type, swapping base and quote amounts and decimals | ||
|
|
||
| @param price The Price type to invert | ||
|
|
||
| @return The inverted Price type | ||
|
|
||
| @dev Used to convert from base/quote to quote/base representation | ||
| */ | ||
| function invert(Price memory price) internal pure returns (Price memory) { | ||
| return | ||
| toPrice( | ||
| intoUint256(price.quoteAmount), | ||
| intoUint256(price.baseAmount) | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| @notice Given an amount of quote asset it calculates how much amount of the base | ||
| asset will be received at the given price rate | ||
|
|
||
| @param price The price rate of base/quote | ||
| @param amount The amount of quote asset to convert, as a uint256 | ||
|
|
||
| @return The amount of base asset that will be received | ||
| */ | ||
| function quote( | ||
| Price memory price, | ||
| uint256 amount | ||
| ) internal pure returns (uint256) { | ||
| return | ||
| intoUint256( | ||
| ud(amount).mul(price.baseAmount).div(price.quoteAmount) | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| @notice Multiplies an amount by a price, effectively quoting the amount from quote asset to base asset | ||
|
|
||
| @param amount The amount of quote asset to convert, as a uint256 | ||
| @param price The price rate of base/quote | ||
|
|
||
| @return The amount of base asset that will be received | ||
|
|
||
| @dev This is a convenience function that calls .quote() with the parameters reversed so that it | ||
| can be chained: | ||
|
|
||
| uint256 baseAmount = priceA.quote(amountA).mul(priceB); | ||
| */ | ||
| function mul( | ||
| uint256 amount, | ||
| Price memory price | ||
| ) internal pure returns (uint256) { | ||
| return quote(price, amount); | ||
| } | ||
|
|
||
| /** | ||
| @notice Divides an amount by a price, effectively quoting the amount from base asset to | ||
| quote asset | ||
|
|
||
| @param amount The amount of base asset to convert, as a uint256 | ||
| @param price The price rate of base/quote | ||
|
|
||
| @return The amount of quote asset that will be received | ||
|
|
||
| @dev This is a convenience function that calls .invert().quote() with the parameters reversed | ||
| so that it can be chained: | ||
|
|
||
| uint256 quoteAmount = priceA.invert().quote(amountA).div(priceB); | ||
| */ | ||
| function div( | ||
| uint256 amount, | ||
| Price memory price | ||
| ) internal pure returns (uint256) { | ||
| return price.invert().quote(amount); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| # Full reference https://github.com/foundry-rs/foundry/tree/master/crates/config | ||
|
|
||
| [profile.default] | ||
| src = "src" | ||
| out = "out" | ||
| libs = ["node_modules"] | ||
| solc = "0.8.28" | ||
| evm_version = "cancun" | ||
| cbor_metadata = true | ||
| viaIR = false | ||
| fs_permissions = [ | ||
| { access = "read-write", path = "./utils/expected_prices.json"} | ||
| ] | ||
|
|
||
| [profile.ci] | ||
| fuzz = { runs = 10_000 } | ||
| verbosity = 4 | ||
|
|
||
| [etherscan] | ||
| arbitrum = { key = "${API_KEY_ARBISCAN}" } | ||
| avalanche = { key = "${API_KEY_SNOWTRACE}" } | ||
| base = { key = "${API_KEY_BASESCAN}" } | ||
| gnosis_chain = { key = "${API_KEY_GNOSISSCAN}" } | ||
| goerli = { key = "${API_KEY_ETHERSCAN}" } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Goerli testnet deprecated. Goerli reached EOL in March 2023. Consider removing these references or replacing with Holesky. Also applies to: 46-46 🤖 Prompt for AI Agents |
||
| mainnet = { key = "${API_KEY_ETHERSCAN}" } | ||
| optimism = { key = "${API_KEY_OPTIMISTIC_ETHERSCAN}" } | ||
| polygon = { key = "${API_KEY_POLYGONSCAN}" } | ||
| sepolia = { key = "${API_KEY_ETHERSCAN}" } | ||
|
|
||
| [fmt] | ||
| bracket_spacing = true | ||
| int_types = "long" | ||
| line_length = 120 | ||
| multiline_func_header = "all" | ||
| number_underscore = "thousands" | ||
| quote_style = "double" | ||
| tab_width = 4 | ||
| wrap_comments = true | ||
| sort_imports = true | ||
|
|
||
| [rpc_endpoints] | ||
| arbitrum = "https://arbitrum-mainnet.infura.io/v3/${API_KEY_INFURA}" | ||
| avalanche = "https://avalanche-mainnet.infura.io/v3/${API_KEY_INFURA}" | ||
| base = "https://mainnet.base.org" | ||
| gnosis_chain = "https://rpc.gnosischain.com" | ||
| goerli = "https://goerli.infura.io/v3/${API_KEY_INFURA}" | ||
| localhost = "http://localhost:8545" | ||
| mainnet = "https://eth-mainnet.g.alchemy.com/v2/${API_KEY_ALCHEMY}" | ||
| optimism = "https://optimism-mainnet.infura.io/v3/${API_KEY_INFURA}" | ||
| polygon = "https://polygon-mainnet.infura.io/v3/${API_KEY_INFURA}" | ||
| sepolia = "https://sepolia.infura.io/v3/${API_KEY_INFURA}" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| TN: | ||
| SF:src/PercentageUtils.sol | ||
| FN:20,PercentageUtils.addPercentage | ||
| FNDA:1,PercentageUtils.addPercentage | ||
| DA:24,1 | ||
| FN:35,PercentageUtils.subtractPercentage | ||
| FNDA:1,PercentageUtils.subtractPercentage | ||
| DA:39,1 | ||
| FN:50,PercentageUtils.applyPercentage | ||
| FNDA:3,PercentageUtils.applyPercentage | ||
| DA:54,3 | ||
| DA:55,3 | ||
| DA:56,3 | ||
| FN:66,PercentageUtils.isPercentageInRange | ||
| FNDA:4,PercentageUtils.isPercentageInRange | ||
| DA:69,4 | ||
| FN:80,PercentageUtils.fromFraction | ||
| FNDA:1,PercentageUtils.fromFraction | ||
| DA:84,1 | ||
| FN:94,PercentageUtils.fromIntegerPercentage | ||
| FNDA:8,PercentageUtils.fromIntegerPercentage | ||
| DA:97,8 | ||
| FNF:6 | ||
| FNH:6 | ||
| LF:8 | ||
| LH:8 | ||
| BRF:0 | ||
| BRH:0 | ||
| end_of_record |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Guard exponent overflow in scaling.
10 ** expoverflows forexp > 77, causing revert. Add a bound check with a clear error.Proposed fix
🤖 Prompt for AI Agents