Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/price-utils/.editorconfig
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
14 changes: 14 additions & 0 deletions packages/price-utils/.gitpod.yml
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"
6 changes: 6 additions & 0 deletions packages/price-utils/.solhint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
18 changes: 18 additions & 0 deletions packages/price-utils/LICENSE.md
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.
67 changes: 67 additions & 0 deletions packages/price-utils/README.md
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
}
}
```
8 changes: 8 additions & 0 deletions packages/price-utils/contracts/Constants.sol
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;
22 changes: 22 additions & 0 deletions packages/price-utils/contracts/Constructor.sol
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)});
}
26 changes: 26 additions & 0 deletions packages/price-utils/contracts/Helpers.sol
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);
Comment on lines +17 to +22
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard exponent overflow in scaling.
10 ** exp overflows for exp > 77, causing revert. Add a bound check with a clear error.

Proposed fix
+error DecimalsOverflow(uint8 amountDecimals, uint8 targetDecimals);
+
 function _normalizeAmount(
     uint256 amount,
     uint8 amountDecimals,
     uint8 targetDecimals
 ) pure returns (uint256) {
     if (amountDecimals > targetDecimals) {
         uint8 exp = amountDecimals - targetDecimals;
+        if (exp > 77) revert DecimalsOverflow(amountDecimals, targetDecimals);
         return amount / (10 ** exp);
     } else if (amountDecimals < targetDecimals) {
         uint8 exp = targetDecimals - amountDecimals;
+        if (exp > 77) revert DecimalsOverflow(amountDecimals, targetDecimals);
         return amount * (10 ** exp);
     } else {
         return amount;
     }
 }
🤖 Prompt for AI Agents
In `@packages/price-utils/contracts/Helpers.sol` around lines 17 - 22, The
exponentiation 10 ** exp can overflow for exp > 77; add a guard that requires
exp <= 77 (or a safe max) before computing 10 ** exp and revert with a clear
error message; apply this check in both branches where exp is computed (the
branch comparing amountDecimals and targetDecimals, referencing the local
variable exp and the surrounding function in Helpers.sol) so the function
validates the bound before performing the multiplication/division.

} else {
return amount;
}
}
8 changes: 8 additions & 0 deletions packages/price-utils/contracts/PriceUtils.sol
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";
13 changes: 13 additions & 0 deletions packages/price-utils/contracts/Types.sol
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
}
103 changes: 103 additions & 0 deletions packages/price-utils/contracts/Utils.sol
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);
}
}
51 changes: 51 additions & 0 deletions packages/price-utils/foundry.toml
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}" }
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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
In `@packages/price-utils/foundry.toml` at line 24, The TOML contains a deprecated
goerli network entry (goerli = { key = "${API_KEY_ETHERSCAN}" }); remove or
replace it with the current Holesky network entry (e.g., holesky = { key =
"${API_KEY_ETHERSCAN}" }) and update any other identical occurrences mentioned
(the second occurrence at the other location) so references and env usage remain
consistent; ensure you only change the network name(s) and preserve the API key
variable name unless you also plan to rename the env var.

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}"
29 changes: 29 additions & 0 deletions packages/price-utils/lcov.info
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
Loading
Loading