Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encapsulation of initialization variables and minor refactoring of BaseTest #1191

Merged
merged 3 commits into from
Dec 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pkg/pool-weighted/test/foundry/BigWeightedPool.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ contract BigWeightedPoolTest is WeightedPoolContractsDeployer, BasePoolTest {
for (uint256 i = 0; i < numTokens; ++i) {
// Use all 18-decimal tokens, for simplicity.
bigPoolTokens[i] = createERC20(string.concat("TKN", Strings.toString(i)), 18);
ERC20TestToken(address(bigPoolTokens[i])).mint(lp, defaultBalance);
ERC20TestToken(address(bigPoolTokens[i])).mint(bob, defaultBalance);
ERC20TestToken(address(bigPoolTokens[i])).mint(lp, defaultAccountBalance());
ERC20TestToken(address(bigPoolTokens[i])).mint(bob, defaultAccountBalance());
weights[i] = 1e18 / numTokens;
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/pool-weighted/test/foundry/WeightedPoolLimits.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ contract WeightedPoolLimitsTest is BaseVaultTest, WeightedPoolContractsDeployer
}

function _testAddLiquidityUnbalanced(uint256 swapFeePercentage) public {
uint256[] memory maxAmountsIn = [defaultBalance, defaultBalance].toMemoryArray();
uint256[] memory maxAmountsIn = [defaultAccountBalance(), defaultAccountBalance()].toMemoryArray();
// Enlarge the pool so that adding liquidity unbalanced does not hit the invariant ratio limit.
uint256 currentBPTSupply = IERC20(weightedPool).totalSupply();
vm.prank(alice);
Expand Down
56 changes: 43 additions & 13 deletions pkg/solidity-utils/test/foundry/utils/BaseTest.sol
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import { WETHTestToken } from "../../../contracts/test/WETHTestToken.sol";
abstract contract BaseTest is Test, GasSnapshot {
using CastingHelpers for *;

uint256 internal constant DEFAULT_BALANCE = 1e9 * 1e18;

// Reasonable block.timestamp `MAY_1_2023`
uint32 internal constant START_TIMESTAMP = 1_682_899_200;

Expand Down Expand Up @@ -65,16 +67,43 @@ abstract contract BaseTest is Test, GasSnapshot {
// List of all ERC4626 tokens
IERC4626[] internal erc4626Tokens;

bool private _initialized;

// Default balance for accounts
uint256 internal defaultBalance = 1e9 * 1e18;
uint256 private _defaultAccountBalance = DEFAULT_BALANCE;

// ------------------------------ Initialization ------------------------------
function setUp() public virtual {
// Set timestamp only if testing locally
if (block.chainid == 31337) {
// Set block.timestamp to something better than 0
vm.warp(START_TIMESTAMP);
}

_initTokens();
_initAccounts();

// Must mock rates after giving wrapped tokens to users, but before creating pools and initializing buffers.
mockERC4626TokenRates();
elshan-eth marked this conversation as resolved.
Show resolved Hide resolved
}

function setDefaultAccountBalance(uint256 balance) internal {
if (isInitialized()) {
revert("Cannot change default account balance after initialization");
}
_defaultAccountBalance = balance;
}

function defaultAccountBalance() internal view returns (uint256) {
return _defaultAccountBalance;
elshan-eth marked this conversation as resolved.
Show resolved Hide resolved
}

// @dev Returns whether the test has been initialized.
function isInitialized() internal view returns (bool) {
return _initialized;
}

function _initTokens() private {
// Deploy the base test contracts.
dai = createERC20("DAI", 18);
// "USDC" is deliberately 18 decimals to test one thing at a time.
Expand All @@ -100,7 +129,9 @@ abstract contract BaseTest is Test, GasSnapshot {
erc4626Tokens.push(waDAI);
erc4626Tokens.push(waWETH);
erc4626Tokens.push(waUSDC);
}

function _initAccounts() private {
// Create users for testing.
(admin, adminKey) = createUser("admin");
(lp, lpKey) = createUser("lp");
Expand All @@ -112,9 +143,6 @@ abstract contract BaseTest is Test, GasSnapshot {
broke = payable(brokeNonPay);
vm.label(broke, "broke");

// Must mock rates after giving wrapped tokens to users, but before creating pools and initializing buffers.
mockERC4626TokenRates();

// Fill the users list
users.push(admin);
userKeys.push(adminKey);
Expand All @@ -128,14 +156,16 @@ abstract contract BaseTest is Test, GasSnapshot {
userKeys.push(brokeUserKey);
}

// ------------------------------ Helpers ------------------------------

/**
* @notice Manipulate rates of ERC4626 tokens.
* @dev It's important to not have a 1:1 rate when testing ERC4626 tokens, so we can differentiate between
* wrapped and underlying amounts. For certain tests, we may need to override these rates for simplicity.
*/
function mockERC4626TokenRates() internal virtual {
waDAI.inflateUnderlyingOrWrapped(0, 6 * defaultBalance);
waUSDC.inflateUnderlyingOrWrapped(23 * defaultBalance, 0);
waDAI.inflateUnderlyingOrWrapped(0, 6 * defaultAccountBalance());
waUSDC.inflateUnderlyingOrWrapped(23 * defaultAccountBalance(), 0);
}

function getSortedIndexes(
Expand Down Expand Up @@ -188,27 +218,27 @@ abstract contract BaseTest is Test, GasSnapshot {
function createUser(string memory name) internal returns (address payable, uint256) {
(address user, uint256 key) = makeAddrAndKey(name);
vm.label(user, name);
vm.deal(payable(user), defaultBalance);
vm.deal(payable(user), defaultAccountBalance());

for (uint256 i = 0; i < tokens.length; ++i) {
deal(address(tokens[i]), user, defaultBalance);
deal(address(tokens[i]), user, defaultAccountBalance());
}

for (uint256 i = 0; i < erc4626Tokens.length; ++i) {
// Give underlying tokens to the user, for depositing in the wrapped token.
if (erc4626Tokens[i].asset() == address(weth)) {
vm.deal(user, user.balance + defaultBalance);
vm.deal(user, user.balance + defaultAccountBalance());

vm.prank(user);
weth.deposit{ value: defaultBalance }();
weth.deposit{ value: defaultAccountBalance() }();
} else {
ERC20TestToken(erc4626Tokens[i].asset()).mint(user, defaultBalance);
ERC20TestToken(erc4626Tokens[i].asset()).mint(user, defaultAccountBalance());
}

// Deposit underlying to mint wrapped tokens to the user.
vm.startPrank(user);
IERC20(erc4626Tokens[i].asset()).approve(address(erc4626Tokens[i]), defaultBalance);
erc4626Tokens[i].deposit(defaultBalance, user);
IERC20(erc4626Tokens[i].asset()).approve(address(erc4626Tokens[i]), defaultAccountBalance());
erc4626Tokens[i].deposit(defaultAccountBalance(), user);
vm.stopPrank();
}

Expand Down
3 changes: 2 additions & 1 deletion pkg/vault/test/foundry/DynamicFeePoolTest.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ contract DynamicFeePoolTest is BaseVaultTest {
uint256 internal usdcIdx;

function setUp() public virtual override {
defaultBalance = 1e10 * 1e18;
setDefaultAccountBalance(1e10 * 1e18);

// We will use min trade amount in this test.
vaultMockMinTradeAmount = PRODUCTION_MIN_TRADE_AMOUNT;

Expand Down
23 changes: 12 additions & 11 deletions pkg/vault/test/foundry/LiquidityApproximation.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ contract LiquidityApproximationTest is BaseVaultTest {

function setUp() public virtual override {
poolInitAmount = 1e9 * 1e18;
defaultBalance = 1e10 * 1e18;
setDefaultAccountBalance(1e10 * 1e18);

BaseVaultTest.setUp();

approveForPool(IERC20(liquidityPool));
Expand Down Expand Up @@ -226,16 +227,16 @@ contract LiquidityApproximationTest is BaseVaultTest {

assertEq(dai.balanceOf(alice), dai.balanceOf(bob), "Bob and Alice DAI balances are not equal");

if (usdc.balanceOf(alice) <= defaultBalance) {
if (usdc.balanceOf(alice) <= defaultAccountBalance()) {
// No amount out (trade too small, rounding ate the difference).
// Dai balances are the same, so we just check that the USDC balances are better for Bob (direct swap).
// There's no point in continuing the test in this case.
assertGe(usdc.balanceOf(bob), usdc.balanceOf(alice), "Alice lost less than bob");
return;
}

uint256 aliceAmountOut = usdc.balanceOf(alice) - defaultBalance;
uint256 bobAmountOut = usdc.balanceOf(bob) - defaultBalance;
uint256 aliceAmountOut = usdc.balanceOf(alice) - defaultAccountBalance();
uint256 bobAmountOut = usdc.balanceOf(bob) - defaultAccountBalance();
uint256 bobToAliceRatio = bobAmountOut.divDown(aliceAmountOut);

// Early returns:
Expand Down Expand Up @@ -267,16 +268,16 @@ contract LiquidityApproximationTest is BaseVaultTest {

assertEq(dai.balanceOf(alice), dai.balanceOf(bob), "Bob and Alice DAI balances are not equal");

if (usdc.balanceOf(alice) <= defaultBalance) {
if (usdc.balanceOf(alice) <= defaultAccountBalance()) {
// No amount out (trade too small, rounding ate the difference).
// Dai balances are the same, so we just check that the USDC balances are better for Bob (direct swap).
// There's no point in continuing the test in this case.
assertGe(usdc.balanceOf(bob), usdc.balanceOf(alice), "Alice lost less than bob");
return;
}

uint256 aliceAmountOut = usdc.balanceOf(alice) - defaultBalance;
uint256 bobAmountOut = usdc.balanceOf(bob) - defaultBalance;
uint256 aliceAmountOut = usdc.balanceOf(alice) - defaultAccountBalance();
uint256 bobAmountOut = usdc.balanceOf(bob) - defaultAccountBalance();
uint256 bobToAliceRatio = bobAmountOut.divDown(aliceAmountOut);

uint256 liquidityTaxPercentage = liquidityPercentageDelta.mulDown(swapFeePercentage);
Expand Down Expand Up @@ -416,7 +417,7 @@ contract LiquidityApproximationTest is BaseVaultTest {
address(swapPool),
dai,
usdc,
defaultBalance - dai.balanceOf(alice),
defaultAccountBalance() - dai.balanceOf(alice),
0,
MAX_UINT256,
false,
Expand Down Expand Up @@ -465,7 +466,7 @@ contract LiquidityApproximationTest is BaseVaultTest {
address(swapPool),
dai,
usdc,
defaultBalance - dai.balanceOf(alice),
defaultAccountBalance() - dai.balanceOf(alice),
0,
MAX_UINT256,
false,
Expand Down Expand Up @@ -517,7 +518,7 @@ contract LiquidityApproximationTest is BaseVaultTest {
address(swapPool),
dai,
usdc,
defaultBalance - dai.balanceOf(alice),
defaultAccountBalance() - dai.balanceOf(alice),
0,
MAX_UINT256,
false,
Expand Down Expand Up @@ -570,7 +571,7 @@ contract LiquidityApproximationTest is BaseVaultTest {
address(swapPool),
dai,
usdc,
defaultBalance - dai.balanceOf(alice),
defaultAccountBalance() - dai.balanceOf(alice),
0,
MAX_UINT256,
false,
Expand Down
Loading
Loading