What is Balancer?

Balancer is very similar to Uniswap. If you're not familiar with Uniswap or Balancer yet, they are fully decentralized protocols for automated liquidity provision on Ethereum. An easier-to-understand description would be that they are decentralized exchanges (DEX) relying on external liquidity providers that can add tokens to smart contract pools and users can trade those directly.

Since Balancer is running on Ethereum, what we can trade are Ethereum ERC-20 tokens. Balancer - being fully decentralized - has no restrictions to which tokens can be added or even how many pools can be created per token.

Balancer Pools cannot be censored or whitelisted. Traders cannot be censored or whitelisted. Balancer Labs does not have the power to stop or edit the smart contracts in any way after they’ve been deployed. There is no upgradeability, admin functionalities, or backdoors in the contracts.

Balancer Labs

Balancer UI

What is different compared to Uniswap?

In Uniswap v2, a factory creates one pool per token pair. Later Uniswap versions can have multiple pools for a pair with different fee or hook configurations. In contrast in Balancer you can have multiple tokens in a single pool with different relations. Take a look at https://pools.balancer.exchange/#/:

balancer-pools

You'll see that a pool can have different balances for each token. What that means for liquidity providers is that they can have exposure to different assets without having to deal with complicated and/or expensive rebalancing procedures over different pools. They can pick or even create a pool that suits their needs and provide liquidity for it.

Weights describe the pool’s target value proportions, not fixed token counts. Trading changes reserves and quoted prices. Arbitrage can align those prices with the external market, subject to fees and available liquidity; the contract does not instantly restore a balance ratio after every trade.

How are pools rebalanced?

In each pool there's a multi-dimensional invariant function which defines swap prices between any two tokens in any pool. This is the heart of the mechanism and allows the rebalancing. Given defined prices for each token swap, a pool can be balanced the following:

Imagine a trade in a 50:50 DAI/WETH weighted pool. Buying DAI changes the reserves and the relative price quoted by the invariant. Other traders may then trade in the opposite direction if the pool price differs sufficiently from external prices after fees. Equal weights do not mean equal token quantities, and a one-percent trade does not imply exact 49/51 reserve proportions.

Thanos Balance

Smart Order Routing (SOR)

The SOR is a conceptual way of dealing with pools to optimize the profit for a trader. They also have an off-chain JavaScript solution available, source code is here. You would use this in the frontend and you can see in the Exchange UI code, that's what they do.

The exact motivation behind SOR is perfectly described in the documentation:

'Since there might be many Balancer pools that contain a given pair, trading only with the most liquid pool is not ideal. The fact that after a one-pool-trade arbitrageurs can profit by levelling all pool prices means the one-pool trader left value on the table.

The ideal solution in a world where there were no gas costs or gas limits would be to trade with all pools available in the desired pair. The amount traded with each pool should move them all to the same new spot price. This would mean all pools would be in an arbitrage free state and no value could be further extracted by arbitrageurs (which always comes at the expense of the trader).

As there are incremental gas costs associated with interacting with each additional Balancer pool, SOR makes sure that the increase in the returns an incremental pool brings exceeds the incremental gas costs. This is an optimization problem that depends therefore on the gas fees paid to the Ethereum network: a higher gas price may cause SOR to select less pools than otherwise.'

Future versions

Albert Einstein Bronze
Two silver-colored rings set with clear gemstones.
Gold Bitcoins
  • Bronze: The initial release from earlier this year.
  • Silver: Silver is currently in a design phase with an expected release date in late 2020.
  • Gold: Final version.


The Silver version will include most notably an on-chain SOR (unless this feature comes only in the Gold release).

This Bronze/Silver/Gold list was the 2020 roadmap. Current documentation describes Balancer v3; these names and forecasts are not a current integration plan.

Further Balancer resources

Integrating Balancer Bronze into contracts

Now to integrate Balancer, you need to choose a pool or a mix of pools. You could add the SOR feature to find the optimal pools to maximize every bit for the user. This is beyond the scope of the tutorial and not really required if users aren't transferring massive amounts of value.

