Skip to content

Starter kit for creating custom pools and hooks contracts on Balancer v3

License

Notifications You must be signed in to change notification settings

balancer/scaffold-balancer-v3

Repository files navigation

πŸ—οΈŽ Scaffold Balancer v3

A starter kit for building on top of Balancer v3. Accelerate the process of creating custom pools and hooks contracts. Concentrate on mastering the core concepts within a swift and responsive environment augmented by a local fork and a frontend pool operations playground.

image

✨ Features

  • Deploy custom pool and hooks to a local anvil fork
  • Explore pool configuration and liquidity details using the frontend
  • Instantly execute swaps, joins, and exits using a burner wallet

πŸ“½οΈ Video Tutorials

πŸͺ§ Table Of Contents

πŸ§‘β€πŸ’» Environment Setup

Requirements

Quickstart

  1. Ensure you have the latest version of foundry installed
foundryup
  1. Clone this repo & install dependencies
git clone https://github.com/balancer/scaffold-balancer-v3.git
cd scaffold-balancer-v3
yarn install
  1. In a packages/foundry/.env file, set RPC URLs for the networks you wish to fork
SEPOLIA_RPC_URL=
MAINNET_RPC_URL=
GNOSIS_RPC_URL=
  1. Start a local anvil fork of Ethereum mainnet
yarn fork

By default, this project is setup to fork Ethereum mainnet. However, you can fork another network by following these steps:

  1. Change targetFork in scaffold.config.ts to chains.gnosis
  2. Make sure the right addresses are un-commented in PoolHelpers.sol
  3. Run yarn fork --network gnosis
  1. Deploy the mock tokens, pool factories, pool hooks, and custom pools contracts
yarn deploy

By default, the anvil account #0 will be the deployer and recieve the mock tokens and BPT from pool initialization

  1. Start the nextjs frontend
yarn start
  1. Explore the frontend
  • Navigate to http://localhost:3000 to see the home page
  • Visit the Pools Page to search by address or select using the pool buttons
  • Visit the Hooks Page to see a growing library of pool hook examples
  • Vist the Debug Page to see external read and write functions for each contract
  1. Run the Foundry tests
yarn test

Scaffold ETH 2 Tips

SE-2 offers a variety of configuration options for connecting an account, choosing networks, and deploying contracts

πŸ”₯ Burner Wallet

If you do not have an active wallet extension connected to your web browser, then scaffold eth will automatically connect to a "burner wallet" that is randomly generated on the frontend and saved to the browser's local storage. When using the burner wallet, transactions will be instantly signed, which is convenient for quick iterative development.

To force the use of burner wallet, disable your browsers wallet extensions and refresh the page. Note that the burner wallet comes with 0 ETH to pay for gas so you will need to click the faucet button in top right corner. Also the mock tokens for the pool are minted to your deployer account set in .env so you will want to navigate to the "Debug Contracts" page to mint your burner wallet some mock tokens to use with the pool.

Burner Wallet

Debug Tab Mint

πŸ‘› Browser Extension Wallet
  • To use your preferred browser extension wallet, ensure that the account you are using matches the PK you previously provided in the foundry/.env file
  • You may need to add a local development network with rpc url http://127.0.0.1:8545/ and chain id 31337. Also, you may need to reset the nonce data for your wallet exension if it gets out of sync.
πŸ› Debug Contracts Page

The Debug Contracts Page can be useful for viewing and interacting with all of the externally avaiable read and write functions of a contract. The page will automatically hot reload with contracts that are deployed via the 01_DeployConstantSumFactory.s.sol script. We use this handy setup to mint mockERC20 tokens to any connected wallet

🌐 Changing The Frontend Network Connection
  • The network the frontend points at is set via targetNetworks in the scaffold.config.ts file using chains from viem.
  • By default, the frontend runs on a local node at http://127.0.0.1:8545
