Skip to content

Commit f77290f

Browse files
authored
Merge pull request #141 from balancer-labs/develop
Release 0.1.22
2 parents e30fd02 + 9467444 commit f77290f

File tree

125 files changed

+10318
-1598
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

125 files changed

+10318
-1598
lines changed

.github/workflows/balancer-js.yaml

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ jobs:
2020
steps:
2121
- uses: actions/checkout@v2
2222
- name: Install node
23-
uses: actions/setup-node@v1
23+
uses: actions/setup-node@v3
2424
with:
25-
node-version: 14
25+
node-version: 18
2626
- name: Cache
2727
uses: actions/cache@v2
2828
id: cache
@@ -40,9 +40,9 @@ jobs:
4040
steps:
4141
- uses: actions/checkout@v2
4242
- name: Install node
43-
uses: actions/setup-node@v1
43+
uses: actions/setup-node@v3
4444
with:
45-
node-version: 14
45+
node-version: 18
4646
- name: Cache
4747
uses: actions/cache@v2
4848
id: cache
@@ -62,9 +62,9 @@ jobs:
6262
steps:
6363
- uses: actions/checkout@v2
6464
- name: Install node
65-
uses: actions/setup-node@v1
65+
uses: actions/setup-node@v3
6666
with:
67-
node-version: 14
67+
node-version: 18
6868
- name: Cache
6969
uses: actions/cache@v2
7070
id: cache
@@ -79,7 +79,7 @@ jobs:
7979
- name: Compile
8080
run: yarn build
8181
- name: Run node in background for integration tests
82-
run: npx hardhat node --hostname 127.0.0.1 &
82+
run: npx hardhat node --hostname 127.0.0.1 --fork ${{ secrets.ALCHEMY_URL }} &
8383
- name: Test
8484
run: yarn test
8585

balancer-js/.nvmrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
v18.3.0

balancer-js/README.md

Lines changed: 66 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,28 @@
22

33
A JavaScript SDK which provides commonly used utilties for interacting with Balancer Protocol V2.
44

5+
## How to run the examples (Javascript)?
6+
7+
**In order to run the examples provided, you need to follow the next steps:**
8+
9+
1. git clone https://github.com/balancer-labs/balancer-sdk.git
10+
2. cd balancer-sdk
11+
3. cd balancer-js
12+
4. Create a .env file in the balancer-js folder
13+
5. In the .env file you will need to define and initialize the following variables
14+
15+
ALCHEMY_URL=[ALCHEMY HTTPS ENDPOINT]
16+
INFURA=[Infura API KEY]
17+
TRADER_KEY=[MetaMask PRIVATE KEY]
18+
We have defined both Alchemy and Infura, because some of the examples use Infura, others use Alchemy. However, feel free to modify accordingly and use your favourite one.
19+
20+
6. Run 'npm run node', this runs a local Hardhat Network
21+
7. Open a new terminal
22+
8. cd to balancer-js
23+
9. Install ts-node using: npm install ts-node
24+
10. Install tsconfig-paths using: npm install --save-dev tsconfig-paths
25+
11. Run one of the provided examples (eg: npm run examples:run -- examples/join.ts)
26+
527
## Installation
628

729
## Getting Started
@@ -10,8 +32,8 @@ A JavaScript SDK which provides commonly used utilties for interacting with Bala
1032
import { BalancerSDK, BalancerSdkConfig, Network } from '@balancer-labs/sdk';
1133

