Skip to content

Commit

Permalink
Merge pull request #262 from morpho-org/feature/integ-1553-apply-chan…
Browse files Browse the repository at this point in the history
…ges-in-sdk-bundler-to-use-new-shared-liquidity

feat: new reallocation algorithm
  • Loading branch information
Rubilmax authored Feb 13, 2025
2 parents 6a25732 + 348d286 commit 6a1d85e
Show file tree
Hide file tree
Showing 2 changed files with 815 additions and 5 deletions.
27 changes: 22 additions & 5 deletions packages/bundler-sdk-viem/src/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,17 +326,34 @@ export const populateSubBundle = (
) {
// Liquidity is insufficient: trigger a public reallocation and try to have a resulting utilization as low as possible, above the target.
// Solve: newTotalBorrowAssets / (newTotalSupplyAssets + reallocatedAssets) = supplyTargetUtilization
// Worst case is: there is not enough withdrawals available to fill reallocatedAssets, so utilization is above supplyTargetUtilization.
// We first try to find public reallocations that respect every markets targets.
// If this is not enough, the first market to be pushed above target is the supply market. Then we fully withdraw from every market.
let requiredAssets =
supplyTargetUtilization === 0n
? MathLib.MAX_UINT_160
: MathLib.wDivDown(newTotalBorrowAssets, supplyTargetUtilization) -
newTotalSupplyAssets;

const { withdrawals } = data.getMarketPublicReallocations(
market.id,
publicAllocatorOptions,
);
let { withdrawals, data: simulationStatePostFriendlyReallocation } =
data.getMarketPublicReallocations(market.id, publicAllocatorOptions);

const marketPostFriendlyReallocation =
simulationStatePostFriendlyReallocation.getMarket(market.id);

if (
marketPostFriendlyReallocation.totalBorrowAssets + borrowedAssets >
marketPostFriendlyReallocation.totalSupplyAssets - withdrawnAssets
) {
// If the "friendly" reallocations are not enough, we fully withdraw from every market.

requiredAssets = newTotalBorrowAssets - newTotalSupplyAssets;

({ withdrawals } = data.getMarketPublicReallocations(market.id, {
...publicAllocatorOptions,
defaultMaxWithdrawalUtilization: MathLib.WAD,
maxWithdrawalUtilization: {},
}));
}

for (const { vault, ...withdrawal } of withdrawals) {
const vaultReallocations = (reallocations[vault] ??= []);
Expand Down
Loading

0 comments on commit 6a1d85e

Please sign in to comment.