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

Upgrade core #3

Merged
merged 2 commits into from
Jun 22, 2022
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
artifacts/
node_modules/
typechain/
cache/
cache/
foundry-out/
lib/
29 changes: 17 additions & 12 deletions contracts/hooks/GeomeanOracle.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
pragma solidity =0.8.13;

import {IPoolManager} from '@uniswap/core-next/contracts/interfaces/IPoolManager.sol';
import {PoolId} from '@uniswap/core-next/contracts/libraries/PoolId.sol';
import {Hooks} from '@uniswap/core-next/contracts/libraries/Hooks.sol';
import {TickMath} from '@uniswap/core-next/contracts/libraries/TickMath.sol';
import {Oracle} from '@uniswap/core-next/contracts/libraries/Oracle.sol';
Expand All @@ -12,6 +13,7 @@ import {BaseHook} from '@uniswap/core-next/contracts/hooks/base/BaseHook.sol';
/// for protocols that wish to use a V3 style geomean oracle.
contract GeomeanOracle is BaseHook {
using Oracle for Oracle.Observation[65535];
using PoolId for IPoolManager.PoolKey;

/// @notice Oracle pools do not have fees because they exist to serve as an oracle for a pair of tokens
error OnlyOneOraclePoolAllowed();
Expand Down Expand Up @@ -75,30 +77,31 @@ contract GeomeanOracle is BaseHook {
address,
IPoolManager.PoolKey calldata key,
uint160
) external view override poolManagerOnly {
) external view override poolManagerOnly returns (bytes4) {
// This is to limit the fragmentation of pools using this oracle hook. In other words,
// there may only be one pool per pair of tokens that use this hook. The tick spacing is set to the maximum
// because we only allow max range liquidity in this pool.
if (key.fee != 0 || key.tickSpacing != poolManager.MAX_TICK_SPACING()) revert OnlyOneOraclePoolAllowed();
return GeomeanOracle.beforeInitialize.selector;
}

function afterInitialize(
address,
IPoolManager.PoolKey calldata key,
uint160,
int24
) external override poolManagerOnly {
bytes32 id = keccak256(abi.encode(key));
) external override poolManagerOnly returns (bytes4) {
bytes32 id = key.toId();
(states[id].cardinality, states[id].cardinalityNext) = observations[id].initialize(_blockTimestamp());
return GeomeanOracle.afterInitialize.selector;
}

/// @dev Called before any action that potentially modifies pool price or liquidity, such as swap or modify position
function _updatePool(IPoolManager.PoolKey calldata key) private {
(, int24 tick) = poolManager.getSlot0(key);

uint128 liquidity = poolManager.getLiquidity(key);
bytes32 id = key.toId();
(, int24 tick, ) = poolManager.getSlot0(id);

bytes32 id = keccak256(abi.encode(key));
uint128 liquidity = poolManager.getLiquidity(id);

(states[id].index, states[id].cardinality) = observations[id].write(
states[id].index,
Expand All @@ -114,22 +117,24 @@ contract GeomeanOracle is BaseHook {
address,
IPoolManager.PoolKey calldata key,
IPoolManager.ModifyPositionParams calldata params
) external override poolManagerOnly {
) external override poolManagerOnly returns (bytes4) {
if (params.liquidityDelta < 0) revert OraclePoolMustLockLiquidity();
int24 maxTickSpacing = poolManager.MAX_TICK_SPACING();
if (
params.tickLower != TickMath.minUsableTick(maxTickSpacing) ||
params.tickUpper != TickMath.maxUsableTick(maxTickSpacing)
) revert OraclePositionsMustBeFullRange();
_updatePool(key);
return GeomeanOracle.beforeModifyPosition.selector;
}

function beforeSwap(
address,
IPoolManager.PoolKey calldata key,
IPoolManager.SwapParams calldata
) external override poolManagerOnly {
) external override poolManagerOnly returns (bytes4) {
_updatePool(key);
return GeomeanOracle.beforeSwap.selector;
}

/// @notice Observe the given pool for the timestamps
Expand All @@ -138,13 +143,13 @@ contract GeomeanOracle is BaseHook {
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
{
bytes32 id = keccak256(abi.encode(key));
bytes32 id = key.toId();

ObservationState memory state = states[id];

(, int24 tick) = poolManager.getSlot0(key);
(, int24 tick, ) = poolManager.getSlot0(id);

uint128 liquidity = poolManager.getLiquidity(key);
uint128 liquidity = poolManager.getLiquidity(id);

return
observations[id].observe(_blockTimestamp(), secondsAgos, tick, state.index, liquidity, state.cardinality);
Expand Down
54 changes: 29 additions & 25 deletions contracts/hooks/LimitOrderHook.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
pragma solidity =0.8.13;

import {IPoolManager} from '@uniswap/core-next/contracts/interfaces/IPoolManager.sol';
import {PoolId} from '@uniswap/core-next/contracts/libraries/PoolId.sol';
import {Hooks} from '@uniswap/core-next/contracts/libraries/Hooks.sol';
import {FullMath} from '@uniswap/core-next/contracts/libraries/FullMath.sol';
import {SafeCast} from '@uniswap/core-next/contracts/libraries/SafeCast.sol';
Expand All @@ -27,6 +28,7 @@ library EpochLibrary {
contract LimitOrderHook is BaseHook {
using SafeCast for uint256;
using EpochLibrary for Epoch;
using PoolId for IPoolManager.PoolKey;

error ZeroLiquidity();
error InRange();
Expand Down Expand Up @@ -91,12 +93,12 @@ contract LimitOrderHook is BaseHook {
);
}

function getTickLowerLast(IPoolManager.PoolKey memory key) public view returns (int24) {
return tickLowerLasts[keccak256(abi.encode(key))];
function getTickLowerLast(bytes32 poolId) public view returns (int24) {
return tickLowerLasts[poolId];
}

function setTickLowerLast(IPoolManager.PoolKey memory key, int24 tickLower) private {
tickLowerLasts[keccak256(abi.encode(key))] = tickLower;
function setTickLowerLast(bytes32 poolId, int24 tickLower) private {
tickLowerLasts[poolId] = tickLower;
}

function getEpoch(
Expand All @@ -120,8 +122,8 @@ contract LimitOrderHook is BaseHook {
return epochInfos[epoch].liquidity[owner];
}

function getTick(IPoolManager.PoolKey memory key) private view returns (int24 tick) {
(, tick) = poolManager.getSlot0(key);
function getTick(bytes32 poolId) private view returns (int24 tick) {
(, tick, ) = poolManager.getSlot0(poolId);
}

function getTickLower(int24 tick, int24 tickSpacing) private pure returns (int24) {
Expand All @@ -135,31 +137,19 @@ contract LimitOrderHook is BaseHook {
IPoolManager.PoolKey calldata key,
uint160,
int24 tick
) external override poolManagerOnly {
setTickLowerLast(key, getTickLower(tick, key.tickSpacing));
) external override poolManagerOnly returns (bytes4) {
setTickLowerLast(key.toId(), getTickLower(tick, key.tickSpacing));
return LimitOrderHook.afterInitialize.selector;
}

function afterSwap(
address,
IPoolManager.PoolKey calldata key,
IPoolManager.SwapParams calldata params,
IPoolManager.BalanceDelta calldata
) external override poolManagerOnly {
int24 tickLower = getTickLower(getTick(key), key.tickSpacing);
int24 tickLowerLast = getTickLowerLast(key);
if (tickLower == tickLowerLast) return;

int24 lower;
int24 upper;
if (tickLower < tickLowerLast) {
// the pool has moved "left", meaning it's traded token1 for token0,
lower = tickLower + key.tickSpacing;
upper = tickLowerLast;
} else {
// the pool has moved "right", meaning it's traded token0 for token1
lower = tickLowerLast;
upper = tickLower - key.tickSpacing;
}
) external override poolManagerOnly returns (bytes4) {
(int24 tickLower, int24 lower, int24 upper) = _getCrossedTicks(key.toId(), key.tickSpacing);
Copy link
Contributor Author

@marktoda marktoda Jun 16, 2022

Choose a reason for hiding this comment

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

was getting stack2deep errors because of the selector return so moved the upper<->lower calc to helper fn

if (lower > upper) return LimitOrderHook.afterSwap.selector;

// note that a zeroForOne swap means that the pool is actually gaining token0, so limit
// order fills are the opposite of swap fills, hence the inversion below
Expand Down Expand Up @@ -189,7 +179,21 @@ contract LimitOrderHook is BaseHook {
}
}

setTickLowerLast(key, tickLower);
setTickLowerLast(key.toId(), tickLower);
return LimitOrderHook.afterSwap.selector;
}

function _getCrossedTicks(bytes32 poolId, int24 tickSpacing) internal view returns (int24 tickLower, int24 lower, int24 upper) {
tickLower = getTickLower(getTick(poolId), tickSpacing);
int24 tickLowerLast = getTickLowerLast(poolId);

if (tickLower < tickLowerLast) {
lower = tickLower + tickSpacing;
upper = tickLowerLast;
} else {
lower = tickLowerLast;
upper = tickLower - tickSpacing;
}
}

function lockAcquiredFill(
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
},
"dependencies": {
"@openzeppelin/contracts": "4.4.2",
"@uniswap/core-next": "git+ssh://git@github.com:Uniswap/core-next.git#43df9917ba606b151420dacfa9a08908256085f8"
"@uniswap/core-next": "git+ssh://git@github.com:Uniswap/core-next.git#50d7873b95218df47bc747d1218a97a29fad494e"
},
"devDependencies": {
"@nomiclabs/hardhat-ethers": "^2.0.2",
Expand Down
6 changes: 3 additions & 3 deletions test/GeomeanOracle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { MockTimeGeomeanOracle, IPoolManager, PoolModifyPositionTest, TestERC20
import { MAX_TICK_SPACING } from './shared/constants'
import { expect } from './shared/expect'
import { tokensFixture } from './shared/fixtures'
import { createHookMask, encodeSqrtPriceX96, getMaxTick, getMinTick } from './shared/utilities'
import { createHookMask, encodeSqrtPriceX96, getMaxTick, getMinTick, getPoolId } from './shared/utilities'

describe('GeomeanOracle', () => {
let wallets: Wallet[]
Expand Down Expand Up @@ -47,7 +47,7 @@ describe('GeomeanOracle', () => {
return (await waffle.deployContract(wallet, {
bytecode: V4_POOL_MANAGER_BYTECODE,
abi: V4_POOL_MANAGER_ABI,
})) as IPoolManager
}, [10000])) as IPoolManager
}

const fixture = async ([wallet]: Wallet[]) => {
Expand Down Expand Up @@ -126,7 +126,7 @@ describe('GeomeanOracle', () => {
let snapshotId: string

beforeEach('check the pool is not initialized', async () => {
const { sqrtPriceX96 } = await poolManager.getSlot0(poolKey)
const { sqrtPriceX96 } = await poolManager.getSlot0(getPoolId(poolKey))
expect(sqrtPriceX96, 'pool is not initialized').to.eq(0)
// it seems like the waffle fixture is not working correctly (perhaps due to hardhat_setCode), and if we don't do this and revert in afterEach, the pool is already initialized
snapshotId = await hre.network.provider.send('evm_snapshot')
Expand Down
Loading