1234
const config: BalancerSdkConfig = {
13-
network: Network.MAINNET,
14-
rpcUrl: `https://mainnet.infura.io/v3/${process.env.INFURA}`,
35+
network: Network.MAINNET,
36+
rpcUrl: `https://mainnet.infura.io/v3/${process.env.INFURA}`,
1537
};
1638
const balancer = new BalancerSDK(config);
1739
```
@@ -20,16 +42,18 @@ In some examples we present a way to make end to end trades against mainnet stat
2042

2143
Installation instructions for:
2244

23-
* [Hardhat](https://hardhat.org/getting-started/#installation)
45+
- [Hardhat](https://hardhat.org/getting-started/#installation)
2446

2547
To start a forked node:
48+
2649
```
2750
npm run node
2851
```
2952

30-
* [Anvil](https://github.com/foundry-rs/foundry/tree/master/anvil#installation) - use with caution, still experimental.
31-
53+
- [Anvil](https://github.com/foundry-rs/foundry/tree/master/anvil#installation) - use with caution, still experimental.
54+
3255
To start a forked node:
56+
3357
```
3458
anvil -f FORKABLE_RPC_URL (optional pinned block: --fork-block-number XXX)
3559
```
@@ -41,30 +65,29 @@ Exposes complete functionality for token swapping. An example of using the modul
4165
```js
4266
// Uses SOR to find optimal route for a trading pair and amount
4367
const route = balancer.swaps.findRouteGivenIn({
44-
tokenIn,
45-
tokenOut,
46-
amount,
47-
gasPrice,
48-
maxPools,
49-
})
68+
tokenIn,
69+
tokenOut,
70+
amount,
71+
gasPrice,
72+
maxPools,
73+
});
5074

5175
// Prepares transaction attributes based on the route
5276
const transactionAttributes = balancer.swaps.buildSwap({
53-
userAddress,
54-
swapInfo: route,
55-
kind: 0, // 0 - givenIn, 1 - givenOut
56-
deadline,
57-
maxSlippage,
58-
})
77+
userAddress,
78+
swapInfo: route,
79+
kind: 0, // 0 - givenIn, 1 - givenOut
80+
deadline,
81+
maxSlippage,
82+
});
5983

6084
// Extract parameters required for sendTransaction
61-
const { to, data, value } = transactionAttributes
85+
const { to, data, value } = transactionAttributes;
6286

