@morpho-org/bundler-sdk-viem 3.0.0-next.9 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/errors.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { SimulationResult } from "@morpho-org/simulation-sdk";
2
+ import type { Address } from "viem";
2
3
  import type { ActionType, InputBundlerOperation } from "./types/index.js";
3
4
  export declare namespace BundlerErrors {
4
5
  class Bundle extends Error {
@@ -14,4 +15,7 @@ export declare namespace BundlerErrors {
14
15
  class UnexpectedAction extends Error {
15
16
  constructor(type: ActionType, chainId: number);
16
17
  }
18
+ class UnexpectedSignature extends Error {
19
+ constructor(spender: Address);
20
+ }
17
21
  }
package/lib/errors.js CHANGED
@@ -1,4 +1,7 @@
1
- export var BundlerErrors;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BundlerErrors = void 0;
4
+ var BundlerErrors;
2
5
  (function (BundlerErrors) {
3
6
  class Bundle extends Error {
4
7
  error;
@@ -27,4 +30,10 @@ export var BundlerErrors;
27
30
  }
28
31
  }
29
32
  BundlerErrors.UnexpectedAction = UnexpectedAction;
30
- })(BundlerErrors || (BundlerErrors = {}));
33
+ class UnexpectedSignature extends Error {
34
+ constructor(spender) {
35
+ super(`unexpected signature consumer "${spender}"`);
36
+ }
37
+ }
38
+ BundlerErrors.UnexpectedSignature = UnexpectedSignature;
39
+ })(BundlerErrors || (exports.BundlerErrors = BundlerErrors = {}));
package/lib/index.js CHANGED
@@ -1,8 +1,24 @@
1
- export * from "./actions.js";
2
- export * from "./operations.js";
3
- export * from "./errors.js";
4
- export * from "./types/index.js";
5
- export * from "./BundlerAction.js";
6
- export * from "./bundle.js";
7
- export * from "./ActionBundle.js";
8
- export * from "./abis.js";
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./actions.js"), exports);
18
+ __exportStar(require("./operations.js"), exports);
19
+ __exportStar(require("./errors.js"), exports);
20
+ __exportStar(require("./types/index.js"), exports);
21
+ __exportStar(require("./BundlerAction.js"), exports);
22
+ __exportStar(require("./bundle.js"), exports);
23
+ __exportStar(require("./ActionBundle.js"), exports);
24
+ __exportStar(require("./abis.js"), exports);
package/lib/operations.js CHANGED
@@ -1,16 +1,19 @@
1
- import { DEFAULT_SLIPPAGE_TOLERANCE, MarketUtils, MathLib, NATIVE_ADDRESS, erc20WrapperTokens, getChainAddresses, getUnwrappedToken, permissionedBackedTokens, permissionedWrapperTokens, } from "@morpho-org/blue-sdk";
2
- import { bigIntComparator, entries, getLast, getValue, keys, } from "@morpho-org/morpho-ts";
3
- import { handleOperation, handleOperations, produceImmutable, simulateOperation, simulateOperations, } from "@morpho-org/simulation-sdk";
4
- import { isAddressEqual, maxUint256 } from "viem";
5
- import { BundlerErrors } from "./errors.js";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.simulateBundlerOperations = exports.simulateBundlerOperation = exports.handleBundlerOperations = exports.handleBundlerOperation = exports.getSimulatedBundlerOperation = exports.simulateRequiredTokenAmounts = exports.populateBundle = exports.finalizeBundle = exports.populateSubBundle = exports.populateInputTransfer = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = void 0;
4
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ const simulation_sdk_1 = require("@morpho-org/simulation-sdk");
7
+ const viem_1 = require("viem");
8
+ const errors_js_1 = require("./errors.js");
6
9
  /**
7
10
  * The default target utilization above which the shared liquidity algorithm is triggered (scaled by WAD).
8
11
  */
