diff --git a/balancer-js/.eslintignore b/balancer-js/.eslintignore index 31a72475d..086952b61 100644 --- a/balancer-js/.eslintignore +++ b/balancer-js/.eslintignore @@ -1,4 +1,3 @@ node_modules dist -examples **/generated diff --git a/balancer-js/examples/contracts/veBAL-proxy.ts b/balancer-js/examples/contracts/veBAL-proxy.ts index 97eeeb8db..512513ffa 100644 --- a/balancer-js/examples/contracts/veBAL-proxy.ts +++ b/balancer-js/examples/contracts/veBAL-proxy.ts @@ -1,20 +1,20 @@ /** * This example shows how to the adjusted veBAL balance from the active boost delegation contract - * + * * How to run: * yarn run example examples/contracts/veBAL-proxy.ts */ import { BalancerSDK, Network } from '@balancer-labs/sdk'; -const sdk = new BalancerSDK({ - network: Network.GOERLI, - rpcUrl: 'https://rpc.ankr.com/eth_goerli' +const sdk = new BalancerSDK({ + network: Network.GOERLI, + rpcUrl: 'https://rpc.ankr.com/eth_goerli', }); const { veBalProxy } = sdk.contracts; async function main() { - const USER = "0x91F450602455564A64207414c7Fbd1F1F0EbB425"; + const USER = '0x91F450602455564A64207414c7Fbd1F1F0EbB425'; const balance = await veBalProxy?.getAdjustedBalance(USER); console.log("User's veBAL adjusted balance", balance); } diff --git a/balancer-js/examples/contracts/veBAL.ts b/balancer-js/examples/contracts/veBAL.ts index 8048a1e98..11fe517ad 100644 --- a/balancer-js/examples/contracts/veBAL.ts +++ b/balancer-js/examples/contracts/veBAL.ts @@ -1,6 +1,6 @@ /** * Shows how to interact with the veBAL contract - * + * * How to run: * yarn run example examples/contracts/veBAL.ts */ @@ -8,7 +8,7 @@ import { BalancerSDK, Network } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: Network.GOERLI, - rpcUrl: 'https://rpc.ankr.com/eth_goerli' + rpcUrl: 'https://rpc.ankr.com/eth_goerli', }); const { veBal } = sdk.contracts; @@ -16,10 +16,10 @@ const { veBal } = sdk.contracts; async function main() { if (!veBal) throw new Error('veBal address must be defined'); - const USER = "0x91F450602455564A64207414c7Fbd1F1F0EbB425"; + const USER = '0x91F450602455564A64207414c7Fbd1F1F0EbB425'; const lockInfo = await veBal.getLockInfo(USER); - console.log("veBAL lock info for user", lockInfo); + console.log('veBAL lock info for user', lockInfo); } main(); diff --git a/balancer-js/examples/data/fee-distributor.ts b/balancer-js/examples/data/fee-distributor.ts index eef8ab1ab..5dd2e19bd 100644 --- a/balancer-js/examples/data/fee-distributor.ts +++ b/balancer-js/examples/data/fee-distributor.ts @@ -1,14 +1,14 @@ /** * This example shows how to use the FeeDistributor contract to claim rewards - * + * * How to run: * yarn example examples/data/fee-distributor.ts */ -import { BalancerSDK, Network } from "@balancer-labs/sdk"; +import { BalancerSDK, Network } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: Network.MAINNET, - rpcUrl: 'https://rpc.ankr.com/eth' + rpcUrl: 'https://rpc.ankr.com/eth', }); const { feeDistributor } = sdk.data; @@ -22,15 +22,19 @@ const claimableTokens: string[] = [ const userAddress = '0x549c660ce2B988F588769d6AD87BE801695b2be3'; (async function () { - if (!feeDistributor) throw new Error("feeDistributor not defined"); - const data = await feeDistributor.getClaimableBalances(userAddress, claimableTokens); + if (!feeDistributor) throw new Error('feeDistributor not defined'); + const data = await feeDistributor.getClaimableBalances( + userAddress, + claimableTokens + ); console.table(data); const callData = feeDistributor.claimBalances(userAddress, claimableTokens); - console.log(`Encoded Callable: ${callData.slice(0, 10)}...${callData.slice(-5)}`); + console.log( + `Encoded Callable: ${callData.slice(0, 10)}...${callData.slice(-5)}` + ); console.log(` const tx = { to: '${sdk.networkConfig.addresses.contracts.feeDistributor}', data: callData }; const receipt = await (await signer.sendTransaction(tx)).wait(); - `) - + `); })(); diff --git a/balancer-js/examples/data/gauge-shares.ts b/balancer-js/examples/data/gauge-shares.ts index 16b2018d4..28dad14b5 100644 --- a/balancer-js/examples/data/gauge-shares.ts +++ b/balancer-js/examples/data/gauge-shares.ts @@ -8,18 +8,19 @@ import { BalancerSDK, Network } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: Network.MAINNET, - rpcUrl: '' + rpcUrl: '', }); const { gaugeShares } = sdk.data; -(async function() { +(async function () { if (!gaugeShares) throw 'Gauge Subgraph must be initialized'; const USER_ADDR = '0x00676e437f1945b85ec3a3c90aae35e0352115ed'; const GAUGE_ID = '0xc5f8b1de80145e3a74524a3d1a772a31ed2b50cc'; const GAUGESHARE_ID = `${USER_ADDR}-${GAUGE_ID}`; - const GAUGESHARE_ID2 = "0x79c17982020abb9a2214aa952308e104e5840e2d-0xc5f8b1de80145e3a74524a3d1a772a31ed2b50cc"; + const GAUGESHARE_ID2 = + '0x79c17982020abb9a2214aa952308e104e5840e2d-0xc5f8b1de80145e3a74524a3d1a772a31ed2b50cc'; let result; @@ -31,12 +32,13 @@ const { gaugeShares } = sdk.data; result = await gaugeShares.findByGauge(GAUGE_ID, 5); console.log('Gauge shares by gauge (first 5)', result); - + result = await gaugeShares.findByGauge(GAUGE_ID, 2, 1); console.log('Gauge shares by gauge (#2 & #3)', result); - result = await gaugeShares.query({ where: { id_in: [ GAUGESHARE_ID, GAUGESHARE_ID2 ] }}); - console.log('Gauge shares subgraph query', result); + result = await gaugeShares.query({ + where: { id_in: [GAUGESHARE_ID, GAUGESHARE_ID2] }, + }); + console.log('Gauge shares subgraph query', result); // Gauges subgraph : https://thegraph.com/hosted-service/subgraph/balancer-labs/balancer-gauges - })(); diff --git a/balancer-js/examples/data/liquidity-gauges.ts b/balancer-js/examples/data/liquidity-gauges.ts index 60fa0c585..1d6bc2c20 100644 --- a/balancer-js/examples/data/liquidity-gauges.ts +++ b/balancer-js/examples/data/liquidity-gauges.ts @@ -1,10 +1,10 @@ /** * Example retrieves all the gauges for the pools and shows one example with BAL and one example with BAL and another reward token (LIDO) - * + * * Run with: * yarn example ./examples/data/liquidity-gauges.ts */ -import { BalancerSDK, Network } from "@balancer-labs/sdk"; +import { BalancerSDK, Network } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: Network.ARBITRUM, @@ -16,6 +16,10 @@ const { liquidityGauges } = sdk.data; if (!liquidityGauges) throw 'Gauge Subgraph must be initialized'; const gauges = await liquidityGauges.fetch(); console.log(`Gauges: `, gauges.length); - console.log(gauges.find((it) => it.id === '0x914ec5f93ccd6362ba925bedd0bd68107b85d2ca')); - console.log(gauges.find((it) => it.id === '0xcf9f895296f5e1d66a7d4dcf1d92e1b435e9f999')); + console.log( + gauges.find((it) => it.id === '0x914ec5f93ccd6362ba925bedd0bd68107b85d2ca') + ); + console.log( + gauges.find((it) => it.id === '0xcf9f895296f5e1d66a7d4dcf1d92e1b435e9f999') + ); })(); diff --git a/balancer-js/examples/data/pool-shares.ts b/balancer-js/examples/data/pool-shares.ts index cd9528dec..be96b863d 100644 --- a/balancer-js/examples/data/pool-shares.ts +++ b/balancer-js/examples/data/pool-shares.ts @@ -1,24 +1,24 @@ /** * Example of using the poolShares data source - * + * * Run with: * yarn example ./examples/data/pool-shares.ts */ import { BalancerSDK, Network } from '@balancer-labs/sdk'; -const sdk = new BalancerSDK( - { - network: Network.MAINNET, - rpcUrl: '' - }); +const sdk = new BalancerSDK({ + network: Network.MAINNET, + rpcUrl: '', +}); const { poolShares } = sdk.data; -(async function() { - - const POOLSHARE_ID = '0x01abc00e86c7e258823b9a055fd62ca6cf61a163-0x2da1bcb14be26be6812e0e871e8dc4f4c0d92629'; - const POOL_ID = '0x01abc00e86c7e258823b9a055fd62ca6cf61a16300010000000000000000003b' +(async function () { + const POOLSHARE_ID = + '0x01abc00e86c7e258823b9a055fd62ca6cf61a163-0x2da1bcb14be26be6812e0e871e8dc4f4c0d92629'; + const POOL_ID = + '0x01abc00e86c7e258823b9a055fd62ca6cf61a16300010000000000000000003b'; const USER_ADDR = '0xba12222222228d8ba445958a75a0704d566bf2c8'; - + let result; result = await poolShares.find(POOLSHARE_ID); @@ -35,9 +35,11 @@ const { poolShares } = sdk.data; result = await poolShares.findByPool(POOL_ID, 2, 1); console.log('Pool shares by pool (#2 & #3)', result); - - result = await poolShares.query({ where: { poolId: POOL_ID, balance_gt: '0' }, first: 3 }); + + result = await poolShares.query({ + where: { poolId: POOL_ID, balance_gt: '0' }, + first: 3, + }); console.log('Pool shares subgraph query', result); // Balancer subgraph : https://thegraph.com/hosted-service/subgraph/balancer-labs/balancer-v2 - })(); diff --git a/balancer-js/examples/data/pools.ts b/balancer-js/examples/data/pools.ts index a55fa48b0..e3ac28443 100644 --- a/balancer-js/examples/data/pools.ts +++ b/balancer-js/examples/data/pools.ts @@ -1,17 +1,18 @@ import { BalancerSDK, Network } from '@balancer-labs/sdk'; -const sdk = new BalancerSDK({ - network: Network.MAINNET, - rpcUrl: 'https://rpc.ankr.com/eth' +const sdk = new BalancerSDK({ + network: Network.MAINNET, + rpcUrl: 'https://rpc.ankr.com/eth', }); const { pools, poolsOnChain } = sdk.data; async function main() { - - const POOL_ID1 = '0x2d011adf89f0576c9b722c28269fcb5d50c2d17900020000000000000000024d'; - const POOL_ID2 = '0x4aa462d59361fc0115b3ab7e447627534a8642ae000100000000000000000158'; - const POOL_IDs = [ POOL_ID1, POOL_ID2 ]; + const POOL_ID1 = + '0x2d011adf89f0576c9b722c28269fcb5d50c2d17900020000000000000000024d'; + const POOL_ID2 = + '0x4aa462d59361fc0115b3ab7e447627534a8642ae000100000000000000000158'; + const POOL_IDs = [POOL_ID1, POOL_ID2]; let result; @@ -21,18 +22,21 @@ async function main() { result = await pools.all(); console.log('Fetch all pools', result); - result = await pools.where(pool => POOL_IDs.includes(pool.id)); + result = await pools.where((pool) => POOL_IDs.includes(pool.id)); console.log('Filter pools by attributes', result); - // Fefetch on-chain balances for a given pool + // Refetch on-chain balances for a given pool const pool = await pools.find(POOL_ID1); - for (const idx in pool!.tokens) { - pool!.tokens[idx].balance = '0'; + if (!pool) { + throw new Error('Pool not found'); + } + for (const idx in pool.tokens) { + pool.tokens[idx].balance = '0'; } - const onchain = await poolsOnChain.refresh(pool!); + const onchain = await poolsOnChain.refresh(pool); console.log('onchain pool', onchain); } main(); -// yarn example ./examples/data/pools.ts \ No newline at end of file +// yarn example ./examples/data/pools.ts diff --git a/balancer-js/examples/data/token-prices.ts b/balancer-js/examples/data/token-prices.ts index 891db596a..9a5121f1c 100644 --- a/balancer-js/examples/data/token-prices.ts +++ b/balancer-js/examples/data/token-prices.ts @@ -15,7 +15,18 @@ const tetuBal = '0x7fc9e0aa043787bfad28e29632ada302c790ce33'; (async () => { // It will be just one request to coingecko - const ps = [eth, weth, dai, ohm, tetuBal, matic, eth, dai, tetuBal, matic].map((t) => data.tokenPrices.find(t)); + const ps = [ + eth, + weth, + dai, + ohm, + tetuBal, + matic, + eth, + dai, + tetuBal, + matic, + ].map((t) => data.tokenPrices.find(t)); const price = await Promise.all(ps); console.log(price); diff --git a/balancer-js/examples/helpers/erc20.ts b/balancer-js/examples/helpers/erc20.ts index df84cc192..6509b0427 100644 --- a/balancer-js/examples/helpers/erc20.ts +++ b/balancer-js/examples/helpers/erc20.ts @@ -1,8 +1,8 @@ -import { hexlify, zeroPad } from '@ethersproject/bytes' -import { keccak256 } from '@ethersproject/solidity' -import { BigNumber } from '@ethersproject/bignumber' -import { Contract } from '@ethersproject/contracts' -import { JsonRpcProvider, JsonRpcSigner } from '@ethersproject/providers' +import { hexlify, zeroPad } from '@ethersproject/bytes'; +import { keccak256 } from '@ethersproject/solidity'; +import { BigNumber } from '@ethersproject/bignumber'; +import { Contract } from '@ethersproject/contracts'; +import { JsonRpcProvider, JsonRpcSigner } from '@ethersproject/providers'; /** * Set token balance for a given account @@ -23,14 +23,16 @@ export const setTokenBalance = async ( isVyperMapping = false ): Promise => { // Get storage slot index - const slotFormat = isVyperMapping ? [slot, account] : [account, slot] - const slotValue = keccak256(['uint256', 'uint256'], slotFormat) + const slotFormat = isVyperMapping ? [slot, account] : [account, slot]; + const slotValue = keccak256(['uint256', 'uint256'], slotFormat); // Manipulate local balance (needs to be bytes32 string) - const value = hexlify(zeroPad(BigNumber.from(String(BigInt(balance))).toHexString(), 32)) + const value = hexlify( + zeroPad(BigNumber.from(String(BigInt(balance))).toHexString(), 32) + ); - await provider.send('hardhat_setStorageAt', [token, slotValue, value]) -} + await provider.send('hardhat_setStorageAt', [token, slotValue, value]); +}; /** * Approve token balance for vault contract @@ -48,17 +50,15 @@ export const approveToken = async ( ): Promise => { const iERC20 = [ 'function approve(address spender, uint256 amount) external returns (bool)', - ] - const erc20 = new Contract(token, iERC20, signer) - const txReceipt = await ( - await erc20.approve(spender, amount) - ).wait() - return txReceipt.status === 1 -} + ]; + const erc20 = new Contract(token, iERC20, signer); + const txReceipt = await (await erc20.approve(spender, amount)).wait(); + return txReceipt.status === 1; +}; /** * Get ERC20 token balance for a given account - * + * * @param token Token address to get balance of * @param account Account to get balance for * @param provider JsonRpcProvider @@ -71,7 +71,7 @@ export const getTokenBalance = async ( ): Promise => { const iERC20 = [ 'function balanceOf(address account) external view returns (uint256)', - ] - const erc20 = new Contract(token, iERC20, provider) - return erc20.balanceOf(account) -} + ]; + const erc20 = new Contract(token, iERC20, provider); + return erc20.balanceOf(account); +}; diff --git a/balancer-js/examples/helpers/forked-utils.ts b/balancer-js/examples/helpers/forked-utils.ts index 257cd0a71..ec102bed0 100644 --- a/balancer-js/examples/helpers/forked-utils.ts +++ b/balancer-js/examples/helpers/forked-utils.ts @@ -1,4 +1,4 @@ -import { JsonRpcProvider } from '@ethersproject/providers' +import { JsonRpcProvider } from '@ethersproject/providers'; /** * Resets the fork to a given block number @@ -6,12 +6,16 @@ import { JsonRpcProvider } from '@ethersproject/providers' * @param provider JsonRpcProvider * @param blockNumber Block number to reset fork to */ -export const reset = (provider: JsonRpcProvider, blockNumber: number, jsonRpcUrl = 'https://rpc.ankr.com/eth'): Promise => +export const reset = ( + provider: JsonRpcProvider, + blockNumber?: number, + jsonRpcUrl = 'https://rpc.ankr.com/eth' +): Promise => provider.send('hardhat_reset', [ { forking: { jsonRpcUrl, - blockNumber - } - } + blockNumber, + }, + }, ]); diff --git a/balancer-js/examples/helpers/index.ts b/balancer-js/examples/helpers/index.ts index 3834b22a9..f16dbc9b4 100644 --- a/balancer-js/examples/helpers/index.ts +++ b/balancer-js/examples/helpers/index.ts @@ -1,4 +1,4 @@ -export * from './print-logs' -export * from './shorten-address' -export * from './forked-utils' -export * from './erc20' \ No newline at end of file +export * from './print-logs'; +export * from './shorten-address'; +export * from './forked-utils'; +export * from './erc20'; diff --git a/balancer-js/examples/helpers/shorten-address.ts b/balancer-js/examples/helpers/shorten-address.ts index 4f7eea708..5b49b97a5 100644 --- a/balancer-js/examples/helpers/shorten-address.ts +++ b/balancer-js/examples/helpers/shorten-address.ts @@ -1,9 +1,9 @@ /** * Helper function to shorten addresses for readability - * + * * @param address * @returns shortened address */ export const shortenAddress = (address: string): string => { - return address.slice(0, 6) + '...' + address.slice(-4) -} + return address.slice(0, 6) + '...' + address.slice(-4); +}; diff --git a/balancer-js/examples/pools/aprs/aprs.arbitrum.ts b/balancer-js/examples/pools/aprs/aprs.arbitrum.ts index 18d2239e0..712a1014c 100644 --- a/balancer-js/examples/pools/aprs/aprs.arbitrum.ts +++ b/balancer-js/examples/pools/aprs/aprs.arbitrum.ts @@ -1,6 +1,6 @@ /** * Display APRs for pool ids hardcoded under `const ids` - * + * * Run command * yarn example ./examples/pools/aprs/aprs.arbitrum.ts */ diff --git a/balancer-js/examples/pools/aprs/aprs.gnosis.ts b/balancer-js/examples/pools/aprs/aprs.gnosis.ts index a344eedaf..db31f9773 100644 --- a/balancer-js/examples/pools/aprs/aprs.gnosis.ts +++ b/balancer-js/examples/pools/aprs/aprs.gnosis.ts @@ -1,6 +1,6 @@ /** * Display APRs for pool ids hardcoded under `const ids` - * + * * Run command: * yarn example ./examples/pools/aprs/aprs.gnosis.ts */ diff --git a/balancer-js/examples/pools/aprs/aprs.polygon.ts b/balancer-js/examples/pools/aprs/aprs.polygon.ts index ce869c881..b3c6fd127 100644 --- a/balancer-js/examples/pools/aprs/aprs.polygon.ts +++ b/balancer-js/examples/pools/aprs/aprs.polygon.ts @@ -1,6 +1,6 @@ /** * Display APRs - * + * * Run command: * yarn example ./examples/pools/aprs/aprs.polygon.ts */ diff --git a/balancer-js/examples/pools/aprs/aprs.zkevm.ts b/balancer-js/examples/pools/aprs/aprs.zkevm.ts index 37784281e..c1036d808 100644 --- a/balancer-js/examples/pools/aprs/aprs.zkevm.ts +++ b/balancer-js/examples/pools/aprs/aprs.zkevm.ts @@ -1,6 +1,6 @@ /** * Display APRs - * + * * Run command: * yarn example ./examples/pools/aprs/aprs.zkevm.ts */ diff --git a/balancer-js/examples/pools/create/create-composable-stable-pool.ts b/balancer-js/examples/pools/create/create-composable-stable-pool.ts index 4953189c7..c5bae80f6 100644 --- a/balancer-js/examples/pools/create/create-composable-stable-pool.ts +++ b/balancer-js/examples/pools/create/create-composable-stable-pool.ts @@ -1,12 +1,12 @@ /** * ComposableStable - Create and do an initial join. - * + * * Run command: * yarn example ./examples/pools/create/create-composable-stable-pool.ts */ -import { BalancerSDK, Network, PoolType } from '@balancer-labs/sdk' -import { parseFixed } from '@ethersproject/bignumber' -import { reset, setTokenBalance, approveToken } from 'examples/helpers' +import { BalancerSDK, Network, PoolType } from '@balancer-labs/sdk'; +import { parseFixed } from '@ethersproject/bignumber'; +import { reset, setTokenBalance, approveToken } from 'examples/helpers'; async function createAndInitJoinComposableStable() { const balancer = new BalancerSDK({ @@ -15,26 +15,48 @@ async function createAndInitJoinComposableStable() { }); // Setup join parameters - const signer = balancer.provider.getSigner() - const ownerAddress = await signer.getAddress() - const usdc = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' - const usdt = '0xdac17f958d2ee523a2206206994597c13d831ec7' - const poolTokens = [usdc, usdt] + const signer = balancer.provider.getSigner(); + const ownerAddress = await signer.getAddress(); + const usdc = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'; + const usdt = '0xdac17f958d2ee523a2206206994597c13d831ec7'; + const poolTokens = [usdc, usdt]; const amountsIn = [ parseFixed('1000000000', 6).toString(), parseFixed('1000000000', 6).toString(), ]; // Prepare local fork for simulation - await reset(balancer.provider, 17347414) - await setTokenBalance(balancer.provider, ownerAddress, poolTokens[0], amountsIn[0], 9) - await setTokenBalance(balancer.provider, ownerAddress, poolTokens[1], amountsIn[1], 2) - await approveToken(poolTokens[0], balancer.contracts.vault.address, amountsIn[0], signer) - await approveToken(poolTokens[1], balancer.contracts.vault.address, amountsIn[1], signer) + await reset(balancer.provider, 17700000); + await setTokenBalance( + balancer.provider, + ownerAddress, + poolTokens[0], + amountsIn[0], + 9 + ); + await setTokenBalance( + balancer.provider, + ownerAddress, + poolTokens[1], + amountsIn[1], + 2 + ); + await approveToken( + poolTokens[0], + balancer.contracts.vault.address, + amountsIn[0], + signer + ); + await approveToken( + poolTokens[1], + balancer.contracts.vault.address, + amountsIn[1], + signer + ); const composableStablePoolFactory = balancer.pools.poolFactory.of( PoolType.ComposableStable - ) + ); const poolParameters = { name: 'Test-Name', diff --git a/balancer-js/examples/pools/create/create-weighted-pool.ts b/balancer-js/examples/pools/create/create-weighted-pool.ts index c30aae724..30b5ab197 100644 --- a/balancer-js/examples/pools/create/create-weighted-pool.ts +++ b/balancer-js/examples/pools/create/create-weighted-pool.ts @@ -27,7 +27,7 @@ async function createAndInitJoinWeightedPool() { ]; // Prepare local fork for simulation - await reset(balancer.provider, 17347414); + await reset(balancer.provider, 17700000); await setTokenBalance( balancer.provider, ownerAddress, diff --git a/balancer-js/examples/pools/emissions.ts b/balancer-js/examples/pools/emissions.ts index 79897265b..046a8969e 100644 --- a/balancer-js/examples/pools/emissions.ts +++ b/balancer-js/examples/pools/emissions.ts @@ -1,23 +1,25 @@ /** * Display weekly BAL emissions for a pool - * + * * How to run: * yarn example examples/pools/emissions.ts */ -import { BalancerSDK } from '@balancer-labs/sdk' +import { BalancerSDK } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: 1, rpcUrl: 'https://rpc.ankr.com/eth', -}) +}); -const { pools } = sdk +const { pools } = sdk; const main = async () => { if (pools.emissionsService) { - const emissions = await pools.emissionsService.weekly('0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080') - console.log(emissions) + const emissions = await pools.emissionsService.weekly( + '0x32296969ef14eb0c6d29669c550d4a0449130230000200000000000000000080' + ); + console.log(emissions); } -} +}; -main() +main(); diff --git a/balancer-js/examples/pools/exit/composable-stable-exit.ts b/balancer-js/examples/pools/exit/composable-stable-exit.ts index a79eee17b..e07b41f20 100644 --- a/balancer-js/examples/pools/exit/composable-stable-exit.ts +++ b/balancer-js/examples/pools/exit/composable-stable-exit.ts @@ -8,7 +8,7 @@ * 6. SDK calculates expectedAmountsOut that is 100% accurate * 7. SDK returns exitGeneralised transaction data with proper minAmountsOut limits in place (calculated using user defined slippage) * 8. User is now able to submit a safe transaction to the blockchain - * + * * Example run: * yarn example ./examples/pools/exit/composable-stable-exit.ts */ @@ -20,22 +20,23 @@ import { truncateAddresses, removeItem, Relayer, - SimulationType -} from '@balancer-labs/sdk' -import { parseEther } from '@ethersproject/units' -import { formatFixed } from '@ethersproject/bignumber' -import { getTokenBalance, reset, setTokenBalance } from 'examples/helpers' + SimulationType, +} from '@balancer-labs/sdk'; +import { parseEther } from '@ethersproject/units'; +import { formatFixed } from '@ethersproject/bignumber'; +import { getTokenBalance, reset, setTokenBalance } from 'examples/helpers'; // bb-a-usd -const poolId = '0xfebb0bbf162e64fb9d0dfe186e517d84c395f016000000000000000000000502' +const poolId = + '0xfebb0bbf162e64fb9d0dfe186e517d84c395f016000000000000000000000502'; const subpools = [ '0x6667c6fa9f2b3fc1cc8d85320b62703d938e43850000000000000000000004fb', '0xa1697f9af0875b63ddc472d6eebada8c1fab85680000000000000000000004f9', '0xcbfa4532d8b2ade2c261d3dd5ef2a2284f7926920000000000000000000004fa', -] +]; // Amount of testPool BPT that will be used to exit -const amount = String(parseEther('10')) +const amount = String(parseEther('10')); /* Example showing how to use the SDK generalisedExit method. @@ -61,38 +62,33 @@ const exit = async () => { in: [poolId, ...subpools], }, }, - } + }; - const subgraphQuery: GraphQLQuery = { args: subgraphArgs, attrs: {} } + const subgraphQuery: GraphQLQuery = { args: subgraphArgs, attrs: {} }; const balancer = new BalancerSDK({ network: Network.MAINNET, rpcUrl: 'http://127.0.0.1:8545', subgraphQuery, - }) + }); - const { provider } = balancer + const { provider } = balancer; // Reset the local fork to block 17000000 - await reset(provider, 17000000) + await reset(provider, 17700000); - const signer = provider.getSigner() + const signer = provider.getSigner(); const address = await signer.getAddress(); - const pool = await balancer.pools.find(poolId) - if (!pool) throw 'Pool not found' + const pool = await balancer.pools.find(poolId); + if (!pool) throw 'Pool not found'; // Setup local fork with correct balances/approval to exit bb-a-usd2 pool - await setTokenBalance(provider, address, pool.address, amount, 0) + await setTokenBalance(provider, address, pool.address, amount, 0); // Use SDK to create exit transaction const { estimatedAmountsOut, tokensOut, tokensToUnwrap } = - await balancer.pools.getExitInfo( - pool.id, - amount, - address, - signer - ) + await balancer.pools.getExitInfo(pool.id, amount, address, signer); // User reviews expectedAmountOut console.log(' -- getExitInfo() -- '); @@ -101,20 +97,20 @@ const exit = async () => { tokensOut: truncateAddresses(tokensOut), estimatedAmountsOut: estimatedAmountsOut, unwrap: tokensOut.map((t) => tokensToUnwrap.includes(t)), - }) + }); // User approves relayer - const { contracts } = balancer + const { contracts } = balancer; const relayerAuth = await Relayer.signRelayerApproval( contracts.relayer.address, address, signer, contracts.vault - ) + ); // Use SDK to create exit transaction - const slippage = '100' + const slippage = '100'; const query = await balancer.pools.generalisedExit( pool.id, amount, @@ -124,17 +120,17 @@ const exit = async () => { SimulationType.Static, relayerAuth, tokensToUnwrap - ) + ); // Submit transaction and check balance deltas to confirm success - await signer.sendTransaction({ to: query.to, data: query.encodedCall }) + await signer.sendTransaction({ to: query.to, data: query.encodedCall }); const balanceDeltas = await Promise.all( [pool.address, ...query.tokensOut].map((token) => getTokenBalance(token, address, balancer.provider) ) - ) - + ); + console.log(' -- Simulating using Static Call -- '); console.log('Price impact: ', formatFixed(query.priceImpact, 18)); console.log(`Amount Pool Token In: ${balanceDeltas[0].toString()}`); diff --git a/balancer-js/examples/pools/exit/recovery-exit.ts b/balancer-js/examples/pools/exit/recovery-exit.ts index 21ce83ce5..38a4f61f0 100644 --- a/balancer-js/examples/pools/exit/recovery-exit.ts +++ b/balancer-js/examples/pools/exit/recovery-exit.ts @@ -1,6 +1,6 @@ /** * Shows how to exit a pool in recovery mode. - * + * * Run command: * yarn example ./examples/pools/exit/recovery-exit.ts */ @@ -9,19 +9,19 @@ import { insert, Network, truncateAddresses, -} from '@balancer-labs/sdk' -import { parseEther } from '@ethersproject/units' -import { getTokenBalance, reset, setTokenBalance } from 'examples/helpers' +} from '@balancer-labs/sdk'; +import { parseEther } from '@ethersproject/units'; +import { getTokenBalance, reset, setTokenBalance } from 'examples/helpers'; async function recoveryExit() { const balancer = new BalancerSDK({ network: Network.MAINNET, rpcUrl: 'http://127.0.0.1:8545', // Using local fork for simulation - }) + }); // Setup exit parameters - const signer = balancer.provider.getSigner() - const address = await signer.getAddress() + const signer = balancer.provider.getSigner(); + const address = await signer.getAddress(); const poolId = // '0x50cf90b954958480b8df7958a9e965752f62712400000000000000000000046f'; // bb-e-usd @@ -29,37 +29,37 @@ async function recoveryExit() { // '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d'; // bb-a-usd '0xa718042e5622099e5f0ace4e7122058ab39e1bbe000200000000000000000475'; // 50temple_50bb-e-usd - const bptIn = String(parseEther('1')) + const bptIn = String(parseEther('1')); const slippage = '200'; // 200 bps = 2% // Use SDK to find pool info - const pool = await balancer.pools.find(poolId) - if (!pool) throw 'POOL_DOESNT_EXIST' + const pool = await balancer.pools.find(poolId); + if (!pool) throw 'POOL_DOESNT_EXIST'; // Prepare local fork for simulation - await reset(balancer.provider, 16819888) - await setTokenBalance(balancer.provider, address, pool.address, bptIn, 0) + await reset(balancer.provider, 17700000); + await setTokenBalance(balancer.provider, address, pool.address, bptIn, 0); // Build transaction const { to, data, expectedAmountsOut, minAmountsOut } = - pool.buildRecoveryExit(address, bptIn, slippage) + pool.buildRecoveryExit(address, bptIn, slippage); // Send transaction - await signer.sendTransaction({ to, data }) + await signer.sendTransaction({ to, data }); // Check balances after transaction to confirm success const balances = await Promise.all( pool.tokensList.map((token) => getTokenBalance(token, address, balancer.provider) ) - ) + ); console.table({ tokensOut: truncateAddresses(pool.tokensList), minAmountsOut: insert(minAmountsOut, pool.bptIndex, bptIn), expectedAmountsOut: insert(expectedAmountsOut, pool.bptIndex, bptIn), amountsOut: balances.map((b) => b.toString()), - }) + }); } -recoveryExit() +recoveryExit(); diff --git a/balancer-js/examples/pools/exit/single-token-exit.ts b/balancer-js/examples/pools/exit/single-token-exit.ts index cbd85977a..9c7f9198c 100644 --- a/balancer-js/examples/pools/exit/single-token-exit.ts +++ b/balancer-js/examples/pools/exit/single-token-exit.ts @@ -1,12 +1,12 @@ /** * Exit a pool with a single token out. - * + * * Run command: - * yarn example ./examples/pools/exit/exit-to-single-token.ts + * yarn example ./examples/pools/exit/single-token-exit.ts */ -import { Network, BalancerSDK } from '@balancer-labs/sdk' -import { reset, setTokenBalance, getTokenBalance } from 'examples/helpers' -import { parseEther } from '@ethersproject/units' +import { Network, BalancerSDK } from '@balancer-labs/sdk'; +import { reset, setTokenBalance, getTokenBalance } from 'examples/helpers'; +import { parseEther } from '@ethersproject/units'; async function singleTokenExit() { const balancer = new BalancerSDK({ @@ -14,21 +14,23 @@ async function singleTokenExit() { rpcUrl: 'http://127.0.0.1:8545', // Using local fork for simulation }); - const signer = balancer.provider.getSigner() - const address = await signer.getAddress() - + const signer = balancer.provider.getSigner(); + const address = await signer.getAddress(); + // Setup exit parameters - const bptIn = String(parseEther('1')) - const weth = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' // weth - const slippage = '1000' // 10% + const bptIn = String(parseEther('1')); + const weth = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; // weth + const slippage = '1000'; // 10% // 50/50 WBTC/WETH Pool - const pool = await balancer.pools.find('0xa6f548df93de924d73be7d25dc02554c6bd66db500020000000000000000000e') - if (!pool) throw Error('Pool not found') - + const pool = await balancer.pools.find( + '0xa6f548df93de924d73be7d25dc02554c6bd66db500020000000000000000000e' + ); + if (!pool) throw Error('Pool not found'); + // Prepare local fork for simulation - await reset(balancer.provider, 17000000) - await setTokenBalance(balancer.provider, address, pool.address, bptIn, 0) + await reset(balancer.provider, 17700000); + await setTokenBalance(balancer.provider, address, pool.address, bptIn, 0); // We are exiting all the BPT to a single token out const { to, data, expectedAmountsOut } = pool.buildExitExactBPTIn( @@ -37,18 +39,16 @@ async function singleTokenExit() { slippage, false, weth - ) + ); // Send transaction - await ( - await signer.sendTransaction({ to, data }) - ).wait() + await (await signer.sendTransaction({ to, data })).wait(); // Check balances after transaction to confirm success - const balance = await getTokenBalance(weth, address, balancer.provider) + const balance = await getTokenBalance(weth, address, balancer.provider); - console.log('Expected amounts out', `${expectedAmountsOut}`) - console.log('Actual amount out', String(balance)) + console.log('Expected amounts out', `${expectedAmountsOut}`); + console.log('Actual amount out', String(balance)); } -singleTokenExit() +singleTokenExit(); diff --git a/balancer-js/examples/pools/fees.ts b/balancer-js/examples/pools/fees.ts index ed52f0a69..7f3e9f71b 100644 --- a/balancer-js/examples/pools/fees.ts +++ b/balancer-js/examples/pools/fees.ts @@ -1,4 +1,4 @@ -import { BalancerSDK } from '@balancer-labs/sdk' +import { BalancerSDK } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: 1, @@ -14,7 +14,7 @@ const sdk = new BalancerSDK({ const fees = await sdk.pools.fees(pool); console.log(fees); } - }) + }); })(); // yarn example ./examples/pools/fees.ts diff --git a/balancer-js/examples/pools/impermanent-loss.ts b/balancer-js/examples/pools/impermanent-loss.ts index 9a4b3fc20..5744cdf2a 100644 --- a/balancer-js/examples/pools/impermanent-loss.ts +++ b/balancer-js/examples/pools/impermanent-loss.ts @@ -5,7 +5,11 @@ * yarn example ./examples/pools/impermanent-loss.ts */ -import {BalancerError, BalancerErrorCode, BalancerSDK} from "@balancer-labs/sdk"; +import { + BalancerError, + BalancerErrorCode, + BalancerSDK, +} from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: 1, @@ -17,15 +21,33 @@ const { pools } = sdk; const { poolJoinExits } = sdk.data; const main = async (): Promise => { - await impermanentLoss('0x0647721e414a7ab11817427c6f49d0d15d6aae53', '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014'); - await impermanentLoss('0x0a53d9586dd052a06fca7649a02b973cc164c1b4', '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014'); - await impermanentLoss('0x000000000088e0120f9e6652cc058aec07564f69', '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014'); - await impermanentLoss('0x07dd13b2705050b2f5c60da9f7f0f37b7395945a', '0xc45d42f801105e861e86658648e3678ad7aa70f900010000000000000000011e'); - await impermanentLoss('0x00bcfc8f7471b2e4d21af417dea393c1578c67c1', '0x1e19cf2d73a72ef1332c882f20534b6519be0276000200000000000000000112'); + await impermanentLoss( + '0x0647721e414a7ab11817427c6f49d0d15d6aae53', + '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014' + ); + await impermanentLoss( + '0x0a53d9586dd052a06fca7649a02b973cc164c1b4', + '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014' + ); + await impermanentLoss( + '0x000000000088e0120f9e6652cc058aec07564f69', + '0x5c6ee304399dbdb9c8ef030ab642b10820db8f56000200000000000000000014' + ); + await impermanentLoss( + '0x07dd13b2705050b2f5c60da9f7f0f37b7395945a', + '0xc45d42f801105e861e86658648e3678ad7aa70f900010000000000000000011e' + ); + await impermanentLoss( + '0x00bcfc8f7471b2e4d21af417dea393c1578c67c1', + '0x1e19cf2d73a72ef1332c882f20534b6519be0276000200000000000000000112' + ); // await impermanentLoss('0x356226e2f6d49749fd5f0fa5656acf86b20f3485', '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d'); -} +}; -const impermanentLoss = async (userAddress: string, poolId: string): Promise => { +const impermanentLoss = async ( + userAddress: string, + poolId: string +): Promise => { try { const joins = await poolJoinExits.findJoins(userAddress, poolId); if (!joins.length) { @@ -40,9 +62,9 @@ const impermanentLoss = async (userAddress: string, poolId: string): Promise ${IL}%`); - } catch (e: any) { + } catch (e: any) { // eslint-disable-line console.error(`${userAddress} ${poolId} => Error: ${e.message}`); } -} +}; -main().then(() => console.log('done')); \ No newline at end of file +main().then(() => console.log('done')); diff --git a/balancer-js/examples/pools/join/join-composable-stable-with-underlying.ts b/balancer-js/examples/pools/join/join-composable-stable-with-underlying.ts index 595c506d4..898ab71c7 100644 --- a/balancer-js/examples/pools/join/join-composable-stable-with-underlying.ts +++ b/balancer-js/examples/pools/join/join-composable-stable-with-underlying.ts @@ -74,7 +74,7 @@ const signer = provider.getSigner(); * would already have DAI and the vault would already be approved. */ async function setup(address: string) { - await reset(provider, 17000000); + await reset(provider, 17700000); await setTokenBalance(provider, address, dai, amount, 2); await approveToken(dai, contracts.vault.address, amount, signer); } diff --git a/balancer-js/examples/pools/join/join-with-eth.ts b/balancer-js/examples/pools/join/join-with-eth.ts index 8baffebf4..d47adc3f3 100644 --- a/balancer-js/examples/pools/join/join-with-eth.ts +++ b/balancer-js/examples/pools/join/join-with-eth.ts @@ -45,7 +45,7 @@ async function join() { const address = await signer.getAddress(); // Prepare local fork for simulation - await reset(provider, 17000000); + await reset(provider, 17700000); await setTokenBalance(provider, address, tokensIn[0], amountsIn[0], slots[0]); await approveToken( tokensIn[0], diff --git a/balancer-js/examples/pools/join/join-with-tokens-in.ts b/balancer-js/examples/pools/join/join-with-tokens-in.ts index 16b43d098..b5a1b2643 100644 --- a/balancer-js/examples/pools/join/join-with-tokens-in.ts +++ b/balancer-js/examples/pools/join/join-with-tokens-in.ts @@ -2,7 +2,7 @@ * Example showing how to use Pools module to join pools. * * Run with: - * yarn example ./examples/pools/join/join.ts + * yarn example ./examples/pools/join/join-with-tokens-in.ts */ import { BalancerSDK, Network } from '@balancer-labs/sdk'; import { @@ -41,7 +41,7 @@ async function join() { const amountsIn = ['10000000', '1000000000000000000']; // Prepare local fork for simulation - await reset(provider, 17000000); + await reset(provider, 17700000); await setTokenBalance(provider, address, tokensIn[0], amountsIn[0], slots[0]); await setTokenBalance(provider, address, tokensIn[1], amountsIn[1], slots[1]); await approveToken( diff --git a/balancer-js/examples/pools/liquidity/liquidity.gnosis.ts b/balancer-js/examples/pools/liquidity/liquidity.gnosis.ts index 60f19420c..77f9408cd 100644 --- a/balancer-js/examples/pools/liquidity/liquidity.gnosis.ts +++ b/balancer-js/examples/pools/liquidity/liquidity.gnosis.ts @@ -1,27 +1,27 @@ /** * Display APRs for pool ids hardcoded under `const ids` - * + * * Run command: * yarn example ./examples/pools/liquidity/liquidity.gnosis.ts */ -import { BalancerSDK } from '@balancer-labs/sdk' +import { BalancerSDK } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: 100, rpcUrl: 'https://rpc.ankr.com/gnosis', -}) +}); -const { pools } = sdk +const { pools } = sdk; const main = async () => { const pool = await pools.find( '0x0503dd6b2d3dd463c9bef67fb5156870af63393e000200000000000000000003' - ) + ); if (pool) { - const liquidity = await pools.liquidity(pool) - console.log(pool.id, pool.poolType, pool.totalLiquidity, liquidity) + const liquidity = await pools.liquidity(pool); + console.log(pool.id, pool.poolType, pool.totalLiquidity, liquidity); } -} +}; -main() +main(); diff --git a/balancer-js/examples/pools/liquidity/liquidity.polygon.ts b/balancer-js/examples/pools/liquidity/liquidity.polygon.ts index 9d864fd68..d13fdd6e9 100644 --- a/balancer-js/examples/pools/liquidity/liquidity.polygon.ts +++ b/balancer-js/examples/pools/liquidity/liquidity.polygon.ts @@ -4,24 +4,24 @@ * Run command: * yarn example ./examples/pools/liquidity/liquidity.polygon.ts */ -import { BalancerSDK } from '@balancer-labs/sdk' +import { BalancerSDK } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: 137, rpcUrl: 'https://rpc.ankr.com/polygon', -}) +}); -const { pools } = sdk +const { pools } = sdk; const main = async () => { const pool = await pools.find( '0xb797adfb7b268faeaa90cadbfed464c76ee599cd0002000000000000000005ba' - ) + ); if (pool) { - const liquidity = await pools.liquidity(pool) - console.log(pool.id, pool.poolType, pool.totalLiquidity, liquidity) + const liquidity = await pools.liquidity(pool); + console.log(pool.id, pool.poolType, pool.totalLiquidity, liquidity); } -} +}; -main() +main(); diff --git a/balancer-js/examples/pools/liquidity/liquidity.ts b/balancer-js/examples/pools/liquidity/liquidity.ts index 557bc3a81..14db7e57a 100644 --- a/balancer-js/examples/pools/liquidity/liquidity.ts +++ b/balancer-js/examples/pools/liquidity/liquidity.ts @@ -1,19 +1,19 @@ /** * How to get the liquidity of a pool - * + * * Run this example: * yarn example ./examples/pools/liquidity/liquidity.ts */ -import { BalancerSDK } from '@balancer-labs/sdk' +import { BalancerSDK } from '@balancer-labs/sdk'; const sdk = new BalancerSDK({ network: 1, rpcUrl: 'https://rpc.ankr.com/eth', -}) +}); -const { pools } = sdk +const { pools } = sdk; -;(() => { +(() => { [ '0xa13a9247ea42d743238089903570127dda72fe4400000000000000000000035d', '0x2f4eb100552ef93840d5adc30560e5513dfffacb000000000000000000000334', diff --git a/balancer-js/examples/pools/price-impact.ts b/balancer-js/examples/pools/price-impact.ts index 0f40887a8..d2596bfb7 100644 --- a/balancer-js/examples/pools/price-impact.ts +++ b/balancer-js/examples/pools/price-impact.ts @@ -1,6 +1,6 @@ /** * Example showing how to use SDK to get price impact for a join or exit operation. - * + * * Run with: * yarn example ./examples/pools/price-impact.ts */ @@ -9,7 +9,7 @@ import { Network, BalancerErrorCode, BalancerError, -} from '@balancer-labs/sdk' +} from '@balancer-labs/sdk'; async function getPriceImpact() { const network = Network.MAINNET; diff --git a/balancer-js/examples/pools/queries.ts b/balancer-js/examples/pools/queries.ts index 85cf977d7..7ebf5af86 100644 --- a/balancer-js/examples/pools/queries.ts +++ b/balancer-js/examples/pools/queries.ts @@ -5,9 +5,9 @@ * yarn example ./examples/pools/queries.ts */ -import { BalancerSDK, PoolWithMethods } from '@balancer-labs/sdk' -import { parseEther, formatEther } from '@ethersproject/units' -import { BigNumber } from "@ethersproject/bignumber"; +import { BalancerSDK, PoolWithMethods } from '@balancer-labs/sdk'; +import { parseEther, formatEther } from '@ethersproject/units'; +import { BigNumber } from '@ethersproject/bignumber'; const sdk = new BalancerSDK({ network: 1, @@ -22,18 +22,20 @@ const { // Joining with a single token const queryJoin = async (pool: PoolWithMethods) => { const token = pool.tokensList[0]; - const maxAmountsInByToken = new Map([[token, parseEther('1')]]); + const maxAmountsInByToken = new Map([ + [token, parseEther('1')], + ]); const joinExactInQuery = pool.buildQueryJoinExactIn({ - maxAmountsInByToken + maxAmountsInByToken, }); const response = await contracts.balancerHelpers.callStatic.queryJoin( ...joinExactInQuery ); - console.log(`Joining ${ pool.poolType }`); + console.log(`Joining ${pool.poolType}`); console.table({ - tokens: pool.tokensList.map((t) => `${ t.slice(0, 6) }...${ t.slice(38, 42) }`), + tokens: pool.tokensList.map((t) => `${t.slice(0, 6)}...${t.slice(38, 42)}`), amountsIn: response.amountsIn.map(formatEther), bptOut: formatEther(response.bptOut), }); @@ -50,9 +52,9 @@ const queryExit = async (pool: PoolWithMethods) => { ...exitToSingleToken ); - console.log(`Exiting ${ pool.poolType }`); + console.log(`Exiting ${pool.poolType}`); console.table({ - tokens: pool.tokensList.map((t) => `${ t.slice(0, 6) }...${ t.slice(38, 42) }`), + tokens: pool.tokensList.map((t) => `${t.slice(0, 6)}...${t.slice(38, 42)}`), amountsOut: response.amountsOut.map(formatEther), bptIn: formatEther(response.bptIn), }); @@ -70,7 +72,9 @@ const queryExit = async (pool: PoolWithMethods) => { ); for (const pool of [composableStable, weighted, metaStable]) { - await queryJoin(pool!); - await queryExit(pool!); + if (pool) { + await queryJoin(pool); + await queryExit(pool); + } } })(); diff --git a/balancer-js/examples/pools/rewards/claim-pools-rewards.ts b/balancer-js/examples/pools/rewards/claim-pools-rewards.ts index d1c78b2af..c5a0d2028 100644 --- a/balancer-js/examples/pools/rewards/claim-pools-rewards.ts +++ b/balancer-js/examples/pools/rewards/claim-pools-rewards.ts @@ -1,53 +1,66 @@ /** * Example of how to claim rewards from a gauge - * + * * Run with: * yarn example ./examples/pools/rewards/claim-pools-rewards.ts */ -import { BalancerSDK, Network } from '@balancer-labs/sdk' -import { reset } from 'examples/helpers' +import { BalancerSDK, Network } from '@balancer-labs/sdk'; +import { reset } from 'examples/helpers'; -const userAddress = '0x549c660ce2B988F588769d6AD87BE801695b2be3' +const userAddress = '0x549c660ce2B988F588769d6AD87BE801695b2be3'; const sdk = new BalancerSDK({ network: Network.MAINNET, - rpcUrl: 'http://localhost:8545', -}) + rpcUrl: 'http://127.0.0.1:8545', +}); -const { provider, claimService } = sdk +const { provider, claimService } = sdk; const main = async () => { - await reset(provider, 16361617) + await reset(provider, 16361617); - if (!claimService) throw new Error("ClaimService not defined"); + if (!claimService) throw new Error('ClaimService not defined'); - const balanceGauges = await claimService.getClaimableRewardTokens(userAddress); + const balanceGauges = await claimService.getClaimableRewardTokens( + userAddress + ); console.table(balanceGauges.map((it) => it.claimableTokens)); const gauges = balanceGauges.map((it) => it.address); - let data = await claimService.buildClaimRewardTokensRequest(gauges.slice(0,1), userAddress); - console.log(`\nSingle Gauge Claim ( gauge: ${gauges.slice(0,1)}) - to: ${data.to} - BalancerMinter Address ${sdk.networkConfig.addresses.contracts.balancerMinter} + let data = await claimService.buildClaimRewardTokensRequest( + gauges.slice(0, 1), + userAddress + ); + console.log(`\nSingle Gauge Claim ( gauge: ${gauges.slice(0, 1)}) + to: ${data.to} - BalancerMinter Address ${ + sdk.networkConfig.addresses.contracts.balancerMinter + } from: ${data.from} - User Address ${userAddress} tokensOut: ${data.tokensOut} expectedTokensValue: ${data.expectedTokensValue} functionName: ${data.functionName} - callData: ${data.callData.slice(0, 10)}...${data.callData.slice(-5)} - `) + callData: ${data.callData.slice(0, 10)}...${data.callData.slice( + -5 + )} + `); data = await claimService.buildClaimRewardTokensRequest(gauges, userAddress); console.log(`\nMultiple Gauges Claim - to: ${data.to} - BalancerMinter Address ${sdk.networkConfig.addresses.contracts.balancerMinter} + to: ${data.to} - BalancerMinter Address ${ + sdk.networkConfig.addresses.contracts.balancerMinter + } from: ${data.from} - User Address ${userAddress} tokensOut: ${data.tokensOut} expectedTokensValue: ${data.expectedTokensValue} functionName: ${data.functionName} - callData: ${data.callData.slice(0, 10)}...${data.callData.slice(-5)} - `) + callData: ${data.callData.slice(0, 10)}...${data.callData.slice( + -5 + )} + `); console.log(`\n\nfinally: const tx = { to: data.to', data: callData }; const receipt = await (await signer.sendTransaction(tx)).wait(); - `) + `); }; -main() \ No newline at end of file +main(); diff --git a/balancer-js/examples/pools/rewards/claim-vebal-rewards.ts b/balancer-js/examples/pools/rewards/claim-vebal-rewards.ts index ad79fe2d7..3895f3e8a 100644 --- a/balancer-js/examples/pools/rewards/claim-vebal-rewards.ts +++ b/balancer-js/examples/pools/rewards/claim-vebal-rewards.ts @@ -1,11 +1,11 @@ /** * Example of how to claim vebal rewards from a gauge - * + * * Run with: * yarn example ./examples/pools/rewards/claim-vebal-rewards.ts */ -import { BalancerSDK, Network } from '@balancer-labs/sdk' -import { reset } from 'examples/helpers' +import { BalancerSDK, Network } from '@balancer-labs/sdk'; +import { reset } from 'examples/helpers'; const userAddress = '0x549c660ce2B988F588769d6AD87BE801695b2be3'; const claimableTokens: string[] = [ @@ -14,35 +14,44 @@ const claimableTokens: string[] = [ '0xba100000625a3754423978a60c9317c58a424e3D', // BAL ]; -const sdk = new BalancerSDK( - { - network: Network.MAINNET, - rpcUrl: 'http://127.0.0.1:8545' - }) +const sdk = new BalancerSDK({ + network: Network.MAINNET, + rpcUrl: 'http://127.0.0.1:8545', +}); const { provider, claimService } = sdk; const main = async () => { - await reset(provider, 16361617) + await reset(provider, 16361617); - if (!claimService) throw new Error("ClaimService not defined"); + if (!claimService) throw new Error('ClaimService not defined'); - const balance = await claimService.getClaimableVeBalTokens(userAddress, claimableTokens); + const balance = await claimService.getClaimableVeBalTokens( + userAddress, + claimableTokens + ); console.table(balance); - const data = await claimService.buildClaimVeBalTokensRequest(userAddress, claimableTokens); + const data = await claimService.buildClaimVeBalTokensRequest( + userAddress, + claimableTokens + ); console.log(` - to: ${data.to} - BalancerMinter Address ${sdk.networkConfig.addresses.contracts.feeDistributor} + to: ${data.to} - BalancerMinter Address ${ + sdk.networkConfig.addresses.contracts.feeDistributor + } from: ${data.from} - User Address ${userAddress} tokensOut: ${data.tokensOut} expectedTokensValue: ${data.expectedTokensValue} functionName: ${data.functionName} - callData: ${data.callData.slice(0, 10)}...${data.callData.slice(-5)} - `) + callData: ${data.callData.slice(0, 10)}...${data.callData.slice( + -5 + )} + `); console.log(`\n\nfinally: const tx = { to: data.to', data: callData }; const receipt = await (await signer.sendTransaction(tx)).wait(); - `) -} + `); +}; -main() +main(); diff --git a/balancer-js/examples/pools/spot-price.ts b/balancer-js/examples/pools/spot-price.ts index 0ef6cacff..4ed41add8 100644 --- a/balancer-js/examples/pools/spot-price.ts +++ b/balancer-js/examples/pools/spot-price.ts @@ -1,7 +1,7 @@ /** * Uses SDK to find spot price for pair in specific pool. * Uses SDK to find most liquid path for a pair and calculate spot price. - * + * * Run with: * yarn example ./examples/pools/spot-price.ts */ diff --git a/balancer-js/examples/pools/staking/gauge-deposit.ts b/balancer-js/examples/pools/staking/gauge-deposit.ts index 59b0e4471..8477e604a 100644 --- a/balancer-js/examples/pools/staking/gauge-deposit.ts +++ b/balancer-js/examples/pools/staking/gauge-deposit.ts @@ -1,45 +1,45 @@ /** * This example shows how to deposit liquidity in a liquidity gauge - * + * * Prerequisite: user must have approved the transfer of his LP tokens by the gauge - * + * * Note: this example uses a forked mainnet for illustraion purpose. - * + * * How to run: - * npm run example examples/gauge-deposit.ts + * yarn example examples/pools/staking/gauge-deposit.ts */ import { BalancerSDK } from '@balancer-labs/sdk'; -import { reset, setTokenBalance } from 'examples/helpers' +import { reset, setTokenBalance } from 'examples/helpers'; -const poolAddress = '0x32296969ef14eb0c6d29669c550d4a0449130230' -const gaugeAddress = '0xcd4722b7c24c29e0413bdcd9e51404b4539d14ae' -const poolBalance = String(BigInt(1e18)) +const poolAddress = '0x32296969ef14eb0c6d29669c550d4a0449130230'; +const gaugeAddress = '0xcd4722b7c24c29e0413bdcd9e51404b4539d14ae'; +const poolBalance = String(BigInt(1e18)); const main = async () => { const sdk = new BalancerSDK({ network: 1, - rpcUrl: `http://127.0.0.1:8545` + rpcUrl: `http://127.0.0.1:8545`, }); - const { contracts, provider } = sdk - const signer = provider.getSigner() - const account = await signer.getAddress() + const { contracts, provider } = sdk; + const signer = provider.getSigner(); + const account = await signer.getAddress(); // Setting up the forked state - await reset(provider, 16940000) - await setTokenBalance(provider, account, poolAddress, poolBalance, 0) - await contracts.ERC20(poolAddress, signer).approve(gaugeAddress, poolBalance) + await reset(provider, 16940000); + await setTokenBalance(provider, account, poolAddress, poolBalance, 0); + await contracts.ERC20(poolAddress, signer).approve(gaugeAddress, poolBalance); - const gauge = contracts.liquidityGauge(gaugeAddress, signer) + const gauge = contracts.liquidityGauge(gaugeAddress, signer); - let balance = await gauge.balanceOf(account) - console.log('User balance before :', String(balance)) + let balance = await gauge.balanceOf(account); + console.log('User balance before :', String(balance)); - console.log(`Deposing ${poolBalance} into the gauge. Wait ...`) - await (await gauge['deposit(uint256)'](poolBalance)).wait() + console.log(`Deposing ${poolBalance} into the gauge. Wait ...`); + await (await gauge['deposit(uint256)'](poolBalance)).wait(); - balance = await gauge.balanceOf(account) - console.log('User balance after :', String(balance)) -} + balance = await gauge.balanceOf(account); + console.log('User balance after :', String(balance)); +}; -main() +main(); diff --git a/balancer-js/examples/swaps/advanced.ts b/balancer-js/examples/swaps/advanced.ts index 7a01cc197..7c37101cc 100644 --- a/balancer-js/examples/swaps/advanced.ts +++ b/balancer-js/examples/swaps/advanced.ts @@ -2,7 +2,7 @@ * Example showing how to find a swap for a pair using SOR directly * - Path only uses swaps: use queryBatchSwap on Vault to see result * - Path use join/exit: Use SDK functions to build calls to submit tx via Relayer - * + * * Run command: * yarn example ./examples/swaps/advanced.ts */ @@ -13,10 +13,10 @@ import { someJoinExit, buildRelayerCalls, canUseJoinExit, -} from '@balancer-labs/sdk' -import { BigNumber, parseFixed } from '@ethersproject/bignumber' -import { Wallet } from '@ethersproject/wallet' -import { AddressZero } from '@ethersproject/constants' +} from '@balancer-labs/sdk'; +import { BigNumber, parseFixed } from '@ethersproject/bignumber'; +import { Wallet } from '@ethersproject/wallet'; +import { AddressZero } from '@ethersproject/constants'; async function getAndProcessSwaps( balancer: BalancerSDK, @@ -53,7 +53,7 @@ async function getAndProcessSwaps( someJoinExit(pools, swapInfo.swaps, swapInfo.tokenAddresses) ) { console.log(`Swaps with join/exit paths. Must submit via Relayer.`); - const key: any = process.env.TRADER_KEY; + const key = process.env.TRADER_KEY as string; const wallet = new Wallet(key, balancer.sor.provider); const slippage = '50'; // 50 bsp = 0.5% try { @@ -75,13 +75,13 @@ async function getAndProcessSwaps( ?.connect(wallet) .callStatic.multicall(relayerCallData.rawCalls); console.log(result); - } catch (err: any) { + } catch (err: any) { // eslint-disable-line // If error we can reprocess without join/exit paths console.log(`Error Using Join/Exit Paths`, err.reason); await getAndProcessSwaps( balancer, - tokenIn!, - tokenOut!, + tokenIn, + tokenOut, swapType, amount, false @@ -126,7 +126,7 @@ async function swapExample() { const swapType = SwapTypes.SwapExactIn; const amount = parseFixed('20', 18); // Currently Relayer only suitable for ExactIn and non-eth swaps - const canUseJoinExitPaths = canUseJoinExit(swapType, tokenIn!, tokenOut!); + const canUseJoinExitPaths = canUseJoinExit(swapType, tokenIn, tokenOut); const balancer = new BalancerSDK({ network, @@ -138,8 +138,8 @@ async function swapExample() { await getAndProcessSwaps( balancer, - tokenIn!, - tokenOut!, + tokenIn, + tokenOut, swapType, amount, canUseJoinExitPaths diff --git a/balancer-js/examples/swaps/query.ts b/balancer-js/examples/swaps/query.ts index 244ccd1a3..79a9be58c 100644 --- a/balancer-js/examples/swaps/query.ts +++ b/balancer-js/examples/swaps/query.ts @@ -1,20 +1,20 @@ /** * Example showing how to find a swap for a pair and use queryBatchSwap to simulate result on the Vault. */ -import { BalancerSDK, Network } from '@balancer-labs/sdk' -import { parseFixed } from '@ethersproject/bignumber' +import { BalancerSDK, Network } from '@balancer-labs/sdk'; +import { parseFixed } from '@ethersproject/bignumber'; const balancer = new BalancerSDK({ network: Network.MAINNET, rpcUrl: 'https://rpc.ankr.com/eth', -}) +}); -const { swaps } = balancer +const { swaps } = balancer; -const tokenIn = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' // WETH -const tokenOut = '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0' // wstETH -const amount = parseFixed('1', 18) -const gasPrice = parseFixed('0', 18) +const tokenIn = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; // WETH +const tokenOut = '0x7f39c581f595b53c5cb19bd0b3f8da6c935e2ca0'; // wstETH +const amount = parseFixed('1', 18); +const gasPrice = parseFixed('0', 18); async function findSwapAndQueryTheVault() { // Fetch all pools for SOR to use @@ -26,21 +26,21 @@ async function findSwapAndQueryTheVault() { tokenOut, amount, gasPrice, - maxPools: 1 - }) + maxPools: 1, + }); if (swapInfo.returnAmount.isZero()) { - console.log('No Swap') - return + console.log('No Swap'); + return; } // Simulates a call to `batchSwap`, returning an array of Vault asset deltas. - const deltas = await swaps.queryExactIn(swapInfo) + const deltas = await swaps.queryExactIn(swapInfo); // Prints the asset deltas for the swap. // Positive values mean the user sending the asset to the vault, and negative is the amount received from the vault. // The asset deltas should be the same as the ones returned by `batchSwap`. - console.log(deltas) + console.log(deltas); } -findSwapAndQueryTheVault() +findSwapAndQueryTheVault(); diff --git a/balancer-js/examples/swaps/swap.ts b/balancer-js/examples/swaps/swap.ts index 98924d382..6b0f37929 100644 --- a/balancer-js/examples/swaps/swap.ts +++ b/balancer-js/examples/swaps/swap.ts @@ -1,29 +1,32 @@ /** * How to build a swap and send it using ethers.js - * + * * How to run: * yarn example examples/swaps/swap.ts */ -import { BalancerSDK, Network } from '@balancer-labs/sdk' -import { formatFixed } from '@ethersproject/bignumber' -import { AddressZero } from '@ethersproject/constants' +import { BalancerSDK, Network } from '@balancer-labs/sdk'; +import { formatFixed } from '@ethersproject/bignumber'; +import { AddressZero } from '@ethersproject/constants'; +import { reset } from 'examples/helpers/forked-utils'; -const tokenIn = AddressZero // eth -const tokenOut = '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599' // wBTC -const amount = String(BigInt(100e18)) // 100 eth +const tokenIn = AddressZero; // eth +const tokenOut = '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599'; // wBTC +const amount = String(BigInt(100e18)); // 100 eth const sdk = new BalancerSDK({ network: Network.MAINNET, rpcUrl: `http://127.0.0.1:8545`, // Uses a local fork for simulating transaction sending. -}) +}); -const { swaps } = sdk +const { swaps } = sdk; -const erc20Out = sdk.contracts.ERC20(tokenOut, sdk.provider) +const erc20Out = sdk.contracts.ERC20(tokenOut, sdk.provider); async function swap() { - const signer = sdk.provider.getSigner() - const account = await signer.getAddress() + await reset(sdk.provider); + + const signer = sdk.provider.getSigner(); + const account = await signer.getAddress(); // Finding a trading route rely on on-chain data. // fetchPools will fetch the current data from the subgraph. @@ -40,33 +43,33 @@ async function swap() { }, orderBy: 'totalLiquidity', orderDirection: 'desc', - }) + }); // Set exectution deadline to 60 seconds from now - const deadline = String(Math.ceil(Date.now() / 1000) + 60) + const deadline = String(Math.ceil(Date.now() / 1000) + 60); // Avoid getting rekt by setting low slippage from expected amounts out, 10 bsp = 0.1% - const maxSlippage = 10 + const maxSlippage = 10; // Building the route payload const payload = await swaps.buildRouteExactIn( account, account, - tokenIn, // eth + tokenIn, // eth tokenOut, // wBTC amount, { maxSlippage, - deadline + deadline, } - ) + ); // Extract parameters required for sendTransaction - const { to, data, value } = payload + const { to, data, value } = payload; // Execution with ethers.js try { - const balanceBefore = await erc20Out.balanceOf(account) + const balanceBefore = await erc20Out.balanceOf(account); await ( await signer.sendTransaction({ @@ -74,20 +77,20 @@ async function swap() { data, value, }) - ).wait() + ).wait(); // check delta - const balanceAfter = await erc20Out.balanceOf(account) + const balanceAfter = await erc20Out.balanceOf(account); console.log( `Amount of BTC received: ${formatFixed( balanceAfter.sub(balanceBefore), 8 )}` - ) + ); } catch (err) { - console.log(err) + console.log(err); } } -swap() +swap(); diff --git a/balancer-js/src/modules/swaps/swaps.module.ts b/balancer-js/src/modules/swaps/swaps.module.ts index 7b224d048..82c131816 100644 --- a/balancer-js/src/modules/swaps/swaps.module.ts +++ b/balancer-js/src/modules/swaps/swaps.module.ts @@ -289,7 +289,7 @@ export class Swaps { */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async fetchPools(queryArgs?: GraphQLArgs): Promise { - return this.sor.fetchPools(); + return this.sor.fetchPools(queryArgs); } public getPools(): SubgraphPoolBase[] {