6387
// Execution with ethers.js
64-
const transactionResponse = await signer.sendTransaction({ to, data, value })
88+
const transactionResponse = await signer.sendTransaction({ to, data, value });
6589
```
6690

67-
6891
## SwapsService
6992

7093
The SwapsService provides function to query and make swaps using Balancer V2 liquidity.
@@ -168,9 +191,9 @@ complex flash swaps, you will have to use batch swap directly.
168191

169192
Gotchas:
170193

171-
- Both pools must have both assets (tokens) for swaps to work
172-
- No pool token balances can be zero
173-
- If the flash swap isn't profitable, the internal flash loan will fail.
194+
- Both pools must have both assets (tokens) for swaps to work
195+
- No pool token balances can be zero
196+
- If the flash swap isn't profitable, the internal flash loan will fail.
174197

175198
### #encodeSimpleFlashSwap
176199

@@ -218,29 +241,40 @@ swaps.querySimpleFlashSwap(batchSwap: {
218241

219242
[Example](./examples/querySimpleFlashSwap.ts)
220243

221-
## Pricing Module
244+
## Pricing
245+
246+
Spot Price functionality allowing user to query spot price for token pair.
247+
248+
### calcSpotPrice
222249

223-
Exposes Spot Price functionality allowing user to query spot price for token pair.
250+
Find Spot Price for pair in specific pool.
224251

225252
```js
226-
const pricing = new Pricing(sdkConfig);
253+
const balancer = new BalancerSDK(sdkConfig);
254+
const pool = await balancer.pools.find(poolId);
255+
const spotPrice = await pool.calcSpotPrice(
256+
ADDRESSES[network].DAI.address,
257+
ADDRESSES[network].BAL.address,
258+
);
227259
```
228260

229261
### #getSpotPrice
230262

231-
Calculates Spot Price for a token pair - for specific pool if ID otherwise finds most liquid path and uses this as reference SP.
263+
Find Spot Price for a token pair - finds most liquid path and uses this as reference SP.
264+
265+
```js
266+
const pricing = new Pricing(sdkConfig);
267+
```
232268

233269
@param { string } tokenIn Token in address.
234270
@param { string } tokenOut Token out address.
235-
@param { string } poolId Optional - if specified this pool will be used for SP calculation.
236271
@param { SubgraphPoolBase[] } pools Optional - Pool data. Will be fetched via dataProvider if not supplied.
237-
@returns { string } Spot price.
272+
@returns { string } Spot price.
238273

239274
```js
240275
async getSpotPrice(
241276
tokenIn: string,
242277
tokenOut: string,
243-
poolId = '',
244278
pools: SubgraphPoolBase[] = []
245279
): Promise<string>
246280
```
@@ -253,7 +287,7 @@ Exposes Join functionality allowing user to join pools.
253287

254288
```js
255289
const balancer = new BalancerSDK(sdkConfig);
256-
const pool = await balancer.poolsProvider.find(poolId);
290+
const pool = await balancer.pools.find(poolId);
257291
const { to, functionName, attributes, data } = pool.buildJoin(params);
258292
```
259293

@@ -285,7 +319,7 @@ Exposes Exit functionality allowing user to exit pools.
285319

286320
```js
287321
const balancer = new BalancerSDK(sdkConfig);
288-
const pool = await balancer.poolsProvider.find(poolId);
322+
const pool = await balancer.pools.find(poolId);
289323
const { to, functionName, attributes, data } = pool.buildExitExactBPTIn(params);
290324
```
291325

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Display APRs for pool ids hardcoded under `const ids`
3+
* Run command: yarn examples:run ./examples/data/token-yields.ts
4+
*/
5+
import { BalancerSDK } from '../../src/modules/sdk.module';
6+
import { yieldTokens } from '../../src/modules/data/token-yields/tokens/aave';
7+
8+
const sdk = new BalancerSDK({ network: 1, rpcUrl: '' });
9+
const { data } = sdk;
10+
11+
const main = async () => {
12+
const tokenYield = await data.tokenYields.find(yieldTokens.waDAI);
13+
14+
console.log(yieldTokens.waDAI, tokenYield);
15+
};
16+
17+
main();

balancer-js/examples/exitExactBPTIn.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
BalancerErrorCode,
66
BalancerSDK,
77
Network,
8-
PoolModel,
8+
PoolWithMethods,
99
} from '../src/index';
1010
import { parseFixed } from '@ethersproject/bignumber';
1111
import { forkSetup, getBalances } from '../src/test/lib/utils';
@@ -40,7 +40,7 @@ async function exitExactBPTIn() {
4040
const balancer = new BalancerSDK(sdkConfig);
4141

4242
// Use SDK to find pool info
43-
const pool: PoolModel | undefined = await balancer.poolsProvider.find(poolId);
43+
const pool: PoolWithMethods | undefined = await balancer.pools.find(poolId);
4444
if (!pool) throw new BalancerError(BalancerErrorCode.POOL_DOESNT_EXIST);
4545

4646
// Sets up local fork granting signer initial balances and token approvals

balancer-js/examples/exitExactTokensOut.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
BalancerErrorCode,
66
BalancerSDK,
77
Network,
8-
PoolModel,
8+
PoolWithMethods,
99
} from '../src/index';
1010
import { forkSetup, getBalances } from '../src/test/lib/utils';
1111
import { ADDRESSES } from '../src/test/lib/constants';
@@ -40,7 +40,7 @@ async function exitExactTokensOut() {
4040
const balancer = new BalancerSDK(sdkConfig);
4141

4242
// Use SDK to find pool info
43-
const pool: PoolModel | undefined = await balancer.poolsProvider.find(poolId);
43+
const pool: PoolWithMethods | undefined = await balancer.pools.find(poolId);
4444
if (!pool) throw new BalancerError(BalancerErrorCode.POOL_DOESNT_EXIST);
4545

4646
const tokensOut = [
@@ -87,7 +87,11 @@ async function exitExactTokensOut() {
8787
console.log('Balances before exit: ', tokenBalancesBefore);
8888
console.log('Balances after exit: ', tokenBalancesAfter);
8989
console.log('Max BPT input: ', [maxBPTIn.toString()]);
90-
console.log('Actual BPT input: ', [BigNumber.from(tokenBalancesBefore[0]).sub(BigNumber.from(tokenBalancesAfter[0])).toString()]);
90+
console.log('Actual BPT input: ', [
91+
BigNumber.from(tokenBalancesBefore[0])
92+
.sub(BigNumber.from(tokenBalancesAfter[0]))
93+
.toString(),
94+
]);
9195
}
9296

9397
// yarn examples:run ./examples/exitExactTokensOut.ts

balancer-js/examples/join.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
BalancerErrorCode,
66
BalancerSDK,
77
Network,
8-
PoolModel,
8+
PoolWithMethods,
99
} from '../src/index';
1010
import { forkSetup, getBalances } from '../src/test/lib/utils';
1111
import { ADDRESSES } from '../src/test/lib/constants';
@@ -56,7 +56,7 @@ async function join() {
5656
);
5757

5858
// Use SDK to find pool info
59-
const pool: PoolModel | undefined = await balancer.poolsProvider.find(poolId);
59+
const pool: PoolWithMethods | undefined = await balancer.pools.find(poolId);
6060
if (!pool) throw new BalancerError(BalancerErrorCode.POOL_DOESNT_EXIST);
6161

6262
// Checking balances to confirm success
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Display APRs for pool ids hardcoded under `const ids`
3+
* Run command: yarn examples:run ./examples/pools/aprs.ts
4+
*/
5+
import dotenv from 'dotenv';
6+
import { BalancerSDK } from '../../src/modules/sdk.module';
7+
8+
dotenv.config();
9+
10+
const sdk = new BalancerSDK({
11+
network: 137,
12+
rpcUrl: `${process.env.ALCHEMY_URL?.replace(
13+
'eth-mainnet',
14+
'polygon-mainnet.g'
15+
)}`,
16+
});
17+
18+
const { pools } = sdk;
19+
20+
const main = async () => {
21+
const pool = await pools.find(
22+
'0x0297e37f1873d2dab4487aa67cd56b58e2f27875000100000000000000000002'
23+
);
24+
25+
if (pool) {
26+
const apr = await pools.apr(pool);
27+
console.log(pool.id, apr);
28+
}
29+
};
30+
31+
main();

balancer-js/examples/pools/aprs.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Display APRs for pool ids hardcoded under `const ids`
3+
* Run command: yarn examples:run ./examples/pools/aprs.ts
4+
*/
5+
import dotenv from 'dotenv';
6+
import { BalancerSDK } from '../../src/modules/sdk.module';
7+
8+
dotenv.config();
9+
10+
const sdk = new BalancerSDK({
11+
network: 1,
12+
rpcUrl: `${process.env.ALCHEMY_URL}`,
13+
});
14+
15+
const { pools } = sdk;
16+
17+
const main = async () => {
18+
const list = (
19+
await pools.where(
20+
(pool) =>
21+
pool.poolType != 'Element' &&
22+
pool.poolType != 'AaveLinear' &&
23+
pool.poolType != 'LiquidityBootstrapping'
24+
)
25+
)
26+
.sort((a, b) => parseFloat(b.totalLiquidity) - parseFloat(a.totalLiquidity))
27+
.slice(0, 30);
28+
29+
list.forEach(async (pool) => {
30+
try {
31+
const apr = await pools.apr(pool);
32+
console.log(pool.id, apr);
33+
} catch (e) {
34+
console.log(e);
35+
}
36+
});
37+
};
38+
39+
main();

0 commit comments

Comments
 (0)