Skip to content
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

fix: scale reserves to 18 decimals #41

Merged
merged 3 commits into from
Oct 18, 2022
Merged
Changes from 2 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
26 changes: 15 additions & 11 deletions src/uniswap/UniV2LPOracle.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {IERC20} from "../utils/IERC20.sol";
import {IOracle} from "../core/IOracle.sol";
import {IUniswapV2Pair} from "./IUniswapV2Pair.sol";
import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol";
import "forge-std/console.sol";
r0ohafza marked this conversation as resolved.
Show resolved Hide resolved

/**
@title Uniswap v2 LP Oracle
@notice Price oracle for uniswap v2 LP Tokens
Expand Down Expand Up @@ -41,23 +43,25 @@ contract UniV2LpOracle is IOracle {
address token0 = IUniswapV2Pair(pair).token0();
address token1 = IUniswapV2Pair(pair).token1();

uint decimalSum = IERC20(token0).decimals() + IERC20(token1).decimals();
(uint r0, uint r1,) = IUniswapV2Pair(pair).getReserves();

uint decimals0 = IERC20(token0).decimals();
uint decimals1 = IERC20(token1).decimals();

uint scale;
if (decimalSum > 18) scale = decimalSum - 18;
if (decimals0 <= 18)
r0 = r0 * 10 ** (18 - decimals0);
else r0 = r0 / 10 ** (decimals0 - 18);

(uint r0, uint r1,) = IUniswapV2Pair(pair).getReserves();
if (decimals1 <= 18)
r1 = r1 * 10 ** (18 - decimals1);
else r1 = r1 / 10 ** (decimals1 - 18);

// 2 * sqrt(r0 * r1 * p0 * p1) / totalSupply
return FixedPointMathLib.sqrt(
r0
.mulDivDown(r1, 10 ** scale)
.mulDivDown(
oracle.getPrice(token0),
(scale == 0 ? 10 ** decimalSum : 1e18)
)
.mulWadDown(r1)
.mulWadDown(oracle.getPrice(token0))
.mulWadDown(oracle.getPrice(token1))
)
.mulDivDown(2e27, IUniswapV2Pair(pair).totalSupply());
).mulDivDown(2e27, IUniswapV2Pair(pair).totalSupply());
}
}