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

Feat/enable hooks sor #896

Draft
wants to merge 4 commits into
base: v3-canary
Choose a base branch
from
Draft
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
132 changes: 132 additions & 0 deletions modules/sor/balancer-sor.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
prismaPoolFactory,
prismaPoolTokenDynamicDataFactory,
prismaPoolTokenFactory,
hookDataFactory,
hookFactory
} from '../../test/factories';
import { createTestClient, formatEther, Hex, http, parseEther, TestClient } from 'viem';
import { sepolia } from 'viem/chains';
Expand Down Expand Up @@ -102,6 +104,7 @@ describe('Balancer SOR Integration Tests', () => {
amountIn,
[prismaWeightedPool],
protocolVersion,
[],
)) as PathWithAmount[];

// build SDK swap from SOR paths
Expand Down Expand Up @@ -177,6 +180,7 @@ describe('Balancer SOR Integration Tests', () => {
amountIn,
[prismaStablePool],
protocolVersion,
[],
)) as PathWithAmount[];

const swapPaths: Path[] = paths.map((path) => ({
Expand Down Expand Up @@ -287,6 +291,7 @@ describe('Balancer SOR Integration Tests', () => {
amountIn,
[nestedPool, weightedPool],
protocolVersion,
[],
)) as PathWithAmount[];

const swapPaths: Path[] = paths.map((path) => ({
Expand Down Expand Up @@ -338,6 +343,7 @@ describe('Balancer SOR Integration Tests', () => {
amountIn,
[nestedPool, weightedPool],
protocolVersion,
[],
)) as PathWithAmount[];

const swapPaths: Path[] = paths.map((path) => ({
Expand Down Expand Up @@ -416,6 +422,7 @@ describe('Balancer SOR Integration Tests', () => {
amountIn,
[prismaStablePool],
protocolVersion,
[],
)) as PathWithAmount[];

const swapPaths: Path[] = paths.map((path) => ({
Expand Down Expand Up @@ -448,6 +455,131 @@ describe('Balancer SOR Integration Tests', () => {
});
});

describe('Stable Pool Path with hooks', async () => {

beforeAll(async() => {
// setup mock pool data
const poolAddress = '0x302b75a27e5e157f93c679dd7a25fdfcdbc1473c';
const stataUSDC = prismaPoolTokenFactory.build({
address: '0x8a88124522dbbf1e56352ba3de1d9f78c143751e',
token: { decimals: 6 },
dynamicData: prismaPoolTokenDynamicDataFactory.build({
balance: '500',
priceRate: '1.046992819427282715',
}),
});
const stataDAI = prismaPoolTokenFactory.build({
address: '0xde46e43f46ff74a23a65ebb0580cbe3dfe684a17',
token: { decimals: 18 },
dynamicData: prismaPoolTokenDynamicDataFactory.build({
balance: '500',
priceRate: '1.101882285912091736',
}),
});
const prismaStablePool = prismaPoolFactory.stable('1000').build({
address: poolAddress,
tokens: [stataUSDC, stataDAI],
dynamicData: prismaPoolDynamicDataFactory.build({
totalShares: '1054.451151293881721519',
swapFee: '0.01',
}),
});


// mock api data for hooks.
const dynamicData = hookDataFactory.build({
// Add any specific dynamic data parameters here
addLiquidityFeePercentage: '0.01',
removeLiquidityFeePercentage: '0.01',
swapFeePercentage: '0.01'
});


// Create the Hook instance
const prismaHook1 = hookFactory.build({
dynamicData: dynamicData,
enableHookAdjustedAmounts: true,
poolsIds: [poolAddress, '0x102b75a27e5e157f93c679dd7a25fdfcdbc1473c'],
shouldCallAfterAddLiquidity: true,
shouldCallAfterInitialize: true,
shouldCallAfterRemoveLiquidity: true,
shouldCallAfterSwap: true,
shouldCallBeforeAddLiquidity: true,
shouldCallBeforeInitialize: true,
shouldCallBeforeRemoveLiquidity: true,
shouldCallBeforeSwap: true,
shouldCallComputeDynamicSwapFee: true,
});

// Create the Hook instance
const prismaHook2 = hookFactory.build({
dynamicData: dynamicData,
enableHookAdjustedAmounts: true,
poolsIds: ['0x102b75a27e5e157f93c679dd6a25fdfcdbc1473f', '0x102b75a17e5e157f93c679dd7a25fdfcdbc1473c'],
shouldCallAfterAddLiquidity: true,
shouldCallAfterInitialize: true,
shouldCallAfterRemoveLiquidity: true,
shouldCallAfterSwap: true,
shouldCallBeforeAddLiquidity: true,
shouldCallBeforeInitialize: true,
shouldCallBeforeRemoveLiquidity: true,
shouldCallBeforeSwap: true,
shouldCallComputeDynamicSwapFee: true,
});




// get SOR paths
const tIn = new Token(
parseFloat(chainToIdMap[stataUSDC.token.chain]),
stataUSDC.address as Address,
stataUSDC.token.decimals,
);
const tOut = new Token(
parseFloat(chainToIdMap[stataDAI.token.chain]),
stataDAI.address as Address,
stataDAI.token.decimals,
);
const amountIn = BigInt(1000e6);
paths = (await sorGetPathsWithPools(
tIn,
tOut,
SwapKind.GivenIn,
amountIn,
[prismaStablePool],
protocolVersion,
[prismaHook1, prismaHook2],
)) as PathWithAmount[];

const swapPaths: Path[] = paths.map((path) => ({
protocolVersion,
inputAmountRaw: path.inputAmount.amount,
outputAmountRaw: path.outputAmount.amount,
tokens: path.tokens.map((token) => ({
address: token.address,
decimals: token.decimals,
})),
pools: path.pools.map((pool) => pool.id),
}));

// build SDK swap from SOR paths
sdkSwap = new Swap({
chainId: parseFloat(chainToIdMap['SEPOLIA']),
paths: swapPaths,
swapKind: SwapKind.GivenIn,
});
})

test('SOR quote should match swap query', async () => {
const returnAmountSOR = getOutputAmount(paths);
const queryOutput = await sdkSwap.query(rpcUrl);
const returnAmountQuery = (queryOutput as ExactInQueryOutput).expectedAmountOut;
expect(returnAmountQuery.amount).toEqual(returnAmountSOR.amount);
});
});


afterAll(async () => {
await stopAnvilForks();
});
Expand Down
3 changes: 2 additions & 1 deletion modules/sor/sorV2/lib/poolsV2/basePool.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BufferState, PoolState } from '@balancer-labs/balancer-maths';
import { BufferState, PoolState, HookState } from '@balancer-labs/balancer-maths';

Check failure on line 1 in modules/sor/sorV2/lib/poolsV2/basePool.ts

View workflow job for this annotation

GitHub Actions / Build

Module '"@balancer-labs/balancer-maths"' declares 'HookState' locally, but it is not exported.
import { PoolType, SwapKind, Token, TokenAmount } from '@balancer/sdk';
import { Hex } from 'viem';
import { BasePoolToken } from './basePoolToken';
Expand All @@ -23,4 +23,5 @@
export interface BasePoolV3 extends BasePool {
tokens: (BasePoolToken | Erc4626PoolToken)[];
getPoolState(): PoolState | BufferState;
getHookState(): HookState | undefined;
}
101 changes: 84 additions & 17 deletions modules/sor/sorV2/lib/poolsV3/stable/stablePool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { parseEther, parseUnits } from 'viem';

import { PrismaPoolWithDynamic } from '../../../../../../prisma/prisma-types';
import { PrismaPoolWithDynamic, PrismaHookWithDynamic } from '../../../../../../prisma/prisma-types';
import { WAD } from '../../utils/math';
import { StablePool } from './stablePool';

Expand All @@ -13,7 +13,10 @@ import {
prismaPoolFactory,
prismaPoolTokenDynamicDataFactory,
prismaPoolTokenFactory,
hookFactory,
hookDataFactory,
} from '../../../../../../test/factories';
import { stable } from '../../../../../pool/pool-data';

describe('SOR V3 Stable Pool Tests', () => {
let amp: string;
Expand All @@ -27,7 +30,39 @@ describe('SOR V3 Stable Pool Tests', () => {
let tokenRates: string[];
let totalShares: string;

beforeAll(() => {
test('Get Pool State', () => {
setupStablePool(false);
const poolState = {
poolType: 'Stable',
swapFee: parseEther(swapFee),
balancesLiveScaled18: tokenBalances.map((b) => parseEther(b)),
tokenRates: tokenRates.map((r) => parseEther(r)),
totalSupply: parseEther(totalShares),
amp: parseUnits(amp, 3),
tokens: tokenAddresses,
scalingFactors,
aggregateSwapFee: 0n
};
expect(poolState).toEqual(stablePool.getPoolState());
});

test('Get hook State hook attached', () => {
// true means that the stable pool has a hook attached in this test
setupStablePool(true);
const hookState = {
tokens: tokenAddresses,
removeLiquidityHookFeePercentage: BigInt(1e16) //'0.01' %
}
expect(hookState).toEqual(stablePool.getHookState());
})

test('Get hook State no hook attached', () => {
// false means that the stable pool has no hook attached in this test
setupStablePool(false);
expect(stablePool.getHookState()).toBeUndefined();
})

const setupStablePool = (hooks: boolean) => {
swapFee = '0.01';
tokenBalances = ['169', '144'];
tokenDecimals = [6, 18];
Expand Down Expand Up @@ -62,20 +97,52 @@ describe('SOR V3 Stable Pool Tests', () => {
tokens: [poolToken1, poolToken2],
dynamicData: prismaPoolDynamicDataFactory.build({ swapFee, totalShares }),
});
stablePool = StablePool.fromPrismaPool(stablePrismaPool);
});
if (!hooks) {
stablePool = StablePool.fromPrismaPool(stablePrismaPool, []);
} else {

test('Get Pool State', () => {
const poolState = {
poolType: 'Stable',
swapFee: parseEther(swapFee),
balancesLiveScaled18: tokenBalances.map((b) => parseEther(b)),
tokenRates: tokenRates.map((r) => parseEther(r)),
totalSupply: parseEther(totalShares),
amp: parseUnits(amp, 3),
tokens: tokenAddresses,
scalingFactors,
};
expect(poolState).toEqual(stablePool.getPoolState());
});
// create hooks here due to needing to pass stable pool address
// The stable pool has a hook attached in this test
const dynamicData = hookDataFactory.build({
// Add any specific dynamic data parameters here
addLiquidityFeePercentage: '0.01',
removeLiquidityFeePercentage: '0.01',
swapFeePercentage: '0.01'
});

// Create the Hook instance
const prismaHook1 = hookFactory.build({
dynamicData: dynamicData,
enableHookAdjustedAmounts: true,
poolsIds: [stablePrismaPool.address, '0x102b75a27e5e157f93c679dd7a25fdfcdbc1473c'],
shouldCallAfterAddLiquidity: true,
shouldCallAfterInitialize: true,
shouldCallAfterRemoveLiquidity: true,
shouldCallAfterSwap: true,
shouldCallBeforeAddLiquidity: true,
shouldCallBeforeInitialize: true,
shouldCallBeforeRemoveLiquidity: true,
shouldCallBeforeSwap: true,
shouldCallComputeDynamicSwapFee: true,
});

// Create the Hook instance
const prismaHook2 = hookFactory.build({
dynamicData: dynamicData,
enableHookAdjustedAmounts: true,
poolsIds: ['0x102b75a27e5e157f93c679dd6a25fdfcdbc1473f', '0x102b75a17e5e157f93c679dd7a25fdfcdbc1473c'],
shouldCallAfterAddLiquidity: true,
shouldCallAfterInitialize: true,
shouldCallAfterRemoveLiquidity: true,
shouldCallAfterSwap: true,
shouldCallBeforeAddLiquidity: true,
shouldCallBeforeInitialize: true,
shouldCallBeforeRemoveLiquidity: true,
shouldCallBeforeSwap: true,
shouldCallComputeDynamicSwapFee: true,
});

stablePool = StablePool.fromPrismaPool(stablePrismaPool, [prismaHook1, prismaHook2]);
}
}
});
Loading
Loading