Skip to content

Commit

Permalink
Merge pull request #406 from balancer/develop
Browse files Browse the repository at this point in the history
Release 1.0.3
  • Loading branch information
johngrantuk authored Apr 5, 2023
2 parents 4d0e1dd + b21ba14 commit b871bb8
Show file tree
Hide file tree
Showing 159 changed files with 28,791 additions and 4,757 deletions.
202 changes: 71 additions & 131 deletions balancer-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,34 +132,6 @@ swaps.queryBatchSwap(batchSwap: {

[Example](./examples/queryBatchSwap.ts)

### #queryBatchSwapWithSor

Uses SOR to create and query a batchSwap for multiple tokens in > multiple tokensOut.

@param queryWithSor - Swap information used for querying using SOR.
@param queryWithSor.tokensIn - Array of addresses of assets in.
@param queryWithSor.tokensOut - Array of addresses of assets out.
@param queryWithSor.swapType - Type of Swap, ExactIn/Out.
@param queryWithSor.amounts - Array of amounts used in swap.
@param queryWithSor.fetchPools - Set whether SOR will fetch updated pool info.
@returns Returns amount of tokens swaps along with swap and asset info that can be submitted to a batchSwap call.

```js
swaps.queryBatchSwapWithSor(queryWithSor: {
tokensIn: string[],
tokensOut: string[],
swapType: SwapType,
amounts: BigNumberish[],
fetchPools: FetchPoolsInput;
}):
Promise<QueryWithSorOutput {
returnAmounts: string[];
swaps: BatchSwapStep[];
assets: string[];
deltas: string[];
}>
```

### #encodeBatchSwap

Static method to encode a [batch swap](https://dev.balancer.fi/references/contracts/apis/the-vault#batch-swaps).
Expand Down Expand Up @@ -378,6 +350,32 @@ buildJoin: (
) => JoinPoolAttributes;
```

where `JoinPoolAttributes` is:

```js
/**
* Join with exact tokens in transaction parameters
* @param to Address that will execute the transaction (vault address)
* @param functionName Function name to be called (joinPool)
* @param attributes Transaction attributes ready to be encoded
* @param data Encoded transaction data
* @param value (Optional) ETH amount that must be informed when joining with ETH
* @param minBptOut Minimum BPT amoutn out of join transaction considering slippage tolerance
* @param expectedBptOut Expected BPT amount out of join transaction
* @param priceImpact Price impact of join transaction
*/
export interface JoinPoolAttributes {
to: string;
functionName: string;
attributes: JoinPool;
data: string;
value?: BigNumber;
minBPTOut: string;
expectedBPTOut: string;
priceImpact: string;
}
```

[Example](./examples/join.ts)

### #buildInitJoin (Weighted Pool)
Expand All @@ -404,6 +402,7 @@ buildInitJoin({
Available pool types:

- Weighted
- ComposableStable ([Example](./examples/pools/composable-stable/init-join.ts))

### Joining nested pools

Expand Down Expand Up @@ -616,11 +615,10 @@ async generalisedExit(

[Example](./examples/exitGeneralised.ts)

## Create Pool

Exposes create functionality allowing user to create pools.
# Factory
### Creating Pools

### #createWeightedPool
### WeightedPool

Builds a transaction to create a weighted pool.

Expand All @@ -644,12 +642,15 @@ create({
weights,
swapFee,
owner,
}) => TransactionRequest
}) => {
to?: string;
data: BytesLike;
}
```

[Example](./examples/pools/weighted/create.ts)
[Example](./examples/pools/weighted/create-and-init-join.ts)

### #createComposableStablePool
### Composable Stable Pool

Builds a transaction to create a composable stable pool.

Expand Down Expand Up @@ -679,11 +680,44 @@ create({
exemptFromYieldProtocolFeeFlags,
swapFee,
owner,
}) => TransactionRequest
}) => {
to?: string;
data: BytesLike;
}
```
[Example](./examples/pools/composable-stable/create-and-init-join.ts)

### Linear Pool

[Example](./examples/pools/composable-stable/create.ts)
Builds a transaction to create a linear pool.

```js
/**
*
* @param name The name of the pool
* @param symbol The symbol of the pool (BPT name)
* @param mainToken The unwrapped token
* @param wrappedToken The wrapped token
* @param upperTarget The maximum balance of the unwrapped(main) token (normal number, no need to fix to 18 decimals)
* @param swapFeeEvm The swap fee of the pool
* @param owner The address of the owner of the pool
* @param protocolId The protocolId, to check the available value
*/
create({
name,
symbol,
mainToken,
wrappedToken,
upperTarget,
swapFeeEvm,
owner,
protocolId,
}: LinearCreatePoolParameters) => {
to?: string;
data: BytesLike;
}
```
[Example](./examples/pools/linear/create.ts)
## RelayerService

Relayers are (user opt-in, audited) contracts that can make calls to the vault (with the transaction “sender” being any arbitrary address) and use the sender’s ERC20 vault allowance, internal balance or BPTs on their behalf.
Expand All @@ -695,100 +729,6 @@ const relayer = new relayerService(
);
```

### #swapUnwrapAaveStaticExactIn

Finds swaps for tokenIn>wrapped Aave static tokens and chains with unwrap to underlying stable. ExactIn - Exact amount of tokenIn to use in swap.

@param tokensIn - array to token addresses for swapping as tokens in.
@param aaveStaticTokens - array contains the addresses of the Aave static tokens that tokenIn will be swapped to. These will be unwrapped.
@param amountsIn - amounts to be swapped for each token in.
@param rates - The rate used to convert wrappedToken to underlying.
@param funds - Funding info for swap. Note - recipient should be relayer and sender should be caller.
@param slippage - Slippage to be applied to swap section. i.e. 5%=50000000000000000.
@param fetchPools - Set whether SOR will fetch updated pool info.
@returns Transaction data with calldata. Outputs.amountsOut has final amounts out of unwrapped tokens.

```js
async relayer.swapUnwrapAaveStaticExactIn(
tokensIn: string[],
aaveStaticTokens: string[],
amountsIn: BigNumberish[],
rates: BigNumberish[],
funds: FundManagement,
slippage: BigNumberish,
fetchPools: FetchPoolsInput = {
fetchPools: true,
fetchOnChain: false
}
): Promise<TransactionData>
```

[Example](./examples/relayerSwapUnwrap.ts)

### #swapUnwrapAaveStaticExactOut

Finds swaps for tokenIn>wrapped Aave static tokens and chains with unwrap to underlying stable. ExactOut - Exact amount of tokens out are used for swaps.

@param tokensIn - array to token addresses for swapping as tokens in.
@param aaveStaticTokens - array contains the addresses of the Aave static tokens that tokenIn will be swapped to. These will be unwrapped.
@param amountsUnwrapped - amounts of unwrapped tokens out.
@param rates - The rate used to convert wrappedToken to underlying.
@param funds - Funding info for swap. Note - recipient should be relayer and sender should be caller.
@param slippage - Slippage to be applied to swap section. i.e. 5%=50000000000000000.
@param fetchPools - Set whether SOR will fetch updated pool info.
@returns Transaction data with calldata. Outputs.amountsIn has the amounts of tokensIn.

```js
async relayer.swapUnwrapAaveStaticExactOut(
tokensIn: string[],
aaveStaticTokens: string[],
amountsUnwrapped: BigNumberish[],
rates: BigNumberish[],
funds: FundManagement,
slippage: BigNumberish,
fetchPools: FetchPoolsInput = {
fetchPools: true,
fetchOnChain: false
}
): Promise<TransactionData>
```

[Example](./examples/relayerSwapUnwrap.ts)

### #exitPoolAndBatchSwap

Chains poolExit with batchSwap to final tokens.

@param params:
@param exiter - Address used to exit pool.
@param swapRecipient - Address that receives final tokens.
@param poolId - Id of pool being exited.
@param exitTokens - Array containing addresses of tokens to receive after exiting pool. (must have the same length and order as the array returned by `getPoolTokens`.)
@param userData - Encoded exitPool data.
@param minExitAmountsOut - Minimum amounts of exitTokens to receive when exiting pool.
@param finalTokensOut - Array containing the addresses of the final tokens out.
@param slippage - Slippage to be applied to swap section. i.e. 5%=50000000000000000.
@param fetchPools - Set whether SOR will fetch updated pool info.
@returns Transaction data with calldata. Outputs.amountsOut has amounts of finalTokensOut returned.

```js
async relayer.exitPoolAndBatchSwap(
params: ExitAndBatchSwapInput {
exiter: string;
swapRecipient: string;
poolId: string;
exitTokens: string[];
userData: string;
minExitAmountsOut: string[];
finalTokensOut: string[];
slippage: string;
fetchPools: FetchPoolsInput;
}
): Promise<TransactionData>
```

[Example](./examples/relayerExitPoolAndBatchSwap.ts)

## Pools Impermanent Loss

> impermanent loss (IL) describes the percentage by which a pool is worth less than what one would have if they had instead just held the tokens outside the pool
Expand Down
4 changes: 2 additions & 2 deletions balancer-js/examples/data/token-yields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
* Display token yields
* Run command: yarn examples:run ./examples/data/token-yields.ts
*/
import { BalancerSDK } from '../../src/modules/sdk.module';
import { yieldTokens } from '../../src/modules/data/token-yields/tokens/aave';
import { BalancerSDK } from '@/modules/sdk.module';
import { yieldTokens } from '@/modules/data/token-prices/aave-rates';

const sdk = new BalancerSDK({ network: 1, rpcUrl: '' });
const { data } = sdk;
Expand Down
8 changes: 4 additions & 4 deletions balancer-js/examples/exitGeneralised.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ dotenv.config();

const network = Network.MAINNET;
const jsonRpcUrl = process.env.ALCHEMY_URL;
const blockNumber = 16685400;
const blockNumber = 16940624;
const rpcUrl = 'http://127.0.0.1:8545';
const customSubgraphUrl =
'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-v2';

const addresses = ADDRESSES[network];

// bb-e-usd
const testPool = addresses.bbeusd;
// bb-a-usd
const testPool = addresses.bbausd2;

// Amount of testPool BPT that will be used to exit
const amount = parseFixed('2', testPool.decimals).toString();
Expand Down Expand Up @@ -146,7 +146,7 @@ const exit = async () => {
provider
);
const relayerAuth = await Relayer.signRelayerApproval(
contractAddresses.relayerV4 as string,
contractAddresses.relayerV5 as string,
signerAddress,
signer,
contracts.vault
Expand Down
39 changes: 20 additions & 19 deletions balancer-js/examples/helpers/print-logs.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any */
import dotenv from 'dotenv';
import { ethers } from 'ethers';
import { Contract } from '@ethersproject/contracts';
import { formatEther } from '@ethersproject/units';
import { shortenAddress } from '.';
import { formatEther } from 'ethers/lib/utils'

dotenv.config();
const { ETHERSCAN_API_KEY } = process.env;
Expand All @@ -15,7 +16,7 @@ const abis = new Map<string, any>();

const decodeLog = async (log: any, abi: any) => {
let decoded;
const contract = new ethers.Contract(log.address, abi);
const contract = new Contract(log.address, abi);

try {
decoded = contract.interface.parseLog(log);
Expand All @@ -39,7 +40,7 @@ export const decodeLogs = async (logs: any[]) => {
abis.set(log.address, abi);
}
const decoded = await decodeLog(log, abi);
if (decoded) decodedLogs.push({...decoded, address: log.address});
if (decoded) decodedLogs.push({ ...decoded, address: log.address });
}

return decodedLogs;
Expand All @@ -57,34 +58,34 @@ export const printLogs = async (logs: any[]) => {
amountIn: formatEther(amountIn),
amountOut: formatEther(amountOut),
}))
)
}
);
};

