import { ethers } from "ethers";
import {
BalancerApi,
AddLiquidity,
AddLiquidityKind,
Slippage,
PriceImpact,
} from "@berachain-foundation/berancer-sdk";
// Initialize provider and wallet
const RPC_URL = "https://rpc.berachain.com/";
const provider = new ethers.JsonRpcProvider(RPC_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const balancerApi = new BalancerApi("https://chgbtcc9ffu7rbdw2kmu4urwy.stellate.sh/", 80094);
// Get pool data
const poolId =
"POOL_ID";
const poolState = await balancerApi.pools.fetchPoolState(poolId);
// Prepare add liquidity input - note we're only adding one token for unbalanced
const addLiquidityInput = {
chainId: CHAIN_ID,
kind: AddLiquidityKind.Unbalanced,
rpcUrl: RPC_URL,
amountsIn: [
{
address: WBERA_TOKEN,
decimals: 18,
rawAmount: ethers.parseUnits("0.1", 18), // 0.1 BERA
},
],
};
const addLiquidity = new AddLiquidity();
// Query expected BPT out and calculate price impact in parallel
const [queryOutput, priceImpact] = await Promise.all([
addLiquidity.query(addLiquidityInput, poolState),
PriceImpact.addLiquidity(addLiquidityInput, poolState)
]);
console.log(
"Expected BPT Out:",
ethers.formatUnits(queryOutput.bptOut.amount, 18)
);
console.log("Price Impact:", priceImpact.percentage, "%");
// Build transaction with 1% slippage
const slippage = Slippage.fromPercentage("1");
const deadline = BigInt(Math.floor(Date.now() / 1000) + 60);
const callData = addLiquidity.buildCall({
...queryOutput,
chainId: CHAIN_ID,
sender: wallet.address,
poolId: poolState.id,
recipient: wallet.address,
wethIsEth: true,
slippage,
deadline,
});
// Send transaction
const tx = await wallet.sendTransaction({
to: callData.to,
data: callData.callData,
value: callData.value,
});
console.log("Transaction sent:", tx.hash);
const receipt = await tx.wait();