9
- export const DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
10
- export const populateInputTransfer = ({ address, args: { amount, from } }, data, { hasSimplePermit = false } = {}) => {
11
- const { bundler3: { bundler3, generalAdapter1 }, permit2, } = getChainAddresses(data.chainId);
12
+ exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
13
+ const populateInputTransfer = ({ address, args: { amount, from } }, data, { hasSimplePermit = false } = {}) => {
14
+ const { bundler3: { generalAdapter1 }, permit2, } = (0, blue_sdk_1.getChainAddresses)(data.chainId);
12
15
  // If native token, it is expected to be sent along as call value.
13
- if (address === NATIVE_ADDRESS)
16
+ if (address === blue_sdk_1.NATIVE_ADDRESS)
14
17
  return [
15
18
  {
16
19
  type: "Erc20_Transfer",
@@ -45,8 +48,8 @@ export const populateInputTransfer = ({ address, args: { amount, from } }, data,
45
48
  hasSimplePermit);
46
49
  const useSimpleTransfer = permit2 == null ||
47
50
  // Token is permissioned and Permit2 may not be authorized so Permit2 cannot be used.
48
- !!permissionedWrapperTokens[data.chainId]?.has(address) ||
49
- !!permissionedBackedTokens[data.chainId]?.has(address);
51
+ !!blue_sdk_1.permissionedWrapperTokens[data.chainId]?.has(address) ||
52
+ !!blue_sdk_1.permissionedBackedTokens[data.chainId]?.has(address);
50
53
  if (useSimplePermit)
51
54
  operations.push({
52
55
  type: "Erc20_Permit",
@@ -87,7 +90,7 @@ export const populateInputTransfer = ({ address, args: { amount, from } }, data,
87
90
  sender: from,
88
91
  address,
89
92
  args: {
90
- amount: MathLib.MAX_UINT_160, // Always approve infinite.
93
+ amount: blue_sdk_1.MathLib.MAX_UINT_160, // Always approve infinite.
91
94
  spender: permit2,
92
95
  },
93
96
  });
@@ -99,13 +102,13 @@ export const populateInputTransfer = ({ address, args: { amount, from } }, data,
99
102
  address,
100
103
  args: {
101
104
  amount,
102
- expiration: MathLib.MAX_UINT_48, // Always approve indefinitely.
105
+ expiration: blue_sdk_1.MathLib.MAX_UINT_48, // Always approve indefinitely.
103
106
  nonce: permit2BundlerAllowance.nonce,
104
107
  },
105
108
  });
106
109
  operations.push({
107
110
  type: "Erc20_Transfer2",
108
- sender: bundler3,
111
+ sender: generalAdapter1,
109
112
  address,
110
113
  args: {
111
114
  amount,
@@ -116,6 +119,7 @@ export const populateInputTransfer = ({ address, args: { amount, from } }, data,
116
119
  }
117
120
  return operations;
118
121
  };
122
+ exports.populateInputTransfer = populateInputTransfer;
119
123
  /**
120
124
  * Simulates the input operation on the given simulation data with args tweaked so the bundler operates on behalf of the sender.
121
125
  * Then, populates a bundle of operations made of:
@@ -129,18 +133,18 @@ export const populateInputTransfer = ({ address, args: { amount, from } }, data,
129
133
  * @param wrapSlippage The slippage simulated during wraps. Should never be 0.
130
134
  * @return The bundle of operations to optimize and skim before being encoded.
131
135
  */
132
- export const populateSubBundle = (inputOperation, data, options = {}) => {
136
+ const populateSubBundle = (inputOperation, data, options = {}) => {
133
137
  const { sender } = inputOperation;
134
- const { morpho, bundler3: { bundler3, generalAdapter1 }, } = getChainAddresses(data.chainId);
138
+ const { morpho, bundler3: { bundler3, generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(data.chainId);
135
139
  const { withSimplePermit = new Set(), publicAllocatorOptions, getRequirementOperations, } = options;
136
140
  const operations = [];
137
141
  const wrappedToken = inputOperation.type === "Erc20_Wrap"
138
142
  ? data.getWrappedToken(inputOperation.address)
139
143
  : undefined;
140
144
  const isErc20Wrapper = !!wrappedToken &&
141
- !!erc20WrapperTokens[data.chainId]?.has(wrappedToken.address);
145
+ !!blue_sdk_1.erc20WrapperTokens[data.chainId]?.has(wrappedToken.address);
142
146
  // Transform input operation to act on behalf of the sender, via the bundler.
143
- const mainOperation = produceImmutable(inputOperation, (draft) => {
147
+ const mainOperation = (0, simulation_sdk_1.produceImmutable)(inputOperation, (draft) => {
144
148
  draft.sender = generalAdapter1;
145
149
  // Redirect MetaMorpho operation owner.
146
150
  switch (draft.type) {
@@ -203,8 +207,8 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
203
207
  const reallocations = {};
204
208
  const supplyTargetUtilization = publicAllocatorOptions.supplyTargetUtilization?.[market.params.id] ??
205
209
  publicAllocatorOptions.defaultSupplyTargetUtilization ??
206
- DEFAULT_SUPPLY_TARGET_UTILIZATION;
207
- if (MarketUtils.getUtilization({
210
+ exports.DEFAULT_SUPPLY_TARGET_UTILIZATION;
211
+ if (blue_sdk_1.MarketUtils.getUtilization({
208
212
  totalSupplyAssets: newTotalSupplyAssets,
209
213
  totalBorrowAssets: newTotalBorrowAssets,
210
214
  }) > supplyTargetUtilization) {
@@ -213,43 +217,46 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
213
217
  // We first try to find public reallocations that respect every markets targets.
214
218
  // If this is not enough, the first market to be pushed above target is the supply market. Then we fully withdraw from every market.
215
219
  let requiredAssets = supplyTargetUtilization === 0n
216
- ? MathLib.MAX_UINT_160
217
- : MathLib.wDivDown(newTotalBorrowAssets, supplyTargetUtilization) -
220
+ ? blue_sdk_1.MathLib.MAX_UINT_160
221
+ : blue_sdk_1.MathLib.wDivDown(newTotalBorrowAssets, supplyTargetUtilization) -
218
222
  newTotalSupplyAssets;
219
- let { withdrawals, data: simulationStatePostFriendlyReallocation } = data.getMarketPublicReallocations(market.id, publicAllocatorOptions);
220
- const marketPostFriendlyReallocation = simulationStatePostFriendlyReallocation.getMarket(market.id);
221
- if (marketPostFriendlyReallocation.totalBorrowAssets + borrowedAssets >
222
- marketPostFriendlyReallocation.totalSupplyAssets - withdrawnAssets) {
223
+ const { withdrawals, data: friendlyReallocationData } = data.getMarketPublicReallocations(market.id, publicAllocatorOptions);
224
+ const friendlyReallocationMarket = friendlyReallocationData.getMarket(market.id);
225
+ if (friendlyReallocationMarket.totalBorrowAssets + borrowedAssets >
226
+ friendlyReallocationMarket.totalSupplyAssets - withdrawnAssets) {
223
227
  // If the "friendly" reallocations are not enough, we fully withdraw from every market.
224
228
  requiredAssets = newTotalBorrowAssets - newTotalSupplyAssets;
225
- ({ withdrawals } = data.getMarketPublicReallocations(market.id, {
229
+ withdrawals.push(...friendlyReallocationData.getMarketPublicReallocations(market.id, {
226
230
  ...publicAllocatorOptions,
227
- defaultMaxWithdrawalUtilization: MathLib.WAD,
231
+ defaultMaxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
228
232
  maxWithdrawalUtilization: {},
229
- }));
233
+ }).withdrawals);
230
234
  }
231
235
  for (const { vault, ...withdrawal } of withdrawals) {
232
236
  const vaultReallocations = (reallocations[vault] ??= []);
233
- if (withdrawal.assets > requiredAssets) {
237
+ const vaultMarketReallocation = vaultReallocations.find((item) => item.id === withdrawal.id);
238
+ const reallocatedAssets = blue_sdk_1.MathLib.min(withdrawal.assets, requiredAssets);
239
+ if (vaultMarketReallocation != null)
240
+ vaultMarketReallocation.assets += reallocatedAssets;
241
+ else
234
242
  vaultReallocations.push({
235
243
  ...withdrawal,
236
- assets: requiredAssets,
244
+ assets: reallocatedAssets,
237
245
  });
246
+ requiredAssets -= reallocatedAssets;
247
+ if (requiredAssets === 0n)
238
248
  break;
239
- }
240
- requiredAssets -= withdrawal.assets;
241
- vaultReallocations.push(withdrawal);
242
249
  }
243
250
  // TODO: we know there are no unwrap native in the middle
244
251
  // of the bundle so we are certain we need to add an input transfer.
245
252
  // This could be handled by `simulateRequiredTokenAmounts` below.
246
- const fees = keys(reallocations).reduce((total, vault) => total + data.getVault(vault).publicAllocatorConfig.fee, 0n);
253
+ const fees = (0, morpho_ts_1.keys)(reallocations).reduce((total, vault) => total + data.getVault(vault).publicAllocatorConfig.fee, 0n);
247
254
  // Native input transfer of all fees.
248
255
  if (fees > 0n)
249
256
  operations.push({
250
257
  type: "Erc20_Transfer",
251
258
  sender,
252
- address: NATIVE_ADDRESS,
259
+ address: blue_sdk_1.NATIVE_ADDRESS,
253
260
  args: {
254
261
  amount: fees,
255
262
  from: sender,
@@ -269,7 +276,7 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
269
276
  },
270
277
  })));
271
278
  }
272
- const callback = getValue(mainOperation.args, "callback");
279
+ const callback = (0, morpho_ts_1.getValue)(mainOperation.args, "callback");
273
280
  const simulatedOperation = {
274
281
  ...mainOperation,
275
282
  args: {
@@ -277,9 +284,9 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
277
284
  ...(callback && {
278
285
  callback: (data) => {
279
286
  const operations = callback.flatMap((inputOperation) => {
280
- const subBundleOperations = populateSubBundle(inputOperation, data, options);
287
+ const subBundleOperations = (0, exports.populateSubBundle)(inputOperation, data, options);
281
288
  // Handle to mutate data (not simulate).
282
- handleBundlerOperations(subBundleOperations, data);
289
+ (0, exports.handleBundlerOperations)(subBundleOperations, data);
283
290
  return subBundleOperations;
284
291
  });
285
292
  mainOperation.args.callback =
@@ -290,27 +297,27 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
290
297
  },
291
298
  };
292
299
  // Operations with callbacks are populated recursively as a side-effect of the simulation, within the callback itself.
293
- let requiredTokenAmounts = simulateRequiredTokenAmounts(operations.concat([simulatedOperation]), data);
300
+ let requiredTokenAmounts = (0, exports.simulateRequiredTokenAmounts)(operations.concat([simulatedOperation]), data);
294
301
  const allOperations = operations.concat([
295
302
  mainOperation,
296
303
  ]);
297
304
  // Skip approvals/transfers if operation only uses available balances (via maxUint256).
298
305
  if (("amount" in mainOperation.args &&
299
- mainOperation.args.amount === maxUint256) ||
306
+ mainOperation.args.amount === viem_1.maxUint256) ||
300
307
  ("assets" in mainOperation.args &&
301
- mainOperation.args.assets === maxUint256) ||
302
- ("shares" in mainOperation.args && mainOperation.args.shares === maxUint256)) {
308
+ mainOperation.args.assets === viem_1.maxUint256) ||
309
+ ("shares" in mainOperation.args && mainOperation.args.shares === viem_1.maxUint256)) {
303
310
  if (mainOperation.type === "MetaMorpho_Withdraw")
304
311
  mainOperation.args.owner = generalAdapter1;
305
312
  return allOperations;
306
313
  }
307
314
  const requirementOperations = getRequirementOperations?.(requiredTokenAmounts) ?? [];
308
- requiredTokenAmounts = simulateRequiredTokenAmounts(requirementOperations
315
+ requiredTokenAmounts = (0, exports.simulateRequiredTokenAmounts)(requirementOperations
309
316
  .concat(allOperations)
310
- .map((operation) => getSimulatedBundlerOperation(operation)), data);
317
+ .map((operation) => (0, exports.getSimulatedBundlerOperation)(operation)), data);
311
318
  // Append required input transfers.
312
319
  requiredTokenAmounts.forEach(({ token, required }) => {
313
- requirementOperations.push(...populateInputTransfer({
320
+ requirementOperations.push(...(0, exports.populateInputTransfer)({
314
321
  type: "Erc20_Transfer",
315
322
  sender: generalAdapter1,
316
323
  address: token,
@@ -323,6 +330,7 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
323
330
  });
324
331
  return requirementOperations.concat(allOperations);
325
332
  };
333
+ exports.populateSubBundle = populateSubBundle;
326
334
  /**
327
335
  * Merges unnecessary duplicate `Erc20_Approve`, `Erc20_Transfer` and `Erc20_Wrap`.
328
336
  * Also redirects `Blue_Borrow|Withdraw|WithdrawCollateral` & `MetaMorpho_Withdraw` operations from the bundler to the receiver,
@@ -335,13 +343,13 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
335
343
  * @param unwrapSlippage The slippage simulated during unwraps. Should never be 0.
336
344
  * @return The optimized bundle.
337
345
  */
338
- export const finalizeBundle = (operations, startData, receiver, unwrapTokens = new Set(), unwrapSlippage = DEFAULT_SLIPPAGE_TOLERANCE) => {
346
+ const finalizeBundle = (operations, startData, receiver, unwrapTokens = new Set(), unwrapSlippage = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE) => {
339
347
  const nbOperations = operations.length;
340
348
  if (nbOperations === 0)
341
349
  return operations;
342
- const { bundler3: { bundler3, generalAdapter1 }, } = getChainAddresses(startData.chainId);
343
- if (isAddressEqual(receiver, bundler3) ||
344
- isAddressEqual(receiver, generalAdapter1))
350
+ const { bundler3: { bundler3, generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(startData.chainId);
351
+ if ((0, viem_1.isAddressEqual)(receiver, bundler3) ||
352
+ (0, viem_1.isAddressEqual)(receiver, generalAdapter1))
345
353
  throw Error(`receiver is bundler`);
346
354
  const approvals = [];
347
355
  const permits = [];
@@ -395,7 +403,7 @@ export const finalizeBundle = (operations, startData, receiver, unwrapTokens = n
395
403
  const { address, sender, args: { amount, from, to }, } = operation;
396
404
  if (from !== generalAdapter1 &&
397
405
  to === generalAdapter1 &&
398
- !erc20WrapperTokens[startData.chainId]?.has(address)) {
406
+ !blue_sdk_1.erc20WrapperTokens[startData.chainId]?.has(address)) {
399
407
  const duplicateTransfer = inputTransfers.find((transfer) => transfer.address === address &&
400
408
  transfer.sender === sender &&
401
409
  transfer.args.from === from);
@@ -438,7 +446,7 @@ export const finalizeBundle = (operations, startData, receiver, unwrapTokens = n
438
446
  inputTransfer2s,
439
447
  others,
440
448
  ].flat(1);
441
- let steps = simulateBundlerOperations(operations, startData);
449
+ let steps = (0, exports.simulateBundlerOperations)(operations, startData);
442
450
  // Redirect MetaMorpho deposits.
443
451
  operations.forEach((operation, index) => {
444
452
  if (operation.type !== "MetaMorpho_Deposit" ||
@@ -521,15 +529,15 @@ export const finalizeBundle = (operations, startData, receiver, unwrapTokens = n
521
529
  return false;
522
530
  });
523
531
  // Simulate without slippage to skim the bundler of all possible surplus of shares & assets.
524
- steps = simulateBundlerOperations(operations, startData, { slippage: 0n });
532
+ steps = (0, exports.simulateBundlerOperations)(operations, startData, { slippage: 0n });
525
533
  // Unwrap requested remaining wrapped tokens.
526
534
  const unwraps = [];
527
- const endBundlerTokenData = getLast(steps).holdings[generalAdapter1] ?? {};
535
+ const endBundlerTokenData = (0, morpho_ts_1.getLast)(steps).holdings[generalAdapter1] ?? {};
528
536
  unwrapTokens.forEach((wrappedToken) => {
529
537
  const remaining = endBundlerTokenData[wrappedToken]?.balance ?? 0n;
530
538
  if (remaining <= 5n)
531
539
  return;
532
- const unwrappedToken = getUnwrappedToken(wrappedToken, startData.chainId);
540
+ const unwrappedToken = (0, blue_sdk_1.getUnwrappedToken)(wrappedToken, startData.chainId);
533
541
  if (unwrappedToken == null)
534
542
  return;
535
543
  unwraps.push({
@@ -537,22 +545,22 @@ export const finalizeBundle = (operations, startData, receiver, unwrapTokens = n
537
545
  address: wrappedToken,
538
546
  sender: generalAdapter1,
539
547
  args: {
540
- amount: maxUint256,
548
+ amount: viem_1.maxUint256,
541
549
  receiver,
542
550
  slippage: unwrapSlippage,
543
551
  },
544
552
  });
545
553
  });
546
554
  if (unwraps.length > 0)
547
- steps = simulateBundlerOperations(operations.concat(unwraps), startData, {
555
+ steps = (0, exports.simulateBundlerOperations)(operations.concat(unwraps), startData, {
548
556
  slippage: 0n,
549
557
  });
550
558
  // Skim any token expected to be left on the bundler.
551
559
  const skims = [];
552
560
  {
553
561
  const startBundlerTokenData = steps[0].holdings[generalAdapter1] ?? {};
554
- const endBundlerTokenData = getLast(steps).holdings[generalAdapter1] ?? {};
555
- skims.push(...entries(endBundlerTokenData)
562
+ const endBundlerTokenData = (0, morpho_ts_1.getLast)(steps).holdings[generalAdapter1] ?? {};
563
+ skims.push(...(0, morpho_ts_1.entries)(endBundlerTokenData)
556
564
  .filter(([token, holding]) => holding != null &&
557
565
  holding.balance - (startBundlerTokenData[token]?.balance ?? 0n) >
558
566
  5n)
@@ -561,7 +569,7 @@ export const finalizeBundle = (operations, startData, receiver, unwrapTokens = n
561
569
  address,
562
570
  sender: generalAdapter1,
563
571
  args: {
564
- amount: maxUint256,
572
+ amount: viem_1.maxUint256,
565
573
  from: generalAdapter1,
566
574
  to: receiver,
567
575
  },
@@ -569,35 +577,37 @@ export const finalizeBundle = (operations, startData, receiver, unwrapTokens = n
569
577
  }
570
578
  return operations.concat(unwraps, skims);
571
579
  };
572
- export const populateBundle = (inputOperations, data, options) => {
580
+ exports.finalizeBundle = finalizeBundle;
581
+ const populateBundle = (inputOperations, data, options) => {
573
582
  const steps = [data];
574
583
  let end = data;
575
584
  const operations = inputOperations.flatMap((inputOperation, index) => {
576
585
  try {
577
- const subBundleOperations = populateSubBundle(inputOperation, end, options);
578
- steps.push((end = getLast(simulateBundlerOperations(subBundleOperations, end))));
586
+ const subBundleOperations = (0, exports.populateSubBundle)(inputOperation, end, options);
587
+ steps.push((end = (0, morpho_ts_1.getLast)((0, exports.simulateBundlerOperations)(subBundleOperations, end))));
579
588
  return subBundleOperations;
580
589
  }
581
590
  catch (error) {
582
591
  if (!(error instanceof Error))
583
592
  throw error;
584
- throw new BundlerErrors.Bundle(error, index, inputOperation, steps);
593
+ throw new errors_js_1.BundlerErrors.Bundle(error, index, inputOperation, steps);
585
594
  }
586
595
  });
587
596
  return { operations, steps };
588
597
  };
589
- export const simulateRequiredTokenAmounts = (operations, data) => {
590
- const { bundler3: { generalAdapter1 }, } = getChainAddresses(data.chainId);
591
- const virtualBundlerData = produceImmutable(data, (draft) => {
598
+ exports.populateBundle = populateBundle;
599
+ const simulateRequiredTokenAmounts = (operations, data) => {
600
+ const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(data.chainId);
601
+ const virtualBundlerData = (0, simulation_sdk_1.produceImmutable)(data, (draft) => {
592
602
  Object.values(draft.holdings[generalAdapter1] ?? {}).forEach((bundlerTokenData) => {
593
603
  if (bundlerTokenData == null)
594
604
  return;
595
605
  // Virtual balance to calculate the amount required.
596
- bundlerTokenData.balance += MathLib.MAX_UINT_160;
606
+ bundlerTokenData.balance += blue_sdk_1.MathLib.MAX_UINT_160;
597
607
  });
598
608
  });
599
- const steps = simulateOperations(operations, virtualBundlerData);
600
- const bundlerTokenDiffs = keys(virtualBundlerData.holdings[generalAdapter1]).map((token) => ({
609
+ const steps = (0, simulation_sdk_1.simulateOperations)(operations, virtualBundlerData);
610
+ const bundlerTokenDiffs = (0, morpho_ts_1.keys)(virtualBundlerData.holdings[generalAdapter1]).map((token) => ({
601
611
  token,
602
612
  required: steps
603
613
  .map((step) =>
@@ -606,22 +616,23 @@ export const simulateRequiredTokenAmounts = (operations, data) => {
606
616
  // | | |=> MAX_UINT_160 - (3 * MAX_UINT_160 + z) < 0
607
617
  // | |=> MAX_UINT_160 - (2 * MAX_UINT_160 - y) < 0
608
618
  // |=> MAX_UINT_160 - (MAX_UINT_160 - y - x) > 0
609
- MathLib.MAX_UINT_160 -
619
+ blue_sdk_1.MathLib.MAX_UINT_160 -
610
620
  (step.holdings[generalAdapter1]?.[token]?.balance ?? 0n))
611
- .sort(bigIntComparator((required) => required,
621
+ .sort((0, morpho_ts_1.bigIntComparator)((required) => required,
612
622
  // Take the highest required amount among all operations.
613
623
  "desc"))[0],
614
624
  }));
615
625
  return bundlerTokenDiffs.filter(({ required }) => required > 0n);
616
626
  };
617
- export const getSimulatedBundlerOperation = (operation, { slippage } = {}) => {
618
- const callback = getValue(operation.args, "callback");
627
+ exports.simulateRequiredTokenAmounts = simulateRequiredTokenAmounts;
628
+ const getSimulatedBundlerOperation = (operation, { slippage } = {}) => {
629
+ const callback = (0, morpho_ts_1.getValue)(operation.args, "callback");
619
630
  const simulatedOperation = {
620
631
  ...operation,
621
632
  args: {
622
633
  ...operation.args,
623
634
  ...(callback && {
624
- callback: () => callback.map((operation) => getSimulatedBundlerOperation(operation, { slippage })),
635
+ callback: () => callback.map((operation) => (0, exports.getSimulatedBundlerOperation)(operation, { slippage })),
625
636
  }),
626
637
  },
627
638
  };
@@ -641,7 +652,12 @@ export const getSimulatedBundlerOperation = (operation, { slippage } = {}) => {
641
652
  }
642
653
  return simulatedOperation;
643
654
  };
644
- export const handleBundlerOperation = (options) => (operation, startData, index) => handleOperation(getSimulatedBundlerOperation(operation, options), startData, index);
645
- export const handleBundlerOperations = (operations, startData, options) => handleOperations(operations, startData, handleBundlerOperation(options));
646
- export const simulateBundlerOperation = (options) => (operation, startData, index) => simulateOperation(getSimulatedBundlerOperation(operation, options), startData, index);
647
- export const simulateBundlerOperations = (operations, startData, options) => handleOperations(operations, startData, simulateBundlerOperation(options));
655
+ exports.getSimulatedBundlerOperation = getSimulatedBundlerOperation;
656
+ const handleBundlerOperation = (options) => (operation, startData, index) => (0, simulation_sdk_1.handleOperation)((0, exports.getSimulatedBundlerOperation)(operation, options), startData, index);
657
+ exports.handleBundlerOperation = handleBundlerOperation;
658
+ const handleBundlerOperations = (operations, startData, options) => (0, simulation_sdk_1.handleOperations)(operations, startData, (0, exports.handleBundlerOperation)(options));
659
+ exports.handleBundlerOperations = handleBundlerOperations;
660
+ const simulateBundlerOperation = (options) => (operation, startData, index) => (0, simulation_sdk_1.simulateOperation)((0, exports.getSimulatedBundlerOperation)(operation, options), startData, index);
661
+ exports.simulateBundlerOperation = simulateBundlerOperation;
662
+ const simulateBundlerOperations = (operations, startData, options) => (0, simulation_sdk_1.handleOperations)(operations, startData, (0, exports.simulateBundlerOperation)(options));
663
+ exports.simulateBundlerOperations = simulateBundlerOperations;