const scaffoldConfig = {
  targetNetworks: [chains.foundry],
🍴 Changing The Forked Network
  • By default, the yarn fork command points at sepolia, but any of the network aliases from the [rpc_endpoints] of foundry.toml can be used to modify the "fork" alias in the packages/foundry/package.json file
	"fork": "anvil --fork-url ${0:-sepolia} --chain-id 31337 --config-out localhost.json",
  • To point the frontend at a different forked network, change the targetFork in scaffold.config.ts
const scaffoldConfig = {
  // The networks the frontend can connect to
  targetNetworks: [chains.foundry],

  // If using chains.foundry as your targetNetwork, you must specify a network to fork
  targetFork: chains.sepolia,

πŸ‘©β€πŸ« Learn Core Concepts

v3-components

πŸ•΅οΈ Explore the Examples

Each of the following examples have turn key deploy scripts that can be found in the foundry/script/ directory

Constant Sum Pool with Dynamic Swap Fee Hook

The swap fee percentage is altered by the hook contract before the pool calculates the amount for the swap

dynamic-fee-hook

Constant Product Pool with Lottery Hook

An after swap hook that uses a random number to determine if user should pay into the lottery or receive the prize

after-swap-hook

Weighted Pool with Exit Fee Hook

An after remove liquidity hook adjusts the amounts before the vault transfers tokens to the user

after-remove-liquidity-hook

🌊 Create a Custom Pool

Custom AMMs built on Balancer inherit the security of the Balancer vault, and benefit from a streamlined development process.

Learn the Basics

Recall the Key Requirements

  • Must inherit from IBasePool and BalancerPoolToken
  • Must implement onSwap, computeInvariant, and computeBalance
  • Must implement getMaximumSwapFeePercentage and getMinimumSwapFeePercentage

🏭 Create a Pool Factory

While not mandatory, we do recommend using a factory contract for the deployment and registration of custom pools.

Learn the Basics

Recall the Key Requirements

  • A pool factory contract must inherit from BasePoolFactory
  • Use the internal _create function to deploy a new pool
  • Use the internal _registerPoolWithVault fuction to register a pool immediately after creation

πŸͺ Create a Pool Hook

Hooks introduce a new framework for extending the functionality of existing pool types at key points throughout pool operation lifecycles.

Learn the Basics

Recall the Key Requirements

  • A hooks contract must inherit from BasePoolHooks.sol
  • A hooks contract should also inherit from VaultGuard.sol
  • Must implement onRegister to determine if a pool is allowed to use the hook contract
  • Must implement getHookFlags to define which hooks are supported
  • The onlyVault modifier should be applied to all hooks functions (i.e. onRegister, onBeforeSwap, onAfterSwap ect.)

🚒 Deploy the Contracts

The deploy scripts are located in the foundry/script/ directory. To better understand the lifecycle of deploying a pool that uses a hooks contract, see the diagram below

pool-deploy-scripts

Understand Scaffold

For all the scaffold integrations to work properly, each deploy script must be imported into Deploy.s.sol and inherited by the DeployScript contract in Deploy.s.sol

Broadcast Transactions

Run the following command to deploy the contracts to a local anvil fork

yarn deploy

Add a --network flag to deploy the contracts to a live network

yarn deploy --network sepolia

πŸ§ͺ Test the Contracts

The balancer-v3-monorepo provides testing utility contracts like BasePoolTest and BaseVaultTest. Therefore, the best way to begin writing tests for custom factories, pools, and hooks contracts is to leverage the examples established by the source code.

Testing Factories

The ConstantSumFactoryTest roughly mirrors the WeightedPool8020FactoryTest

yarn test --match-contract ConstantSumFactoryTest

Testing Pools

The ConstantSumPoolTest roughly mirrors the WeightedPoolTest

yarn test --match-contract ConstantSumPoolTest

Testing Hooks

The VeBALFeeDiscountHookExampleTest mirrors the VeBALFeeDiscountHookExampleTest

yarn test --match-contract VeBALFeeDiscountHookExampleTest

About

Starter kit for creating custom pools and hooks contracts on Balancer v3

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published