If you want to do this via SOR, install the @balancer-labs/sor package in the frontend app. Use it to find out the optimal swap strategy. The result will be an array of Swap definitions (how much to trade in which pool). Then you can pass these Swap definitions to the smart contract and execute each one.

We will instead be doing only a single swap. Let's use again DAI and WETH in the Kovan testnet. You can interact with the Kovan contracts in the frontend via:


Let's choose the DAI/WETH/MKR pool: https://kovan.pools.balancer.exchange/#/pool/0x1492b5b01350b7c867185a643f2e59f7be279fd3/. For a mainnet contract, make sure that the pool has very high liquidity if you're using only a single pool. Now let's try and enable ETH payments that are actually converted to DAI, so a user has the choice between paying in DAI or in ETH:


The Kovan URLs and chosen pool are historical. Select the version, chain and verified deployment from the current documentation before any new integration.

Adding ETH payments as alternative

solidity
function pay(uint paymentAmountInDai) public payable {
      if (msg.value > 0) {
          _swapEthForDai(paymentAmountInDai);
      } else {
          require(daiToken.transferFrom(msg.sender, address(this), paymentAmountInDai));
      }

      // do something with that DAI
      ...
}

A simple check like this at the beginning of your function will be enough. Now as for the _swapEthForDai function, it will look like something this:

This is an outline: the application must authenticate its required payment amount, enforce a caller-chosen expiry and suitable price bounds, and complete checks and accounting before external interactions. Pool liquidity alone is not a price guarantee.

Converting the ETH to DAI

solidity
function _swapEthForDai(uint daiAmount) private {
    _wrapEth(); // wrap ETH and approve to balancer pool

    (uint amountIn,) = PoolInterface(bPool).swapExactAmountOut(
        address(weth),
        msg.value, // this call must not spend pre-existing WETH
        address(daiToken),
        daiAmount,
        type(uint).max // maxPrice, set to max -> accept any swap prices
    );

    // Keep the exact DAI output here as payment.
    _refundLeftoverEth(msg.value - amountIn);
}

There are several things to unpack here.

  • WETH: You might notice that we are using WETH here. In Balancer there are no direct ETH pairs, all ETH must be converted to WETH first.
  • swapExactAmountOut: This function can be used to receive an exact amount of tokens for it. Any leftover tokens not required will be refunded, so make sure you have the fallback function in your contract. If you instead want the other way around to use an exact amount of ETH to pay, use the swapExactAmountIn.
  • Refund: Once the trade is finished, we can return any leftover ETH to the user. The corrected example refunds only the unused input from this call, preserving any unrelated ETH or WETH balance.

Wrapping the initial ETH

As for the _wrapEth function, you simply deposit the the ETH into the WETH contract and approve it for the balancer pool:

solidity
function _wrapEth() private {
    weth.deposit{ value: msg.value }();
    
    if (weth.allowance(address(this), address(bPool)) < msg.value) {
        weth.approve(address(bPool), type(uint).max);
    }
}

Refunding leftover ETH

The opposite is happening inside _refundLeftoverEth, we withdraw any leftover WETH and then return any ETH to the user.

solidity
function _refundLeftoverEth(uint wethBalance) private {

    if (wethBalance > 0) {
        // refund leftover ETH
        weth.withdraw(wethBalance);
        (bool success,) = msg.sender.call{ value: wethBalance }("");
        require(success, "ERR_ETH_FAILED");
    }
}

And let's not forget to add a fallback function to receive refunded ETH:

solidity
receive() external payable {}

And lastly, you'll also need the interface definitions:

solidity
interface PoolInterface {
    function swapExactAmountIn(address, uint, address, uint, uint) external returns (uint, uint);
    function swapExactAmountOut(address, uint, address, uint, uint) external returns (uint, uint);
}

interface TokenInterface {
    function balanceOf(address) external returns (uint);
    function allowance(address, address) external returns (uint);
    function approve(address, uint) external returns (bool);
    function transfer(address, uint) external returns (bool);
    function transferFrom(address, address, uint) external returns (bool);
    function deposit() external payable;
    function withdraw(uint) external;
}

What do you think of Balancer? Have you tried it before? Let me know in the comments and ask anything if you need further help.