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

feat: gas optimizations for position mover #391

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,10 @@ interface ILendPool {
uint256 amount
) external returns (uint256, bool);


function batchRepay(
address[] calldata nftAssets,
uint256[] calldata nftTokenIds,
uint256[] calldata amounts
) external returns (uint256[] memory, bool[] memory);
}
13 changes: 12 additions & 1 deletion contracts/mocks/benddao/MockLendPool.sol
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ contract MockLendPool {
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external returns (uint256, bool) {
) public returns (uint256, bool) {
BDaoDataTypes.LoanData storage loan = loans[loanMapping[nftAsset][nftTokenId]];

if (amount == loan.scaledAmount) {
Expand All @@ -51,4 +51,15 @@ contract MockLendPool {

IERC20(weth).transferFrom(msg.sender, address(this), amount);
}

function batchRepay(
address[] calldata nftAssets,
uint256[] calldata nftTokenIds,
uint256[] calldata amounts
) external returns (uint256[] memory, bool[] memory) {
for (uint256 index = 0; index < nftAssets.length; index++) {
repay(nftAssets[index], nftTokenIds[index], amounts[index]);
}
}

}
199 changes: 140 additions & 59 deletions contracts/protocol/libraries/logic/PositionMoverLogic.sol
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,10 @@ library PositionMoverLogic {
using ReserveLogic for DataTypes.ReserveData;

struct PositionMoverVars {
address weth;
address xTokenAddress;
address nftAsset;
uint256 tokenId;
uint256 borrowAmount;
address[] nftAssets;
uint256[] tokenIds;
uint256[] borrowAmounts;
uint256 totalBorrowAmount;
}

event PositionMoved(address asset, uint256 tokenId, address user);
Expand All @@ -41,103 +40,185 @@ library PositionMoverLogic {
IPoolAddressesProvider poolAddressProvider,
ILendPoolLoan lendPoolLoan,
ILendPool lendPool,
uint256[] calldata loandIds
uint256[] calldata loanIds
) external {
PositionMoverVars memory tmpVar;

tmpVar.weth = poolAddressProvider.getWETH();
DataTypes.ReserveData storage reserve = ps._reserves[tmpVar.weth];
tmpVar.xTokenAddress = reserve.xTokenAddress;

for (uint256 index = 0; index < loandIds.length; index++) {
(
tmpVar.nftAsset,
tmpVar.tokenId,
tmpVar.borrowAmount
) = _repayBendDAOPositionLoan(
lendPoolLoan,
lendPool,
tmpVar.weth,
tmpVar.xTokenAddress,
loandIds[index]
);

supplyNFTandBorrowWETH(ps, poolAddressProvider, tmpVar);
address weth = poolAddressProvider.getWETH();
DataTypes.ReserveData storage reserve = ps._reserves[weth];
address xTokenAddress = reserve.xTokenAddress;

uint256 borrowAmount = _repayBendDAOPositionLoanAndSupply(
ps,
lendPoolLoan,
lendPool,
weth,
xTokenAddress,
loanIds
);

emit PositionMoved(tmpVar.nftAsset, tmpVar.tokenId, msg.sender);
}
borrowWETH(ps, poolAddressProvider, weth, borrowAmount);
}

function _repayBendDAOPositionLoan(
function _repayBendDAOPositionLoanAndSupply(
DataTypes.PoolStorage storage ps,
ILendPoolLoan lendPoolLoan,
ILendPool lendPool,
address weth,
address xTokenAddress,
uint256 loanId
)
internal
returns (
address nftAsset,
uint256 tokenId,
uint256 borrowAmount
)
{
BDaoDataTypes.LoanData memory loanData = lendPoolLoan.getLoan(loanId);

require(
loanData.state == BDaoDataTypes.LoanState.Active,
"Loan not active"
);
require(loanData.borrower == msg.sender, Errors.NOT_THE_OWNER);
uint256[] calldata loanIds
) internal returns (uint256 borrowAmount) {
BDaoDataTypes.LoanData memory loanData;
PositionMoverVars memory tmpVar;

(, borrowAmount) = lendPoolLoan.getLoanReserveBorrowAmount(loanId);
tmpVar.borrowAmounts = new uint256[](loanIds.length);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we cache "loanIds.length" as a uint value to save gas?

tmpVar.nftAssets = new address[](loanIds.length);
tmpVar.tokenIds = new uint256[](loanIds.length);

for (uint256 index = 0; index < loanIds.length; index++) {
loanData = lendPoolLoan.getLoan(loanIds[index]);

require(
loanData.state == BDaoDataTypes.LoanState.Active,
"Loan not active"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion : use Errors.xxx

);
require(loanData.borrower == msg.sender, Errors.NOT_THE_OWNER);

(, tmpVar.borrowAmounts[index]) = lendPoolLoan
.getLoanReserveBorrowAmount(loanIds[index]);

tmpVar.totalBorrowAmount += tmpVar.borrowAmounts[index];

tmpVar.nftAssets[index] = loanData.nftAsset;
tmpVar.tokenIds[index] = loanData.nftTokenId;
emit PositionMoved(
loanData.nftAsset,
loanData.nftTokenId,
msg.sender
);
}

DataTypes.TimeLockParams memory timeLockParams;
IPToken(xTokenAddress).transferUnderlyingTo(
address(this),
borrowAmount,
tmpVar.totalBorrowAmount,
timeLockParams
);
IERC20(weth).approve(address(lendPool), borrowAmount);
IERC20(weth).approve(address(lendPool), tmpVar.totalBorrowAmount);

lendPool.repay(loanData.nftAsset, loanData.nftTokenId, borrowAmount);
lendPool.batchRepay(
tmpVar.nftAssets,
tmpVar.tokenIds,
tmpVar.borrowAmounts
);

supplyAssets(ps, tmpVar);

(nftAsset, tokenId) = (loanData.nftAsset, loanData.nftTokenId);
borrowAmount = tmpVar.totalBorrowAmount;
}

function supplyNFTandBorrowWETH(
function supplyAssets(
DataTypes.PoolStorage storage ps,
IPoolAddressesProvider poolAddressProvider,
PositionMoverVars memory tmpVar
) internal {
uint256 tokenIdsLength = tmpVar.tokenIds.length;
DataTypes.ERC721SupplyParams[]
memory tokenData = new DataTypes.ERC721SupplyParams[](1);
tokenData[0] = DataTypes.ERC721SupplyParams({
tokenId: tmpVar.tokenId,
memory tokensToSupply = new DataTypes.ERC721SupplyParams[](
tokenIdsLength
);

address currentSupplyAsset = tmpVar.nftAssets[0];
uint256 supplySize = 1;
tokensToSupply[0] = DataTypes.ERC721SupplyParams({
tokenId: tmpVar.tokenIds[0],
useAsCollateral: true
});
uint256 nextIndex;
/**
The following logic divides the array of tokenIds into sub-arrays based on the asset in a greedy logic.
Then uses the sub-arrays as an inout to the supply logic to reduce the number of supplies.
Example1:
input: [BAYCToken1, BAYCToken2, MAYCToken1, MAYCToken1, BAKCToken1]
output: [BAYCToken1, BAYCToken2] [MAYCToken1, MAYCToken1] [BAKCToken1] (3 supply calls)

Example2:
input: [BAYCToken1, MAYCToken1, BAYCToken2, MAYCToken1, BAKCToken1]
output: [BAYCToken1] [MAYCToken1] [BAYCToken2] [MAYCToken1] [BAKCToken1] (5 supply calls)
Note: To optimi
*/
for (uint256 index = 0; index < tokenIdsLength; index++) {
nextIndex = index + 1;
if (
nextIndex < tokenIdsLength &&
tmpVar.nftAssets[index] == tmpVar.nftAssets[nextIndex]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion more readable : currentSupplyAsset == tmpVar.nftAssets[nextIndex]

) {
tokensToSupply[supplySize] = DataTypes.ERC721SupplyParams({
tokenId: tmpVar.tokenIds[nextIndex],
useAsCollateral: true
});
supplySize++;
} else {
reduceArrayAndSupply(
ps,
currentSupplyAsset,
tokensToSupply,
supplySize
);

if (nextIndex < tokenIdsLength) {
currentSupplyAsset = tmpVar.nftAssets[nextIndex];
tokensToSupply = new DataTypes.ERC721SupplyParams[](
tokenIdsLength
);
tokensToSupply[0] = DataTypes.ERC721SupplyParams({
tokenId: tmpVar.tokenIds[nextIndex],
useAsCollateral: true
});
supplySize = 1;
}
}
}
}

function reduceArrayAndSupply(
DataTypes.PoolStorage storage ps,
address asset,
DataTypes.ERC721SupplyParams[] memory tokensToSupply,
uint256 subArraySize
) internal {
if (tokensToSupply.length - subArraySize != 0 && subArraySize != 0) {
assembly {
mstore(tokensToSupply, subArraySize)
}
}

// supply the current asset and tokens
SupplyLogic.executeSupplyERC721(
ps._reserves,
ps._usersConfig[msg.sender],
DataTypes.ExecuteSupplyERC721Params({
asset: tmpVar.nftAsset,
tokenData: tokenData,
asset: asset,
tokenData: tokensToSupply,
onBehalfOf: msg.sender,
payer: msg.sender,
referralCode: 0x0
})
);
}

function borrowWETH(
DataTypes.PoolStorage storage ps,
IPoolAddressesProvider poolAddressProvider,
address weth,
uint256 borrowAmount
) internal {
BorrowLogic.executeBorrow(
ps._reserves,
ps._reservesList,
ps._usersConfig[msg.sender],
DataTypes.ExecuteBorrowParams({
asset: tmpVar.weth,
asset: weth,
user: msg.sender,
onBehalfOf: msg.sender,
amount: tmpVar.borrowAmount,
amount: borrowAmount,
referralCode: 0x0,
releaseUnderlying: false,
reservesCount: ps._reservesCount,
Expand Down
20 changes: 17 additions & 3 deletions test/_pool_position_mover.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,34 @@ describe("Pool: rescue tokens", () => {
const {
users: [user1, user2],
bayc,
mayc,
pool,
} = testEnv;

bendDaoLendPool = await getMockBendDaoLendPool();

await mintAndValidate(bayc, "5", user1);
await mintAndValidate(mayc, "5", user1);
await bayc
.connect(user1.signer)
.transferFrom(user1.address, user2.address, 2);

await waitForTx(
await bayc.connect(user1.signer).setApprovalForAll(pool.address, true)
);

await waitForTx(
await mayc.connect(user1.signer).setApprovalForAll(pool.address, true)
);
await waitForTx(
await bayc
.connect(user1.signer)
.setApprovalForAll(bendDaoLendPool.address, true)
);
await waitForTx(
await mayc
.connect(user1.signer)
.setApprovalForAll(bendDaoLendPool.address, true)
);
await waitForTx(
await bayc.connect(user2.signer).setApprovalForAll(pool.address, true)
);
Expand Down Expand Up @@ -183,6 +193,7 @@ describe("Pool: rescue tokens", () => {
users: [user1],
pool,
bayc,
mayc,
variableDebtWeth,
nBAYC,
} = testEnv;
Expand All @@ -195,13 +206,16 @@ describe("Pool: rescue tokens", () => {
2
);

await bendDaoLendPool.setLoan(5, mayc.address, 1, user1.address, "20", 2);

await expect(
await pool.connect(user1.signer).movePositionFromBendDAO([3, 4])
await pool.connect(user1.signer).movePositionFromBendDAO([3, 4, 5])
);

await expect(await variableDebtWeth.balanceOf(user1.address)).to.be.eq(
"600000"
"600020"
);

await expect(await nBAYC.balanceOf(user1.address)).to.be.eq(3);
});
});