const printPoolBalanceChanged = (log: any) => {
console.log(log.args.poolId)
console.log(log.args.poolId);
console.table({
tokens: log?.args.tokens.map(shortenAddress),
deltas: log?.args.deltas.map((delta: string) => formatEther(delta)),
})
}
});
};

const printTransfer = (log: any) => {
console.log(log.address);
const { from, to, value, src, dst, wad } = log.args
console.log('\x1b[32m%s\x1b[0m', 'From: ', from || src)
console.log('\x1b[32m%s\x1b[0m', 'To: ', to || dst)
console.log('\x1b[32m%s\x1b[0m', 'Value:', formatEther(value || wad))
}
const { from, to, value, src, dst, wad } = log.args;
console.log('\x1b[32m%s\x1b[0m', 'From: ', from || src);
console.log('\x1b[32m%s\x1b[0m', 'To: ', to || dst);
console.log('\x1b[32m%s\x1b[0m', 'Value:', formatEther(value || wad));
};

decodedLogs.map((log) => {
console.log('-'.repeat(80))
console.log(log.name)
console.log('-'.repeat(80));
console.log(log.name);
if (log.name === 'Swap') {
printSwap(log)
printSwap(log);
} else if (log.name === 'PoolBalanceChanged') {
printPoolBalanceChanged(log)
printPoolBalanceChanged(log);
} else if (log.name === 'Transfer') {
printTransfer(log)
printTransfer(log);
}
});
};
4 changes: 2 additions & 2 deletions balancer-js/examples/joinGeneralised.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ dotenv.config();
// -- Mainnet network setup --
const network = Network.MAINNET;
const jsonRpcUrl = process.env.ALCHEMY_URL;
const blockNumber = 16075635;
const blockNumber = 16940624;
const rpcUrl = 'http://127.0.0.1:8545';
const customSubgraphUrl =
'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-v2-beta';
Expand Down Expand Up @@ -164,7 +164,7 @@ async function join() {
provider
);
const authorisation = await Relayer.signRelayerApproval(
contractAddresses.relayerV4 as string,
contractAddresses.relayerV5 as string,
signerAddress,
signer,
contracts.vault
Expand Down
Loading

0 comments on commit b871bb8

Please sign in to comment.