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

Add Add/Remove Liquidity #91

Merged
merged 244 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
244 commits
Select commit Hold shift + click to select a range
91b735b
WIP Join implementation.
johngrantuk Aug 3, 2023
f297e2b
Initial suggestion for join implementation structure (WIP)
brunoguerios Aug 29, 2023
7e4bd2e
Minor refactor to apply code review suggestions
brunoguerios Aug 30, 2023
6be1c05
Add encoders and query
brunoguerios Aug 30, 2023
71315d2
Refactor the code to use pool address instead of pool id
brunoguerios Aug 30, 2023
e264a8b
Fix lint errors
brunoguerios Aug 30, 2023
2c423b6
Refactor WeightedPoolEncoder to WeightedEncoder
brunoguerios Aug 31, 2023
fc845e7
Add decimals to tokens on PoolState
brunoguerios Aug 31, 2023
cce91bf
Update integration test with TestClient from viem
brunoguerios Aug 31, 2023
eb34419
Update viem to v1.9.3
brunoguerios Aug 31, 2023
41a7d6f
Add integration test (wip)
brunoguerios Aug 31, 2023
8747aa2
Add helpers to test
brunoguerios Sep 1, 2023
6733647
Refactor test to improve readability
brunoguerios Sep 1, 2023
feda776
Add Slippage helper class
brunoguerios Sep 1, 2023
dfb113f
Expose slippage entity
brunoguerios Sep 1, 2023
443ec16
Add hardhat to dev dependencies so we're able to run local fork for t…
brunoguerios Sep 4, 2023
29fa180
Add comments to test file
brunoguerios Sep 4, 2023
92438bf
Fix encoders issues
brunoguerios Sep 5, 2023
24adcc7
Rename join inputs to make interface more intuitive (wip)
brunoguerios Sep 6, 2023
c401a48
Rename join inputs to make interface more intuitive
brunoguerios Sep 6, 2023
18af0b1
Rearrange join related types
brunoguerios Sep 6, 2023
0995200
Run local fork in background before github checks
brunoguerios Sep 6, 2023
ecbdf1f
Add join with native assets
brunoguerios Sep 6, 2023
9f9935b
Refactor join with native asset interface
brunoguerios Sep 8, 2023
c95d21e
Refactor join types to match contract interface
brunoguerios Sep 8, 2023
4745d30
Refactor encoder functions to make them more explicit
brunoguerios Sep 8, 2023
e20724d
Refactor tokens to use basic types instead of Token class
brunoguerios Sep 11, 2023
03e3bff
Remove unnecessary getInstance method
brunoguerios Sep 11, 2023
e645593
Add setTokenBalance helper
brunoguerios Sep 12, 2023
606c210
Add exactOut integration tests
brunoguerios Sep 12, 2023
c2c8030
Add findTokenBalanceSlot helper
brunoguerios Sep 12, 2023
c0edb27
Add forkSetup to test helper
brunoguerios Sep 12, 2023
aef4026
Add comments describing helper methods
brunoguerios Sep 12, 2023
3cafa27
refactor: Fix typos in weightedEncoder.
johngrantuk Sep 13, 2023
294c082
feat: Initial Exit functionality and Weighted Pool implementation.
johngrantuk Sep 13, 2023
7a52426
Rename join kind to follow convention decided by the team
brunoguerios Sep 13, 2023
2ece720
Add initial structure to check inputs
brunoguerios Sep 13, 2023
4d49b3f
Use index provided by the api to sort pool tokens
brunoguerios Sep 13, 2023
ced8f97
chore: Merge changes from Join.
johngrantuk Sep 14, 2023
fb58e4c
Apply code review suggestions
brunoguerios Sep 14, 2023
3900067
Remove unused comment
brunoguerios Sep 14, 2023
e0722d9
refactor: Separate functions that may be common to other pool types s…
johngrantuk Sep 14, 2023
914e236
chore: Merge main branch and fix conflicts.
johngrantuk Sep 14, 2023
0d2271f
Rename joinWtihNativeAsset to useNativeAssetAsWrappedAmountIn
brunoguerios Sep 18, 2023
c55ce89
refactor: Address review comments.
johngrantuk Sep 19, 2023
fe067bc
chore: Merge join and fix conflicts.
johngrantuk Sep 19, 2023
8f64c6a
refactor: Single point to santise tokens in check.
johngrantuk Sep 19, 2023
42b1e7b
chore: Merge refactor branch and fix conflicts.
johngrantuk Sep 19, 2023
45d76dd
chore: Merge common refactor branch and fix conflicts.
johngrantuk Sep 19, 2023
71d1872
fix: Native asset exit test and functionality.
johngrantuk Sep 19, 2023
b801f74
Merge pull request #94 from balancer/refactor-common-pools
johngrantuk Sep 20, 2023
2d755f8
refactor: Add isSameAddress to Token to keep sanitising consistent.
johngrantuk Sep 20, 2023
5ea7e26
feat: Add validation for weightedExit inputs.
johngrantuk Sep 20, 2023
18796f1
Merge branch 'join' into refactor-tests
johngrantuk Sep 20, 2023
41b9569
refactor: Move constants.
johngrantuk Sep 20, 2023
99fe390
refactor: WeightedExit test.
johngrantuk Sep 20, 2023
bccfda9
refactor: Weighted Join tests.
johngrantuk Sep 20, 2023
368f3d9
fix: Handle native assets correctly on join.
johngrantuk Sep 20, 2023
fe3cc45
Move input validation to a higher level to simplify the individual im…
danielmkm Sep 21, 2023
80c339b
remove parser
danielmkm Sep 21, 2023
ccef327
refactor: Update naming.
johngrantuk Sep 21, 2023
346cb9d
Merge pull request #95 from balancer/refactor-tests
johngrantuk Sep 21, 2023
f8ede7c
Merge pull request #93 from balancer/exit
johngrantuk Sep 21, 2023
986988a
Merge branch 'join' into exit-refactor
johngrantuk Sep 21, 2023
78dc6dc
chore: Fix liniting.
johngrantuk Sep 21, 2023
e0e044b
chore: Fix imports, types for joins.
johngrantuk Sep 21, 2023
49be636
fix: Circular dep issue when exporting PoolExit.
johngrantuk Sep 21, 2023
d6674ab
fix: Change test to use new PoolExit instead of parser.
johngrantuk Sep 21, 2023
34b6b9e
refactor: Remove poolType input param. Add poolType to query return.
johngrantuk Sep 21, 2023
dfe5577
feat: Change Join to use PoolJoin instead of parser. Updated tests.
johngrantuk Sep 21, 2023
1cee514
fix: Change BuildOutput naming to fix build issue.
johngrantuk Sep 21, 2023
b62ab16
Creating a provider to fetch data from the Balancer API;
Sep 21, 2023
e480e1c
Merge pull request #96 from balancer/exit-refactor
johngrantuk Sep 25, 2023
e1efe6b
Add changeset.
johngrantuk Sep 25, 2023
5702561
Adding Example;
Sep 25, 2023
16376b7
Fixing wrong replacements
Sep 25, 2023
581478e
Changing folder name "balancer-api-provider" to "balancer-api
Sep 25, 2023
8f52f44
[WIP] Creating example for api integration;
Sep 25, 2023
5e01345
Changing "Weighted" to "WEIGHTED" (format that comes from the API);
Sep 26, 2023
1d54c4c
fix: Circular deps.
johngrantuk Sep 26, 2023
d0c1116
Added example for exit;
Sep 26, 2023
50875db
Merge commit 'e1efe6b68f4528287410adb0a7d5782273959b7b' into integrat…
Sep 26, 2023
55eed3b
Removing Parser;
Sep 27, 2023
3862fd5
Merge pull request #98 from balancer/fix-circular-deps
johngrantuk Sep 28, 2023
36e684f
fixing lint errors
Oct 2, 2023
1fbd05e
Changing hardhat to anvil client in tests;
Oct 11, 2023
1948ff3
Created Join for Composable Stable Pools;
Oct 16, 2023
d8ae99b
Installing foundry and running anvil in the github actions;
Oct 17, 2023
c27a526
Fixing script to install foundry
Oct 17, 2023
78be59e
Fixing commands to install foundry (2);
Oct 17, 2023
ee49610
Another try to install foundry;
Oct 17, 2023
b8777fd
using custom bash to install foundry;
Oct 17, 2023
741e78b
no message
Oct 17, 2023
0621250
refreshing bash before running anvil;
Oct 17, 2023
876e9a6
adding foundry to test needs property;
Oct 17, 2023
6a960ca
Yet Another Try to recognize anvil command;
Oct 17, 2023
547984c
Running the Anvil Client in the Foundry tab, hopefully it will recogn…
Oct 17, 2023
3d68f79
replacing wrongly removed environment variables;
Oct 17, 2023
a4981ca
Putting the Foundry in github setup action;
Oct 17, 2023
746dd3f
Fixing foundry setup action;
Oct 17, 2023
13b92f8
fixing wrong parameter "test > needs", foundry no longer exists;
Oct 17, 2023
ac375de
secrets.ETHEREUM_RPC_URL is not available in setup/action.yml, trying…
Oct 17, 2023
7ca52ad
Adding "ComposableStableJoinQueryResult" type;
Oct 17, 2023
2691fdf
Creating composable Stable Exit and integration test;
Oct 18, 2023
2a938d6
Fixing Lint;
Oct 18, 2023
2794e86
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 18, 2023
2fc96f7
Fixing Lint;
Oct 18, 2023
ffeaa9d
fix: Client type in test.
johngrantuk Oct 18, 2023
4687026
chore: Add comment explaining PHANTOM_STABLE naming.
johngrantuk Oct 18, 2023
6a08b5f
Refactor: Join types.
johngrantuk Oct 18, 2023
cb58df9
Setup @viem/anvil for automatic fork setup
agualis Oct 18, 2023
9d6f0ac
mend
agualis Oct 18, 2023
3119a49
Fix lint
agualis Oct 18, 2023
457c50c
Refactor .env vars
agualis Oct 18, 2023
1a7d990
Fix VITE envs in checks.yml
agualis Oct 18, 2023
3dc7efd
chore: Merge main and fix conflicts.
johngrantuk Oct 18, 2023
3c232b0
test: Fix undefined tests.
johngrantuk Oct 18, 2023
b5838d8
Refactoring the types;
Oct 18, 2023
422f42b
bptIndex is mandatory for composable stable pools;
Oct 18, 2023
e0016ab
Running rome lint on all files;
Oct 18, 2023
357d8be
Debug: exclude weighted integration tests
agualis Oct 19, 2023
be6bf80
add threads false to test setup
agualis Oct 19, 2023
1ff65fd
Avoid viem prefix in CI envs
agualis Oct 19, 2023
1e7c494
Clean integration tests
agualis Oct 19, 2023
18151a8
Add weighted tests back
agualis Oct 19, 2023
89ded1b
Bump viem and vitest
agualis Oct 19, 2023
8b7744a
Keep old viem version
agualis Oct 19, 2023
7cf3fd5
Adapting doTransaction to a doJoin function usable for both pool type…
Oct 19, 2023
cffe049
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 19, 2023
72301a3
Merging Weighted and ComposableStable doTransactions into one single …
Oct 19, 2023
ff2132d
Fixing Lint
Oct 19, 2023
0cb5b95
Fixing Lint;
Oct 19, 2023
7ff60c0
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 19, 2023
eaa0218
Merge pull request #109 from balancer/viem-anvil
johngrantuk Oct 20, 2023
d2c181f
Merge branch 'join' into anvil-tests
agualis Oct 20, 2023
a5bc0da
Fix pnpm loclkfile
agualis Oct 20, 2023
f09b572
Merge pull request #103 from balancer/anvil-tests
johngrantuk Oct 20, 2023
e1b71c7
Changing "chainId" type to ChainId instead of number;
Oct 22, 2023
4e98722
Merge commit 'f09b5722cc06807709d041d5450e8018c33de99f' into integrat…
Oct 22, 2023
e9dde1c
Removing unused types file;
Oct 22, 2023
8a3b8d6
Updating pnpm-lock.yaml after merge;
Oct 22, 2023
b3128a7
Adding comments in the doJoin function;
Oct 23, 2023
a262e92
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 23, 2023
1e73927
changing toBeDefined to to.not.be.undefined
Oct 23, 2023
3254192
Adding comments for the doExit test helper function
Oct 23, 2023
cf3e386
Merge commit 'f09b5722cc06807709d041d5450e8018c33de99f' into composab…
Oct 23, 2023
1e0afcc
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 23, 2023
e9b3b32
Changing examples to anvil;
Oct 23, 2023
eee4ac1
removed unused blockNumber variable;
Oct 23, 2023
400f4ba
Adapting test for anvil;
Oct 23, 2023
a51839f
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 23, 2023
c368c94
Adapting test to anvil;
Oct 23, 2023
7789d6d
Fixing get-port version and pnpm-lock file;
Oct 23, 2023
82e507f
Running rome in the client/index.ts file;
Oct 24, 2023
c5285e3
Linting files;
Oct 24, 2023
598348a
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 24, 2023
40288dd
Moving assertJoinTransaction to the general helper file and renaming …
Oct 24, 2023
b8dbab2
Merge branch 'composable-stable-join' into composable-stable-exit
Oct 24, 2023
7ad13df
Moving validateInputs to utils folder;
Oct 24, 2023
097ac9e
refactor: Fix formatting.
johngrantuk Oct 25, 2023
73b19fc
chore: Add changeset.
johngrantuk Oct 25, 2023
9de8240
Merge pull request #97 from balancer/integrate-api
johngrantuk Oct 25, 2023
b33cda8
chore: Fix formatting.
johngrantuk Oct 25, 2023
b3a6376
chore: Merge join and fix conflicts.
johngrantuk Oct 25, 2023
1f5b579
chore: Fix lock file.
johngrantuk Oct 25, 2023
8a13f6e
refactor: getAmountsQuery & getAmountsCall return maxAmountsInNoBpt.
johngrantuk Oct 25, 2023
40f3427
refactor: Join tests to use common helpers.
johngrantuk Oct 27, 2023
ebccf76
refactor: Change value to never be undefined.
johngrantuk Oct 27, 2023
ecba974
refactor: Based off PR code review.
johngrantuk Oct 30, 2023
d7a644d
Merge pull request #106 from balancer/composable-stable-join
johngrantuk Oct 30, 2023
0e24dc5
feat: Update anvil setup to work with multiple networks.
johngrantuk Oct 31, 2023
c5f9b49
chore: Update rpcs to local fork.
johngrantuk Oct 31, 2023
bdd1c55
refactor: FxPool tests use test pool json to avoid SG call.
johngrantuk Oct 31, 2023
c089a5f
refactor: Split Weighted & CS tests and use local pool files instead …
johngrantuk Oct 31, 2023
fc26998
test: Add Fantom Anvil config and Fantom integration test.
johngrantuk Oct 31, 2023
6cdd241
refactor: Reorg and rename pool test files.
johngrantuk Oct 31, 2023
66da0df
Merge commit '6cdd24121cab1cecabb4078e248336959f33b550' into composab…
Nov 2, 2023
4f1186e
setup vitest jobids for anvil tests
agualis Nov 3, 2023
a073afc
Refactor anvil ports to be separated by 100
agualis Nov 3, 2023
2612b13
Remove old code
agualis Nov 3, 2023
b1a0f7d
Fix lint
agualis Nov 3, 2023
498a3d0
Refactoring all exit tests, exit enums and parameters names;
Nov 5, 2023
8e34a4d
Merge pull request #117 from balancer/anvil-test-parallelization
johngrantuk Nov 6, 2023
4340eb2
fix: Check for undefined in .env.
johngrantuk Nov 6, 2023
a8d539d
Merge pull request #112 from balancer/test-refactor-local
johngrantuk Nov 6, 2023
aebbc40
feat: Add InputAmount type.
johngrantuk Nov 6, 2023
70cd9e4
refactor: Change exit inputs to use InputAmount type instead of Token…
johngrantuk Nov 6, 2023
00533a8
refactor: Change join inputs to use InputAmount type instead of Token…
johngrantuk Nov 6, 2023
8f4ca80
refactor: Use helper method to get amounts in exit.
johngrantuk Nov 6, 2023
394896f
Fixing Lint Errors
Nov 6, 2023
851c161
Fixing weightedJoin assert function names;
Nov 6, 2023
94633e2
removing unused imports;
Nov 6, 2023
9cc3118
Merge pull request #118 from balancer/test-exit-refactor
lgahdl Nov 6, 2023
343ef5f
Merge pull request #119 from balancer/input-amounts
johngrantuk Nov 6, 2023
3081903
Merge commit '343ef5fa4f09ddf7b028a57a4d49ff78cc46d81b' into composab…
Nov 6, 2023
826bd07
Update test/lib/utils/exitHelper.ts
lgahdl Nov 7, 2023
42771ee
making bptIndex mandatory for getAmountsQuery function;
Nov 7, 2023
1a86e14
Merge pull request #108 from balancer/composable-stable-exit
lgahdl Nov 7, 2023
ab9933a
refactor: join/exit examples. Separate fork logic to keep focus on ex…
johngrantuk Nov 8, 2023
ef3f07a
Adding support to gyro joins and exits.
Nov 8, 2023
9699a64
Fixing/Removing comments;
Nov 8, 2023
fbb917a
fix: We are working on assumption that API will return BPT token in t…
johngrantuk Nov 9, 2023
a071f1b
Merge pull request #120 from balancer/examples-refactor
johngrantuk Nov 9, 2023
0e580a8
feat: Make CS BPT addition more resilient by only adding if it doesnt…
johngrantuk Nov 9, 2023
2eca71b
Merge pull request #122 from balancer/cs-api-missing-bpt
johngrantuk Nov 9, 2023
4ef701d
feat: Add toInputAmount helper on TokenAmount.
johngrantuk Nov 9, 2023
1192f57
Adding tests for other gyro pool types (no test with native token, ca…
Nov 9, 2023
8663fa1
fix: Update exits to use TokenAmounts.
johngrantuk Nov 10, 2023
2a9d1df
fix: Update joins to use TokenAmounts.
johngrantuk Nov 10, 2023
483220d
Refactor AmountsJoin into AddLiquidityAmounts
brunoguerios Nov 10, 2023
b06078c
Refactor JoinKind into AddLiquidityKind
brunoguerios Nov 10, 2023
010ad6d
Refactor JoinInput into AddLiquidityInput
brunoguerios Nov 10, 2023
7c9851d
Refactor JoinQueryResult into AddLiquidityQueryResult
brunoguerios Nov 10, 2023
f608e6f
Refactor JoinCall into AddLiquidityCall
brunoguerios Nov 10, 2023
196480b
Merge pull request #123 from balancer/buildCall-output-tokenAmounts
johngrantuk Nov 10, 2023
280950d
Refactor PoolJoin into AddLiquidity
brunoguerios Nov 10, 2023
85cfd33
Refactor JoinBuildOutput into AddLiquidityOutput
brunoguerios Nov 10, 2023
0676e28
Refactor QueryResult into QueryOutput for consistency
brunoguerios Nov 10, 2023
3a014d7
Refactor doQueryJoin and parseJoinArgs to doAddLiquidityQuery and par…
brunoguerios Nov 10, 2023
50c6934
Refactor join into addLiquidity within tests
brunoguerios Nov 10, 2023
e70254f
Refactor remaining comments throughout the code
brunoguerios Nov 10, 2023
6a4dd95
Refactor encoders to expose addLiquidity functions instead of join
brunoguerios Nov 10, 2023
cd50289
Refactor join into addLiquidity within examples and readme
brunoguerios Nov 10, 2023
738c08d
Merge remote-tracking branch 'origin/join' into refactor-join-interface
brunoguerios Nov 10, 2023
fbb33b1
Refactor ExitKind into RemoveLiquidityKind
brunoguerios Nov 10, 2023
c47de57
Refactor ExitInput into RemoveLiquidityInput
brunoguerios Nov 10, 2023
933ebaf
Refactor ExitQueryResult into RemoveLiquidityQueryOutput
brunoguerios Nov 10, 2023
2cf4d39
Refactor ExitCall into RemoveLiquidityCall
brunoguerios Nov 10, 2023
1332692
Refactor PoolExit into RemoveLiquidity
brunoguerios Nov 10, 2023
b63f1b8
Refactor ExitBuildOutput into RemoveLiquidityOutput
brunoguerios Nov 10, 2023
30ea9e3
Refactor encoders and other files from exit to removeLiquidity
brunoguerios Nov 10, 2023
26025a8
Refactor remaining exit to removeLiquidity
brunoguerios Nov 10, 2023
54b917c
Refactor SingleAsset to SingleToken
brunoguerios Nov 10, 2023
c82f935
Refactor exitWithNativeAsset parameter to toNativeAsset
brunoguerios Nov 10, 2023
65651a2
Refactor some result into output for consistency
brunoguerios Nov 10, 2023
2dfca4c
Rename liquidity test files
brunoguerios Nov 10, 2023
4e529d4
Fix doRemoveLiquidityQuery
brunoguerios Nov 10, 2023
ec2f98a
Merge commit '4ef701db221df2062415a44fda2d8c4aeb30e0e4' into gyro-join
Nov 10, 2023
1f29e68
Renaming wrong gyro types;
Nov 10, 2023
fab87ca
Merge pull request #121 from balancer/gyro-join
lgahdl Nov 13, 2023
acfd6d0
Merge remote-tracking branch 'origin/join' into refactor-join-interface
brunoguerios Nov 13, 2023
b366164
Refactor join into addLiquidity and exit into removeLiquidity for Gyr…
brunoguerios Nov 13, 2023
31d244a
Merge pull request #124 from balancer/refactor-join-interface
brunoguerios Nov 14, 2023
bbdc8c8
Merge remote-tracking branch 'origin/main' into join
brunoguerios Nov 14, 2023
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
1 change: 1 addition & 0 deletions src/entities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './swap';
export * from './token';
export * from './tokenAmount';
export * from './pools/';
export * from './join';
25 changes: 25 additions & 0 deletions src/entities/join.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { BaseJoin } from './pools';
import { JoinWeighted } from './pools/weighted';

/*********************** Basic Helper to get join class from pool type *************/
export type JoinConfig = {
customPoolFactories: Record<string, BaseJoin>;
};

export class JoinHelper {
private readonly poolFactories: Record<string, BaseJoin> = {};
johngrantuk marked this conversation as resolved.
Show resolved Hide resolved

constructor(config?: JoinConfig) {
const { customPoolFactories } = config || {};
this.poolFactories = {
weighted: new JoinWeighted(),
// custom pool factories take precedence over base factories
...customPoolFactories,
};
}

public getJoin(poolType: string): BaseJoin {
brunoguerios marked this conversation as resolved.
Show resolved Hide resolved
// TODO - Need to parse
return this.poolFactories[poolType];
}
}
36 changes: 36 additions & 0 deletions src/entities/pools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,39 @@ export interface BasePoolFactory {
isPoolForFactory(pool: RawPool): boolean;
create(chainId: number, pool: RawPool): BasePool;
}

// Returned from API and used as input
export type PoolState = {
id: string;
johngrantuk marked this conversation as resolved.
Show resolved Hide resolved
type: string;
assets: string[]; // already properly sorted in case different versions sort them differently
// TODO - Possibly add encoding info here?
};

// This will be extended for each pools specific input requirements
export type JoinInput = {
tokenAmounts: TokenAmount[];
chainId: number;
rpcUrl: string;
isInit?: boolean;
};

// Returned from a join query
export type JoinQueryResult = {
id: string;
assets: string[];
joinKind: string;
bptOut: TokenAmount;
amountsIn: TokenAmount[];
};

export interface BaseJoin {
getInstance(): BaseJoin;
query(input: JoinInput, poolState: PoolState): Promise<JoinQueryResult>;
// TODO - Best way to represent slippage?
johngrantuk marked this conversation as resolved.
Show resolved Hide resolved
getCall(input: JoinQueryResult & { slippage: string }): {
johngrantuk marked this conversation as resolved.
Show resolved Hide resolved
call: string;
to: string;
value: string;
};
}
1 change: 1 addition & 0 deletions src/entities/pools/weighted/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './weightedFactory';
export * from './weightedPool';
export * from './weightedMath';
export * from './weightedJoin';
187 changes: 187 additions & 0 deletions src/entities/pools/weighted/weightedJoin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import { BaseJoin, JoinInput, JoinQueryResult, PoolState } from '..';
johngrantuk marked this conversation as resolved.
Show resolved Hide resolved
import { Address } from '../../../types';
import { ZERO_ADDRESS, getPoolAddress } from '../../../utils';
import { TokenAmount } from '../../tokenAmount';

export class JoinWeighted implements BaseJoin {
// TODO - Probably not needed
getInstance(): JoinWeighted {
return new JoinWeighted();
}

public async query(
input: JoinInput,
danielmkm marked this conversation as resolved.
Show resolved Hide resolved
poolState: PoolState,
): Promise<JoinQueryResult> {
// TODO - This would need extended to work with relayer

this.checkInputs(input, poolState);

// infer join kind by input tokens
const poolAddress = getPoolAddress(poolState.id) as Address;
const joinKind = this.getJoinKind(input, poolAddress);

// Initialize join parameters
let amountsIn = Array(poolState.assets.length).fill('0');
let userData = '';

switch (joinKind) {
case 'Init': {
amountsIn = this.getAmountsIn(input, poolState.assets);
userData = `Encode userData as Init [${amountsIn}]`;
break;
}
case 'GivenIn': {
brunoguerios marked this conversation as resolved.
Show resolved Hide resolved
amountsIn = this.getAmountsIn(input, poolState.assets);
const bptOut = '0';
userData = `Encode userData as GivenIn [${amountsIn}, ${bptOut}]`;
break;
}
case 'GivenOut': {
const bptOut = input.tokenAmounts[0].amount.toString();
userData = `Encode userData as exact out [${bptOut}]`;
break;
}
default:
throw new Error('Invalid join kind');
}

const queryArgs = this.getJoinParameters({
poolId: poolState.id,
assets: poolState.assets,
sender: ZERO_ADDRESS,
recipient: ZERO_ADDRESS,
maxAmountsIn: amountsIn,
userData,
});

// Do query and get bptOut/amountsIn
console.log(queryArgs);

return {
joinKind,
id: poolState.id,
assets: poolState.assets,
bptOut: {} as TokenAmount, // TODO: update with query result if needed
amountsIn: [{} as TokenAmount], // TODO: update with query result if needed
};
}

public getCall(
input: JoinQueryResult & {
slippage: string;
sender: string;
receiver: string;
},
): { call: string; to: string; value: string } {
let maxAmountsIn: string[];
let userData: string;

switch (input.joinKind) {
case 'Init': {
maxAmountsIn = input.amountsIn.map((a) => a.amount.toString());
userData = `Encode userData as init [${maxAmountsIn}]`;
break;
}
case 'GivenIn': {
maxAmountsIn = input.amountsIn.map((a) => a.amount.toString());
const minBptOut = input.bptOut; // TODO sub slippage here
userData = `Encode userData as exact in [${maxAmountsIn}, ${minBptOut}]`;
break;
}
case 'GivenOut': {
maxAmountsIn = input.amountsIn.map((a) => a.amount.toString()); // TODO add slippage here
const exactBptOut = input.bptOut;
userData = `Encode userData as exact out [${exactBptOut}]`;
break;
}
default:
throw new Error('Invalid join kind');
}

const queryArgs = this.getJoinParameters({
poolId: input.id,
assets: input.assets,
sender: input.sender,
recipient: input.receiver,
maxAmountsIn,
userData,
});

const call = JSON.stringify(queryArgs); // TODO - Encode data

// Encode data
return {
call,
to: '0xbalancerVaultAddress',
value: '0', // TODO: ETH value when joining with ETH
};
}

private getJoinParameters({
poolId,
assets,
sender,
recipient,
maxAmountsIn,
userData,
}: {
poolId: string;
assets: string[];
sender: string;
recipient: string;
maxAmountsIn: string[];
userData: string;
}) {
const joinPoolRequest = {
assets, // with BPT
maxAmountsIn, // with BPT
userData, // wihtout BPT
fromInternalBalance: false,
};

return {
poolId,
sender,
recipient,
joinPoolRequest,
};
}

private checkInputs(input: JoinInput, poolState: PoolState) {
const tokensIn = input.tokenAmounts.map((t) => t.token.address);
if (input.tokenAmounts.length === 0) {
throw new Error('Must specify at least one input');
} else if (tokensIn.some((t) => !poolState.assets.includes(t))) {
throw new Error('Input token not in pool');
} else if (tokensIn.includes(getPoolAddress(poolState.id) as Address)) {
if (tokensIn.length > 1) {
throw new Error('Cannot join with BPT and other tokens');
} else if (input.isInit) {
throw new Error('Cannot init with BPT');
}
}
}

private getJoinKind(input: JoinInput, poolAddress: Address): string {
brunoguerios marked this conversation as resolved.
Show resolved Hide resolved
const tokensIn = input.tokenAmounts.map((t) => t.token.address);
if (tokensIn.includes(poolAddress)) {
return 'GivenOut';
} else {
return input.isInit ? 'Init' : 'GivenIn';
}
}

private getAmountsIn(input: JoinInput, poolAssets: string[]): string[] {
return poolAssets.map((asset) => {
let amountIn = '0';
const tokenIn = input.tokenAmounts.find(
(t) => t.token.address === asset,
);
if (tokenIn) {
amountIn = tokenIn.amount.toString();
}
return amountIn;
});
}
}
48 changes: 48 additions & 0 deletions test/weightedJoin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// pnpm test -- weightedJoin.test.ts
import { describe, expect, test, beforeAll } from 'vitest';
import {
JoinHelper,
JoinInput,
PoolState,
Token,
TokenAmount,
} from '../src/entities';
import { ChainId } from '../src/utils';

describe('weighted join test', () => {
let api: MockApi;
beforeAll(() => {
api = new MockApi();
});
test('should join', async () => {
const joinHelper = new JoinHelper();
const poolId = '0xpoolId';
// Calls API
const poolFromApi = await api.getPool(poolId);
const join = joinHelper.getJoin(poolFromApi.type);
const tokenIn = new Token(ChainId.MAINNET, '0xtoken1Addr', 18);
const queryInput: JoinInput = {
tokenAmounts: [TokenAmount.fromHumanAmount(tokenIn, '1')],
chainId: ChainId.MAINNET,
rpcUrl: '',
};
const queryResult = await join.query(queryInput, poolFromApi);
const call = join.getCall({ ...queryResult, slippage: '10' });
console.log(call); // Make call
expect(true).toEqual(true);
});
});

/*********************** Mock To Represent API Requirements **********************/

export class MockApi {
public async getPool(id: string): Promise<PoolState> {
return {
id,
type: 'Weighted',
assets: ['0xtoken1Addr', '0xtoken2Addr'],
};
}
}

/******************************************************************************/