Skip to content

Estimate gas cost of liquidations #7

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

Merged
merged 19 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
14 changes: 10 additions & 4 deletions src/Market.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ uint constant alpha = 0.5e18;

uint constant N = 10;

function bucketToLLTV(uint bucket) pure returns (uint) {
return MathLib.wDiv(bucket + 1, N + 1);
}

function irm(uint utilization) pure returns (uint) {
// Divide by the number of seconds in a year.
// This is a very simple model (to refine later) where x% utilization corresponds to x% APR.
Expand All @@ -28,6 +24,10 @@ contract Market {
using MathLib for uint;
using SafeTransferLib for IERC20;

function bucketToLLTV(uint bucket) public pure returns (uint) {
return MathLib.wDiv(bucket + 1, N + 1);
}

// Constants.

uint public constant getN = N;
Expand Down Expand Up @@ -161,6 +161,12 @@ contract Market {
IERC20(borrowableAsset).handleTransfer(msg.sender, -sumBorrow);
}

function singleLiquidate(uint bucket, address borrower, uint maxCollat) external returns (int collat, int borrow) {
(collat, borrow) = liquidate(bucket, borrower, maxCollat);
IERC20(collateralAsset).handleTransfer(msg.sender, collat);
IERC20(borrowableAsset).handleTransfer(msg.sender, -borrow);
}

/// @return collat The negative amount of collateral added.
/// @return borrow The negative amount of borrow added.
function liquidate(uint bucket, address borrower, uint maxCollat) internal returns (int collat, int borrow) {
Expand Down
30 changes: 30 additions & 0 deletions src/mocks/LiquidatorMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {ERC20Mock} from "./ERC20Mock.sol";
import {Market} from "src/Market.sol";

contract LiquidatorMock {
function approveBorrowable(Market market) public {
ERC20Mock(market.borrowableAsset()).approve(address(market), type(uint).max);
}

function nativeBatchLiquidate(Market market, Market.Liquidation[] memory liquidationData)
external
returns (int sumCollat, int sumBorrow)
{
return market.batchLiquidate(liquidationData);
}

function manualBatchLiquidate(Market market, Market.Liquidation[] memory liquidationData)
external
returns (int sumCollat, int sumBorrow)
{
for (uint i; i < liquidationData.length; i++) {
Market.Liquidation memory liq = liquidationData[i];
(int collat, int borrow) = market.singleLiquidate(liq.bucket, liq.borrower, liq.maxCollat);
sumCollat += collat;
sumBorrow += borrow;
}
}
}
9 changes: 6 additions & 3 deletions test/forge/Market.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,10 @@ contract MarketTest is Test {

uint collateralValue = amountCollateral.wMul(priceCollateral);
uint borrowValue = amountBorrowed.wMul(priceBorrowable);
if (borrowValue == 0 || (collateralValue > 0 && borrowValue <= collateralValue.wMul(bucketToLLTV(bucket)))) {
if (
borrowValue == 0
|| (collateralValue > 0 && borrowValue <= collateralValue.wMul(market.bucketToLLTV(bucket)))
) {
vm.prank(borrower);
market.modifyBorrow(int(amountBorrowed), bucket);
} else {
Expand Down Expand Up @@ -253,7 +256,7 @@ contract MarketTest is Test {
vm.assume(bucket < N);

uint amountCollateral = amountLent;
uint lLTV = bucketToLLTV(bucket);
uint lLTV = market.bucketToLLTV(bucket);
uint borrowingPower = amountCollateral.wMul(lLTV);
uint amountBorrowed = borrowingPower.wMul(0.8e18);
uint maxCollat = amountCollateral.wMul(lLTV);
Expand Down Expand Up @@ -308,7 +311,7 @@ contract MarketTest is Test {
vm.assume(bucket < N);

uint amountCollateral = amountLent;
uint lLTV = bucketToLLTV(bucket);
uint lLTV = market.bucketToLLTV(bucket);
uint borrowingPower = amountCollateral.wMul(lLTV);
uint amountBorrowed = borrowingPower.wMul(0.8e18);
uint maxCollat = type(uint).max;
Expand Down
93 changes: 65 additions & 28 deletions test/hardhat/Market.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { BigNumber, Wallet, constants } from "ethers";
import { BigNumber, constants } from "ethers";
import hre from "hardhat";

import { hexZeroPad } from "@ethersproject/bytes";
import { setBalance } from "@nomicfoundation/hardhat-network-helpers";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";

import { Market, OracleMock, ERC20Mock } from "types";
import { Market, OracleMock, ERC20Mock, LiquidatorMock } from "types";

const iterations = 500;
function assert(condition: boolean, message: string) {
if (!condition) {
throw message || "Assertion failed";
}
}

let seed = 42;

Expand All @@ -20,6 +23,12 @@ function random() {
return (next() - 1) / 2147483646;
}

let nbLiquidations = 5;
let nativeBatching = false;
let closePositions = false;

assert(2 * nbLiquidations + 1 < 20, "more liquidations than signers");

describe("Market", () => {
let signers: SignerWithAddress[];

Expand All @@ -28,63 +37,91 @@ describe("Market", () => {
let borrowableOracle: OracleMock;
let collateralOracle: OracleMock;
let market: Market;
let liquidatorContract: LiquidatorMock;
let admin: SignerWithAddress;
let liquidator: SignerWithAddress;

const initBalance = constants.MaxUint256.div(2);

beforeEach(async () => {
signers = await hre.ethers.getSigners();
admin = signers[2 * nbLiquidations];
liquidator = signers[2 * nbLiquidations + 1];

const ERC20MockFactory = await hre.ethers.getContractFactory("ERC20Mock", signers[0]);
const ERC20MockFactory = await hre.ethers.getContractFactory("ERC20Mock", admin);

borrowable = await ERC20MockFactory.deploy("DAI", "DAI", 18);
collateral = await ERC20MockFactory.deploy("Wrapped BTC", "WBTC", 18);
collateral = await ERC20MockFactory.deploy("USDC", "USDC", 18);

const OracleMockFactory = await hre.ethers.getContractFactory("OracleMock", signers[0]);
const OracleMockFactory = await hre.ethers.getContractFactory("OracleMock", admin);

borrowableOracle = await OracleMockFactory.deploy();
collateralOracle = await OracleMockFactory.deploy();

const MarketFactory = await hre.ethers.getContractFactory("Market", signers[0]);
await borrowableOracle.connect(admin).setPrice(BigNumber.WAD);
await collateralOracle.connect(admin).setPrice(BigNumber.WAD);

const MarketFactory = await hre.ethers.getContractFactory("Market", admin);

market = await MarketFactory.deploy(
borrowable.address,
collateral.address,
borrowableOracle.address,
collateralOracle.address
);

const LiquidatorMockFactory = await hre.ethers.getContractFactory("LiquidatorMock", admin);

liquidatorContract = await LiquidatorMockFactory.deploy();
});

it("should simulate gas cost", async () => {
const n = (await market.getN()).toNumber();
assert(2 * nbLiquidations <= n, "more liquidations than buckets");
let liquidationData = []

for (let i = 1; i < iterations; ++i) {
console.log(i, "/", iterations);

const user = new Wallet(hexZeroPad(BigNumber.from(i).toHexString(), 32), hre.ethers.provider);
// Create accounts close to liquidation
for (let i = 0; i < 2 * nbLiquidations; ++i) {
const user = signers[i];
const bucket = Math.floor(i / 2);
await setBalance(user.address, initBalance);
await borrowable.setBalance(user.address, initBalance);
await borrowable.connect(user).approve(market.address, constants.MaxUint256);
await collateral.setBalance(user.address, initBalance);
await collateral.connect(user).approve(market.address, constants.MaxUint256);

let amount = BigNumber.WAD.mul(1 + Math.floor(random() * 100));
const bucket = Math.floor(random() * n);

let supplyOnly: boolean = random() < 2 / 3;
if (supplyOnly) {
await market.connect(user).modifyDeposit(amount, bucket);
await market.connect(user).modifyDeposit(amount.div(2).mul(-1), bucket);
} else {
const totalSupply = await market.totalSupply(bucket);
const totalBorrow = await market.totalBorrow(bucket);
let liq = BigNumber.from(totalSupply).sub(BigNumber.from(totalBorrow));
amount = BigNumber.min(amount, BigNumber.from(liq).div(2));

await market.connect(user).modifyCollateral(amount, bucket);
await market.connect(user).modifyBorrow(amount.div(2), bucket);
await market.connect(user).modifyBorrow(amount.div(4).mul(-1), bucket);
await market.connect(user).modifyCollateral(amount.div(8).mul(-1), bucket);

await market.connect(user).modifyDeposit(amount, bucket);
await market.connect(user).modifyCollateral(amount, bucket);

let lltv = await market.bucketToLLTV(bucket);
let borrowedAmount = amount.mul(lltv).div(BigNumber.WAD);
await market.connect(user).modifyBorrow(borrowedAmount, bucket);

let maxCollat = closePositions ? constants.MaxUint256 : amount.div(2);

if (i % 2 == 0) {
liquidationData.push({ bucket: bucket, borrower: user.address, maxCollat: maxCollat });
}
}

await borrowableOracle.connect(admin).setPrice(BigNumber.WAD.mul(1000));

await setBalance(liquidator.address, initBalance);
await borrowable.setBalance(liquidatorContract.address, initBalance);
await liquidatorContract.connect(liquidator).approveBorrowable(market.address);
if (nativeBatching) {
await liquidatorContract.connect(liquidator).nativeBatchLiquidate(market.address, liquidationData);
} else {
await liquidatorContract.connect(liquidator).manualBatchLiquidate(market.address, liquidationData);
}

for (let i = 0; i < 2 * nbLiquidations; i++) {
const user = signers[i];
const bucket = Math.floor(i / 2);
let collat = await market.collateral(user.address, bucket);
assert(closePositions || collat != BigNumber.from(0), "did not take the whole collateral when closing the position");
}
});
});
Loading