@morpho-org/bundler-sdk-viem 3.0.0-next.1 → 3.0.0-next.10

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.
@@ -0,0 +1,35 @@
1
+ import type { SimulationResult } from "@morpho-org/simulation-sdk";
2
+ import type { Account, Address, Chain, Client, Hex, Transport } from "viem";
3
+ import type { Action, SignatureRequirement, TransactionRequirement } from "./types/index.js";
4
+ export declare class ActionBundleRequirements<TR extends {
5
+ tx: {
6
+ to: Address;
7
+ data: Hex;
8
+ };
9
+ } = TransactionRequirement, SR extends SignatureRequirement = SignatureRequirement> {
10
+ readonly txs: TR[];
11
+ readonly signatures: SR[];
12
+ constructor(txs?: TR[], signatures?: SR[]);
13
+ sign(client: Client<Transport, Chain | undefined, Account>): Promise<Hex[]>;
14
+ sign(client: Client, account: Account): Promise<Hex[]>;
15
+ }
16
+ export declare class ActionBundle<TR extends {
17
+ tx: {
18
+ to: Address;
19
+ data: Hex;
20
+ };
21
+ } = TransactionRequirement, SR extends SignatureRequirement = SignatureRequirement> {
22
+ readonly steps: SimulationResult;
23
+ readonly actions: Action[];
24
+ readonly requirements: ActionBundleRequirements<TR, SR>;
25
+ constructor(steps: SimulationResult, actions?: Action[], requirements?: ActionBundleRequirements<TR, SR>);
26
+ tx(): {
27
+ to: `0x${string}`;
28
+ value: bigint;
29
+ data: `0x${string}`;
30
+ };
31
+ txs(): {
32
+ to: Address;
33
+ data: Hex;
34
+ }[];
35
+ }
@@ -0,0 +1,28 @@
1
+ import { BundlerAction } from "./BundlerAction.js";
2
+ export class ActionBundleRequirements {
3
+ txs;
4
+ signatures;
5
+ constructor(txs = [], signatures = []) {
6
+ this.txs = txs;
7
+ this.signatures = signatures;
8
+ }
9
+ sign(client, account = client.account) {
10
+ return Promise.all(this.signatures.map((requirement) => requirement.sign(client, account)));
11
+ }
12
+ }
13
+ export class ActionBundle {
14
+ steps;
15
+ actions;
16
+ requirements;
17
+ constructor(steps, actions = [], requirements = new ActionBundleRequirements()) {
18
+ this.steps = steps;
19
+ this.actions = actions;
20
+ this.requirements = requirements;
21
+ }
22
+ tx() {
23
+ return BundlerAction.encodeBundle(this.steps[0].chainId, this.actions);
24
+ }
25
+ txs() {
26
+ return this.requirements.txs.map(({ tx }) => tx).concat([this.tx()]);
27
+ }
28
+ }
@@ -9,7 +9,7 @@ export interface BundlerCall {
9
9
  callbackHash: Hex;
10
10
  }
11
11
  /**
12
- * Namespace to easily encode calls to the Bundler contract, using ethers.
12
+ * Namespace to easily encode calls to the Bundler contract, using viem.
13
13
  */
14
14
  export declare namespace BundlerAction {
15
15
  function encodeBundle(chainId: ChainId, actions: Action[]): {
@@ -33,7 +33,7 @@ export declare namespace BundlerAction {
33
33
  * @param recipient The address to send tokens to.
34
34
  * @param amount The amount of tokens to send.
35
35
  */
36
- function erc20Transfer(chainId: ChainId, asset: Address, recipient: Address, amount: bigint): BundlerCall[];
36
+ function erc20Transfer(chainId: ChainId, asset: Address, recipient: Address, amount: bigint, adapter?: Address): BundlerCall[];
37
37
  /**
38
38
  * Encodes a call to the Adapter to transfer ERC20 tokens from the sender to the Bundler.
39
39
  * @param chainId The chain id for which to encode the call.
@@ -340,7 +340,7 @@ export declare namespace BundlerAction {
340
340
  * @param manager The address of the manager to approve. Defaults to the chain's bundler3 AaveV3OptimizerMigrationAdapter.
341
341
  * @param skipRevert Whether to allow the signature to revert without making the whole multicall revert.
342
342
  */
343
- function aaveV3OptimizerApproveManagerWithSig(chainId: ChainId, owner: Address, isApproved: boolean, nonce: bigint, deadline: bigint, signature: Hex, manager?: Address, skipRevert?: boolean): BundlerCall[];
343
+ function aaveV3OptimizerApproveManagerWithSig(chainId: ChainId, aaveV3Optimizer: Address, owner: Address, isApproved: boolean, nonce: bigint, deadline: bigint, signature: Hex, manager?: Address, skipRevert?: boolean): BundlerCall[];
344
344
  /**
345
345
  * Encodes a call to the Adapter to repay a debt on CompoundV2.
346
346
  * @param chainId The chain id for which to encode the call.
@@ -348,7 +348,7 @@ export declare namespace BundlerAction {
348
348
  * @param amount The amount of debt to repay.
349
349
  * @param recipient The recipient of ERC20 tokens. Defaults to the chain's bundler3 general adapter.
350
350
  */
351
- function compoundV2Repay(chainId: ChainId, cToken: Address, amount: bigint, recipient?: Address): BundlerCall[];
351
+ function compoundV2Repay(chainId: ChainId, cToken: Address, amount: bigint, isEth: boolean, onBehalf: Address): BundlerCall[];
352
352
  /**
353
353
  * Encodes a call to the Adapter to withdraw collateral from CompoundV2.
354
354
  * @param chainId The chain id for which to encode the call.
@@ -356,7 +356,7 @@ export declare namespace BundlerAction {
356
356
  * @param amount The amount to withdraw.
357
357
  * @param recipient The recipient of ERC20 tokens. Defaults to the chain's bundler3 general adapter.
358
358
  */
359
- function compoundV2Redeem(chainId: ChainId, cToken: Address, amount: bigint, recipient?: Address): BundlerCall[];
359
+ function compoundV2Redeem(chainId: ChainId, cToken: Address, amount: bigint, isEth: boolean, recipient?: Address): BundlerCall[];
360
360
  /**
361
361
  * Encodes a call to the Adapter to repay a debt on CompoundV3.
362
362
  * @param chainId The chain id for which to encode the call.
@@ -388,4 +388,3 @@ export declare namespace BundlerAction {
388
388
  */
389
389
  function compoundV3AllowBySig(chainId: ChainId, instance: Address, owner: Address, isAllowed: boolean, nonce: bigint, expiry: bigint, signature: Hex, manager?: Address, skipRevert?: boolean): BundlerCall[];
390
390
  }
391
- export default BundlerAction;
@@ -1,18 +1,17 @@
1
1
  import { aaveV2MigrationAdapterAbi, aaveV3MigrationAdapterAbi, aaveV3OptimizerMigrationAdapterAbi, bundler3Abi, compoundV2MigrationAdapterAbi, compoundV3MigrationAdapterAbi, coreAdapterAbi, erc20WrapperAdapterAbi, ethereumGeneralAdapter1Abi, generalAdapter1Abi, universalRewardsDistributorAbi, } from "./abis.js";
2
2
  import { getChainAddresses, } from "@morpho-org/blue-sdk";
3
3
  import { blueAbi, erc2612Abi, permit2Abi, publicAllocatorAbi, } from "@morpho-org/blue-sdk-viem";
4
- import { encodeAbiParameters, encodeFunctionData, keccak256, maxUint256, parseSignature, toFunctionSelector, zeroHash, } from "viem";
4
+ import { encodeAbiParameters, encodeFunctionData, keccak256, maxUint256, parseSignature, zeroHash, } from "viem";
5
5
  import { BundlerErrors } from "./errors.js";
6
- const reenterSelectorHash = keccak256(toFunctionSelector(bundler3Abi.find((item) => item.type === "function" && item.name === "reenter")));
6
+ const reenterAbiInputs = bundler3Abi.find((item) => item.name === "reenter").inputs;
7
7
  /**
8
- * Namespace to easily encode calls to the Bundler contract, using ethers.
8
+ * Namespace to easily encode calls to the Bundler contract, using viem.
9
9
  */
10
10
  export var BundlerAction;
11
11
  (function (BundlerAction) {
12
12
  function encodeBundle(chainId, actions) {
13
13
  const { bundler3: { bundler3, generalAdapter1 }, } = getChainAddresses(chainId);
14
14
  let value = 0n;
15
- let generalAdapter1Value = 0n;
16
15
  for (const { type, args } of actions) {
17
16
  if (type !== "nativeTransfer")
18
17
  continue;
@@ -21,18 +20,8 @@ export var BundlerAction;
21
20
  owner !== generalAdapter1 &&
22
21
  (recipient === bundler3 || recipient === generalAdapter1))
23
22
  value += amount;
24
- if (owner !== generalAdapter1 && recipient === generalAdapter1)
25
- generalAdapter1Value += amount;
26
23
  }
27
24
  const encodedActions = actions.flatMap(BundlerAction.encode.bind(null, chainId));
28
- if (generalAdapter1Value > 0n)
29
- encodedActions.unshift({
30
- to: generalAdapter1,
31
- value: generalAdapter1Value,
32
- data: "0x",
33
- skipRevert: false,
34
- callbackHash: zeroHash,
35
- });
36
25
  return {
37
26
  to: bundler3,
38
27
  value,
@@ -178,10 +167,10 @@ export var BundlerAction;
178
167
  return BundlerAction.aaveV3OptimizerWithdrawCollateral(chainId, ...args);
179
168
  }
180
169
  case "aaveV3OptimizerApproveManagerWithSig": {
181
- const [owner, isApproved, nonce, deadline, signature, manager, skipRevert,] = args;
170
+ const [aaveV3Optimizer, owner, isApproved, nonce, deadline, signature, manager, skipRevert,] = args;
182
171
  if (signature == null)
183
172
  throw new BundlerErrors.MissingSignature();
184
- return BundlerAction.aaveV3OptimizerApproveManagerWithSig(chainId, owner, isApproved, nonce, deadline, signature, manager, skipRevert);
173
+ return BundlerAction.aaveV3OptimizerApproveManagerWithSig(chainId, aaveV3Optimizer, owner, isApproved, nonce, deadline, signature, manager, skipRevert);
185
174
  }
186
175
  /* CompoundV2 */
187
176
  case "compoundV2Repay": {
@@ -251,11 +240,12 @@ export var BundlerAction;
251
240
  * @param recipient The address to send tokens to.
252
241
  * @param amount The amount of tokens to send.
253
242
  */
254
- function erc20Transfer(chainId, asset, recipient, amount) {
243
+ function erc20Transfer(chainId, asset, recipient, amount, adapter) {
255
244
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
245
+ adapter ??= generalAdapter1;
256
246
  return [
257
247
  {
258
- to: generalAdapter1,
248
+ to: adapter,
259
249
  data: encodeFunctionData({
260
250
  abi: coreAdapterAbi,
261
251
  functionName: "erc20Transfer",
@@ -672,7 +662,7 @@ export var BundlerAction;
672
662
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
673
663
  const reenter = callbackCalls.length > 0;
674
664
  const reenterData = reenter
675
- ? encodeAbiParameters(bundler3Abi.find((item) => item.name === "reenter").inputs, [callbackCalls])
665
+ ? encodeAbiParameters(reenterAbiInputs, [callbackCalls])
676
666
  : "0x";
677
667
  return [
678
668
  {
@@ -701,7 +691,7 @@ export var BundlerAction;
701
691
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
702
692
  const reenter = callbackCalls.length > 0;
703
693
  const reenterData = reenter
704
- ? encodeAbiParameters(bundler3Abi.find((item) => item.name === "reenter").inputs, [callbackCalls])
694
+ ? encodeAbiParameters(reenterAbiInputs, [callbackCalls])
705
695
  : "0x";
706
696
  return [
707
697
  {
@@ -758,7 +748,7 @@ export var BundlerAction;
758
748
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
759
749
  const reenter = callbackCalls.length > 0;
760
750
  const reenterData = reenter
761
- ? encodeAbiParameters(bundler3Abi.find((item) => item.name === "reenter").inputs, [callbackCalls])
751
+ ? encodeAbiParameters(reenterAbiInputs, [callbackCalls])
762
752
  : "0x";
763
753
  return [
764
754
  {
@@ -834,6 +824,10 @@ export var BundlerAction;
834
824
  */
835
825
  function morphoFlashLoan(chainId, asset, amount, callbackCalls) {
836
826
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
827
+ const reenter = callbackCalls.length > 0;
828
+ const reenterData = reenter
829
+ ? encodeAbiParameters(reenterAbiInputs, [callbackCalls])
830
+ : "0x";
837
831
  return [
838
832
  {
839
833
  to: generalAdapter1,
@@ -852,7 +846,7 @@ export var BundlerAction;
852
846
  }),
853
847
  value: 0n,
854
848
  skipRevert: false,
855
- callbackHash: keccak256(`${generalAdapter1}${reenterSelectorHash}`),
849
+ callbackHash: reenter ? keccak256(reenterData) : zeroHash,
856
850
  },
857
851
  ];
858
852
  }
@@ -867,6 +861,8 @@ export var BundlerAction;
867
861
  */
868
862
  function publicAllocatorReallocateTo(chainId, vault, fee, withdrawals, supplyMarketParams) {
869
863
  const { publicAllocator } = getChainAddresses(chainId);
864
+ if (publicAllocator == null)
865
+ throw new BundlerErrors.UnexpectedAction("reallocateTo", chainId);
870
866
  return [
871
867
  {
872
868
  to: publicAllocator,
@@ -1239,9 +1235,9 @@ export var BundlerAction;
1239
1235
  * @param manager The address of the manager to approve. Defaults to the chain's bundler3 AaveV3OptimizerMigrationAdapter.
1240
1236
  * @param skipRevert Whether to allow the signature to revert without making the whole multicall revert.
1241
1237
  */
1242
- function aaveV3OptimizerApproveManagerWithSig(chainId, owner, isApproved, nonce, deadline, signature, manager, skipRevert = true) {
1243
- const { aaveV3Optimizer, bundler3: { aaveV3OptimizerMigrationAdapter }, } = getChainAddresses(chainId);
1244
- if (aaveV3Optimizer == null || aaveV3OptimizerMigrationAdapter == null)
1238
+ function aaveV3OptimizerApproveManagerWithSig(chainId, aaveV3Optimizer, owner, isApproved, nonce, deadline, signature, manager, skipRevert = true) {
1239
+ const { bundler3: { aaveV3OptimizerMigrationAdapter }, } = getChainAddresses(chainId);
1240
+ if (aaveV3OptimizerMigrationAdapter == null)
1245
1241
  throw new BundlerErrors.UnexpectedAction("aaveV3OptimizerApproveManagerWithSig", chainId);
1246
1242
  manager ??= aaveV3OptimizerMigrationAdapter;
1247
1243
  const { r, s, yParity } = parseSignature(signature);
@@ -1299,12 +1295,10 @@ export var BundlerAction;
1299
1295
  * @param amount The amount of debt to repay.
1300
1296
  * @param recipient The recipient of ERC20 tokens. Defaults to the chain's bundler3 general adapter.
1301
1297
  */
1302
- function compoundV2Repay(chainId, cToken, amount, recipient) {
1303
- const { cEth, bundler3: { compoundV2MigrationAdapter }, } = getChainAddresses(chainId);
1304
- if (cEth == null || compoundV2MigrationAdapter == null)
1298
+ function compoundV2Repay(chainId, cToken, amount, isEth, onBehalf) {
1299
+ const { bundler3: { compoundV2MigrationAdapter }, } = getChainAddresses(chainId);
1300
+ if (compoundV2MigrationAdapter == null)
1305
1301
  throw new BundlerErrors.UnexpectedAction("compoundV2Repay", chainId);
1306
- const isEth = cToken === cEth;
1307
- recipient ??= compoundV2MigrationAdapter;
1308
1302
  return [
1309
1303
  {
1310
1304
  to: compoundV2MigrationAdapter,
@@ -1312,12 +1306,12 @@ export var BundlerAction;
1312
1306
  ? encodeFunctionData({
1313
1307
  abi: compoundV2MigrationAdapterAbi,
1314
1308
  functionName: "compoundV2RepayEth",
1315
- args: [amount, recipient],
1309
+ args: [amount, onBehalf],
1316
1310
  })
1317
1311
  : encodeFunctionData({
1318
1312
  abi: compoundV2MigrationAdapterAbi,
1319
1313
  functionName: "compoundV2RepayErc20",
1320
- args: [cToken, amount, recipient],
1314
+ args: [cToken, amount, onBehalf],
1321
1315
  }),
1322
1316
  value: isEth ? amount : 0n,
1323
1317
  skipRevert: false,
@@ -1333,11 +1327,10 @@ export var BundlerAction;
1333
1327
  * @param amount The amount to withdraw.
1334
1328
  * @param recipient The recipient of ERC20 tokens. Defaults to the chain's bundler3 general adapter.
1335
1329
  */
1336
- function compoundV2Redeem(chainId, cToken, amount, recipient) {
1337
- const { cEth, bundler3: { compoundV2MigrationAdapter }, } = getChainAddresses(chainId);
1338
- if (cEth == null || compoundV2MigrationAdapter == null)
1330
+ function compoundV2Redeem(chainId, cToken, amount, isEth, recipient) {
1331
+ const { bundler3: { compoundV2MigrationAdapter }, } = getChainAddresses(chainId);
1332
+ if (compoundV2MigrationAdapter == null)
1339
1333
  throw new BundlerErrors.UnexpectedAction("compoundV2Repay", chainId);
1340
- const isEth = cToken === cEth;
1341
1334
  recipient ??= compoundV2MigrationAdapter;
1342
1335
  return [
1343
1336
  {
@@ -1466,4 +1459,3 @@ export var BundlerAction;
1466
1459
  }
1467
1460
  BundlerAction.compoundV3AllowBySig = compoundV3AllowBySig;
1468
1461
  })(BundlerAction || (BundlerAction = {}));
1469
- export default BundlerAction;
package/lib/actions.d.ts CHANGED
@@ -1,14 +1,12 @@
1
1
  import { type Address } from "viem";
2
- import { ChainId } from "@morpho-org/blue-sdk";
3
2
  import { type MaybeDraft, type SimulationState } from "@morpho-org/simulation-sdk";
4
- import type { Action, ActionBundle, BundlerOperation, TransactionRequirement } from "./types/index.js";
5
- export declare const APPROVE_ONLY_ONCE_TOKENS: Partial<Record<ChainId, Address[]>>;
3
+ import { ActionBundle, ActionBundleRequirements } from "./ActionBundle.js";
4
+ import type { Action, BundlerOperation, TransactionRequirement } from "./types/index.js";
5
+ export declare const APPROVE_ONLY_ONCE_TOKENS: Partial<Record<number, Address[]>>;
6
+ export declare const MAX_TOKEN_APPROVALS: Partial<Record<number, Record<Address, bigint>>>;
6
7
  export declare const encodeOperation: (operation: BundlerOperation, dataBefore: MaybeDraft<SimulationState>, supportsSignature?: boolean, index?: number) => {
7
8
  dataAfter: MaybeDraft<SimulationState>;
8
9
  actions: Action[];
9
- requirements: {
10
- signatures: import("./types/actions.js").SignatureRequirement[];
11
- txs: TransactionRequirement[];
12
- };
10
+ requirements: ActionBundleRequirements<TransactionRequirement, import("./types/actions.js").SignatureRequirement>;
13
11
  };
14
- export declare function encodeBundle(operations: BundlerOperation[], startData: MaybeDraft<SimulationState>, supportsSignature?: boolean): ActionBundle;
12
+ export declare function encodeBundle(operations: BundlerOperation[], startData: MaybeDraft<SimulationState>, supportsSignature?: boolean): ActionBundle<TransactionRequirement, import("./types/actions.js").SignatureRequirement>;
package/lib/actions.js CHANGED
@@ -1,17 +1,17 @@
1
1
  import { encodeFunctionData, erc20Abi, maxUint256, verifyTypedData, zeroAddress, } from "viem";
2
- import { ChainId, MathLib, NATIVE_ADDRESS, convexWrapperTokens, erc20WrapperTokens, getChainAddresses, getUnwrappedToken, } from "@morpho-org/blue-sdk";
2
+ import { ChainId, DEFAULT_SLIPPAGE_TOLERANCE, MathLib, NATIVE_ADDRESS, convexWrapperTokens, erc20WrapperTokens, getChainAddresses, getUnwrappedToken, } from "@morpho-org/blue-sdk";
3
3
  import { Time, getValue } from "@morpho-org/morpho-ts";
4
- import { simulateOperation, } from "@morpho-org/simulation-sdk";
4
+ import { getCurrent, simulateOperation, } from "@morpho-org/simulation-sdk";
5
5
  import { blueAbi, getAuthorizationTypedData, getDaiPermitTypedData, getPermit2PermitTypedData, getPermitTypedData, } from "@morpho-org/blue-sdk-viem";
6
6
  import { signTypedData } from "viem/actions";
7
- import BundlerAction from "./BundlerAction.js";
7
+ import { ActionBundle, ActionBundleRequirements } from "./ActionBundle.js";
8
8
  export const APPROVE_ONLY_ONCE_TOKENS = {
9
9
  [ChainId.EthMainnet]: [
10
10
  "0xdAC17F958D2ee523a2206206994597C13D831ec7", // USDT
11
11
  "0xD533a949740bb3306d119CC777fa900bA034cd52", // CRV
12
12
  ],
13
13
  };
14
- const MAX_TOKEN_APPROVALS = {
14
+ export const MAX_TOKEN_APPROVALS = {
15
15
  [ChainId.EthMainnet]: {
16
16
  "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984": MathLib.maxUint(96), // UNI --> see https://github.com/Uniswap/governance/blob/eabd8c71ad01f61fb54ed6945162021ee419998e/contracts/Uni.sol#L154
17
17
  },
@@ -67,10 +67,7 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
67
67
  const deadline = Time.timestamp() + Time.s.from.h(24n);
68
68
  const { morpho, bundler3: { bundler3, generalAdapter1 }, permit2, wNative, dai, wstEth, stEth, } = getChainAddresses(chainId);
69
69
  const actions = [];
70
- const requirements = {
71
- signatures: [],
72
- txs: [],
73
- };
70
+ const requirements = new ActionBundleRequirements();
74
71
  let callbackBundle;
75
72
  const callback = getValue(operation.args, "callback");
76
73
  const simulatedOperation = {
@@ -79,7 +76,7 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
79
76
  ...operation.args,
80
77
  ...(callback && {
81
78
  callback: (dataBefore) => {
82
- callbackBundle = encodeBundle(callback, dataBefore, supportsSignature);
79
+ callbackBundle = encodeBundle(callback, getCurrent(dataBefore), supportsSignature);
83
80
  return callback;
84
81
  },
85
82
  }),
@@ -94,13 +91,13 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
94
91
  const { sender, address } = operation;
95
92
  switch (operation.type) {
96
93
  case "Blue_SetAuthorization": {
97
- const { owner } = operation.args;
94
+ const { owner, isAuthorized, authorized } = operation.args;
98
95
  if (supportsSignature) {
99
96
  const ownerData = dataBefore.getUser(owner);
100
97
  const authorization = {
101
98
  authorizer: owner,
102
- authorized: generalAdapter1,
103
- isAuthorized: true,
99
+ authorized,
100
+ isAuthorized,
104
101
  deadline,
105
102
  nonce: ownerData.morphoNonce,
106
103
  };
@@ -133,13 +130,13 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
133
130
  // Signatures are not supported, fallback to standard approval.
134
131
  requirements.txs.push({
135
132
  type: "morphoSetAuthorization",
136
- args: [generalAdapter1, true],
133
+ args: [authorized, isAuthorized],
137
134
  tx: {
138
135
  to: morpho,
139
136
  data: encodeFunctionData({
140
137
  abi: blueAbi,
141
138
  functionName: "setAuthorization",
142
- args: [generalAdapter1, true],
139
+ args: [authorized, isAuthorized],
143
140
  }),
144
141
  },
145
142
  });
@@ -346,7 +343,7 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
346
343
  break;
347
344
  }
348
345
  default: {
349
- if (erc20WrapperTokens[chainId].has(address)) {
346
+ if (erc20WrapperTokens[chainId]?.has(address)) {
350
347
  const underlying = getUnwrappedToken(address, chainId);
351
348
  if (underlying == null)
352
349
  throw Error(`unknown wrapped token: ${address}`);
@@ -357,7 +354,7 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
357
354
  break;
358
355
  }
359
356
  // Convex token wrapping is executed onchain along with supplyCollateral, via depositFor.
360
- if (!convexWrapperTokens[chainId].has(address))
357
+ if (!convexWrapperTokens[chainId]?.has(address))
361
358
  throw Error(`unexpected token wrap: ${address}`);
362
359
  }
363
360
  }
@@ -381,7 +378,7 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
381
378
  break;
382
379
  }
383
380
  default: {
384
- if (!erc20WrapperTokens[chainId].has(address))
381
+ if (!erc20WrapperTokens[chainId]?.has(address))
385
382
  throw Error(`unexpected token unwrap: ${address}`);
386
383
  actions.push({
387
384
  type: "erc20WrapperWithdrawTo",
@@ -392,14 +389,13 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
392
389
  break;
393
390
  }
394
391
  case "Blue_Supply": {
395
- const { id, assets = 0n, shares = 0n, onBehalf, slippage = 0n, } = operation.args;
396
- const { params, totalSupplyAssets, totalSupplyShares } = dataBefore.getMarket(id);
397
- const maxSharePrice = (totalSupplyAssets * MathLib.wToRay(MathLib.WAD + slippage)) /
398
- totalSupplyShares;
392
+ const { id, assets = 0n, shares = 0n, onBehalf, slippage = DEFAULT_SLIPPAGE_TOLERANCE, } = operation.args;
393
+ const market = dataBefore.getMarket(id);
394
+ const maxSharePrice = market.toSupplyAssets(MathLib.wToRay(MathLib.WAD + slippage));
399
395
  actions.push({
400
396
  type: "morphoSupply",
401
397
  args: [
402
- params,
398
+ market.params,
403
399
  assets,
404
400
  shares,
405
401
  maxSharePrice,
@@ -410,36 +406,33 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
410
406
  break;
411
407
  }
412
408
  case "Blue_Withdraw": {
413
- const { id, assets = 0n, shares = 0n, receiver, slippage = 0n, } = operation.args;
414
- const { params, totalSupplyAssets, totalSupplyShares } = dataBefore.getMarket(id);
415
- const minSharePrice = (totalSupplyAssets * MathLib.wToRay(MathLib.WAD - slippage)) /
416
- totalSupplyShares;
409
+ const { id, assets = 0n, shares = 0n, receiver, slippage = DEFAULT_SLIPPAGE_TOLERANCE, } = operation.args;
410
+ const market = dataBefore.getMarket(id);
411
+ const minSharePrice = market.toSupplyAssets(MathLib.wToRay(MathLib.WAD - slippage));
417
412
  actions.push({
418
413
  type: "morphoWithdraw",
419
- args: [params, assets, shares, minSharePrice, receiver],
414
+ args: [market.params, assets, shares, minSharePrice, receiver],
420
415
  });
421
416
  break;
422
417
  }
423
418
  case "Blue_Borrow": {
424
- const { id, assets = 0n, shares = 0n, receiver, slippage = 0n, } = operation.args;
425
- const { params, totalBorrowAssets, totalBorrowShares } = dataBefore.getMarket(id);
426
- const minSharePrice = (totalBorrowAssets * MathLib.wToRay(MathLib.WAD - slippage)) /
427
- totalBorrowShares;
419
+ const { id, assets = 0n, shares = 0n, receiver, slippage = DEFAULT_SLIPPAGE_TOLERANCE, } = operation.args;
420
+ const market = dataBefore.getMarket(id);
421
+ const minSharePrice = market.toBorrowAssets(MathLib.wToRay(MathLib.WAD - slippage));
428
422
  actions.push({
429
423
  type: "morphoBorrow",
430
- args: [params, assets, shares, minSharePrice, receiver],
424
+ args: [market.params, assets, shares, minSharePrice, receiver],
431
425
  });
432
426
  break;
433
427
  }
434
428
  case "Blue_Repay": {
435
- const { id, assets = 0n, shares = 0n, onBehalf, slippage = 0n, } = operation.args;
436
- const { params, totalBorrowAssets, totalBorrowShares } = dataBefore.getMarket(id);
437
- const maxSharePrice = (totalBorrowAssets * MathLib.wToRay(MathLib.WAD + slippage)) /
438
- totalBorrowShares;
429
+ const { id, assets = 0n, shares = 0n, onBehalf, slippage = DEFAULT_SLIPPAGE_TOLERANCE, } = operation.args;
430
+ const market = dataBefore.getMarket(id);
431
+ const maxSharePrice = market.toBorrowAssets(MathLib.wToRay(MathLib.WAD + slippage));
439
432
  actions.push({
440
433
  type: "morphoRepay",
441
434
  args: [
442
- params,
435
+ market.params,
443
436
  assets,
444
437
  shares,
445
438
  maxSharePrice,
@@ -452,7 +445,7 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
452
445
  case "Blue_SupplyCollateral": {
453
446
  const { id, assets, onBehalf } = operation.args;
454
447
  const { params } = dataBefore.getMarket(id);
455
- if (convexWrapperTokens[chainId].has(params.collateralToken)) {
448
+ if (convexWrapperTokens[chainId]?.has(params.collateralToken)) {
456
449
  const underlying = getUnwrappedToken(address, chainId);
457
450
  if (underlying == null)
458
451
  throw Error(`unknown wrapped token: ${address}`);
@@ -478,10 +471,9 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
478
471
  break;
479
472
  }
480
473
  case "MetaMorpho_Deposit": {
481
- const { assets = 0n, shares = 0n, owner, slippage = 0n } = operation.args;
474
+ const { assets = 0n, shares = 0n, owner, slippage = DEFAULT_SLIPPAGE_TOLERANCE, } = operation.args;
482
475
  const vault = dataBefore.getVault(address);
483
- const maxSharePrice = (vault.totalAssets * MathLib.wToRay(MathLib.WAD + slippage)) /
484
- vault.totalSupply;
476
+ const maxSharePrice = vault.toAssets(MathLib.wToRay(MathLib.WAD + slippage));
485
477
  if (shares === 0n)
486
478
  actions.push({
487
479
  type: "erc4626Deposit",
@@ -495,10 +487,9 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
495
487
  break;
496
488
  }
497
489
  case "MetaMorpho_Withdraw": {
498
- const { assets = 0n, shares = 0n, owner, receiver, slippage = 0n, } = operation.args;
490
+ const { assets = 0n, shares = 0n, owner, receiver, slippage = DEFAULT_SLIPPAGE_TOLERANCE, } = operation.args;
499
491
  const vault = dataBefore.getVault(address);
500
- const minSharePrice = (vault.totalAssets * MathLib.wToRay(MathLib.WAD - slippage)) /
501
- vault.totalSupply;
492
+ const minSharePrice = vault.toAssets(MathLib.wToRay(MathLib.WAD - slippage));
502
493
  if (assets > 0n)
503
494
  actions.push({
504
495
  type: "erc4626Withdraw",
@@ -537,24 +528,13 @@ export const encodeOperation = (operation, dataBefore, supportsSignature = true,
537
528
  };
538
529
  };
539
530
  export function encodeBundle(operations, startData, supportsSignature = true) {
540
- const { chainId } = startData;
541
- const actions = [];
542
- const requirements = {
543
- signatures: [],
544
- txs: [],
545
- };
546
- const steps = [startData];
531
+ const bundle = new ActionBundle([startData]);
547
532
  for (let index = 0; index < operations.length; ++index) {
548
- const bundle = encodeOperation(operations[index], steps[index], supportsSignature, index);
549
- steps.push(bundle.dataAfter);
550
- actions.push(...bundle.actions);
551
- requirements.signatures.push(...bundle.requirements.signatures);
552
- requirements.txs.push(...bundle.requirements.txs);
533
+ const { dataAfter, actions, requirements } = encodeOperation(operations[index], bundle.steps[index], supportsSignature, index);
534
+ bundle.steps.push(dataAfter);
535
+ bundle.actions.push(...actions);
536
+ bundle.requirements.signatures.push(...requirements.signatures);
537
+ bundle.requirements.txs.push(...requirements.txs);
553
538
  }
554
- return {
555
- steps,
556
- actions,
557
- requirements,
558
- tx: () => BundlerAction.encodeBundle(chainId, actions),
559
- };
539
+ return bundle;
560
540
  }
@@ -0,0 +1,12 @@
1
+ import type { SimulationState } from "@morpho-org/simulation-sdk";
2
+ import type { Address } from "viem";
3
+ import { type BundlingOptions } from "./operations.js";
4
+ import type { InputBundlerOperation } from "./types/index.js";
5
+ export declare const setupBundle: (inputOperations: InputBundlerOperation[], startData: SimulationState, receiver: Address, { supportsSignature, unwrapTokens, unwrapSlippage, ...options }?: BundlingOptions & {
6
+ supportsSignature?: boolean;
7
+ unwrapTokens?: Set<Address>;
8
+ unwrapSlippage?: bigint;
9
+ }) => {
10
+ operations: import("./types/operations.js").BundlerOperation[];
11
+ bundle: import("./ActionBundle.js").ActionBundle<import("./types/actions.js").TransactionRequirement, import("./types/actions.js").SignatureRequirement>;
12
+ };
package/lib/bundle.js ADDED
@@ -0,0 +1,11 @@
1
+ import { encodeBundle } from "./actions.js";
2
+ import { finalizeBundle, populateBundle, } from "./operations.js";
3
+ export const setupBundle = (inputOperations, startData, receiver, { supportsSignature, unwrapTokens, unwrapSlippage, ...options } = {}) => {
4
+ let { operations } = populateBundle(inputOperations, startData, options);
5
+ operations = finalizeBundle(operations, startData, receiver, unwrapTokens, unwrapSlippage);
6
+ const bundle = encodeBundle(operations, startData, supportsSignature);
7
+ return {
8
+ operations,
9
+ bundle,
10
+ };
11
+ };
package/lib/index.d.ts CHANGED
@@ -2,3 +2,7 @@ export * from "./actions.js";
2
2
  export * from "./operations.js";
3
3
  export * from "./errors.js";
4
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";
package/lib/index.js CHANGED
@@ -2,3 +2,7 @@ export * from "./actions.js";
2
2
  export * from "./operations.js";
3
3
  export * from "./errors.js";
4
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";
package/lib/operations.js CHANGED
@@ -45,8 +45,8 @@ export const populateInputTransfer = ({ address, args: { amount, from } }, data,
45
45
  hasSimplePermit);
46
46
  const useSimpleTransfer = permit2 == null ||
47
47
  // 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);
48
+ !!permissionedWrapperTokens[data.chainId]?.has(address) ||
49
+ !!permissionedBackedTokens[data.chainId]?.has(address);
50
50
  if (useSimplePermit)
51
51
  operations.push({
52
52
  type: "Erc20_Permit",
@@ -138,7 +138,7 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
138
138
  ? data.getWrappedToken(inputOperation.address)
139
139
  : undefined;
140
140
  const isErc20Wrapper = !!wrappedToken &&
141
- erc20WrapperTokens[data.chainId].has(wrappedToken.address);
141
+ !!erc20WrapperTokens[data.chainId]?.has(wrappedToken.address);
142
142
  // Transform input operation to act on behalf of the sender, via the bundler.
143
143
  const mainOperation = produceImmutable(inputOperation, (draft) => {
144
144
  draft.sender = generalAdapter1;
@@ -179,7 +179,8 @@ export const populateSubBundle = (inputOperation, data, options = {}) => {
179
179
  address: morpho,
180
180
  args: {
181
181
  owner: sender,
182
- isBundlerAuthorized: true,
182
+ isAuthorized: true,
183
+ authorized: generalAdapter1,
183
184
  },
184
185
  });
185
186
  // Reallocate liquidity if necessary.
@@ -394,7 +395,7 @@ export const finalizeBundle = (operations, startData, receiver, unwrapTokens = n
394
395
  const { address, sender, args: { amount, from, to }, } = operation;
395
396
  if (from !== generalAdapter1 &&
396
397
  to === generalAdapter1 &&
397
- !erc20WrapperTokens[startData.chainId].has(address)) {
398
+ !erc20WrapperTokens[startData.chainId]?.has(address)) {
398
399
  const duplicateTransfer = inputTransfers.find((transfer) => transfer.address === address &&
399
400
  transfer.sender === sender &&
400
401
  transfer.args.from === from);
@@ -1,6 +1,5 @@
1
1
  import type { Account, Chain, Client, Hex, TransactionRequest, Transport } from "viem";
2
2
  import type { Address, InputMarketParams } from "@morpho-org/blue-sdk";
3
- import type { SimulationResult } from "@morpho-org/simulation-sdk";
4
3
  export interface Authorization {
5
4
  authorizer: Address;
6
5
  authorized: Address;
@@ -25,7 +24,12 @@ export interface Permit2PermitSingle {
25
24
  }
26
25
  export interface ActionArgs {
27
26
  nativeTransfer: [owner: Address, recipient: Address, amount: bigint];
28
- erc20Transfer: [asset: Address, recipient: Address, amount: bigint];
27
+ erc20Transfer: [
28
+ asset: Address,
29
+ recipient: Address,
30
+ amount: bigint,
31
+ adapter?: Address
32
+ ];
29
33
  erc20TransferFrom: [asset: Address, amount: bigint, recipient?: Address];
30
34
  erc20WrapperDepositFor: [
31
35
  wrapper: Address,
@@ -196,6 +200,7 @@ export interface ActionArgs {
196
200
  recipient?: Address
197
201
  ];
198
202
  aaveV3OptimizerApproveManagerWithSig: [
203
+ aaveV3Optimizer: Address,
199
204
  owner: Address,
200
205
  isApproved: boolean,
201
206
  nonce: bigint,
@@ -204,8 +209,18 @@ export interface ActionArgs {
204
209
  manager?: Address,
205
210
  skipRevert?: boolean
206
211
  ];
207
- compoundV2Repay: [cToken: Address, amount: bigint, onBehalf: Address];
208
- compoundV2Redeem: [cToken: Address, amount: bigint, recipient?: Address];
212
+ compoundV2Repay: [
213
+ cToken: Address,
214
+ amount: bigint,
215
+ isEth: boolean,
216
+ onBehalf: Address
217
+ ];
218
+ compoundV2Redeem: [
219
+ cToken: Address,
220
+ amount: bigint,
221
+ isEth: boolean,
222
+ recipient?: Address
223
+ ];
209
224
  compoundV3Repay: [instance: Address, amount: bigint, onBehalf: Address];
210
225
  compoundV3WithdrawFrom: [
211
226
  instance: Address,
@@ -256,15 +271,3 @@ export interface SignatureRequirement {
256
271
  action: Action;
257
272
  sign: SignatureRequirementFunction;
258
273
  }
259
- export interface ActionBundle {
260
- steps: SimulationResult;
261
- actions: Action[];
262
- requirements: {
263
- signatures: SignatureRequirement[];
264
- txs: TransactionRequirement[];
265
- };
266
- tx: () => TransactionRequest & {
267
- to: Address;
268
- data: Hex;
269
- };
270
- }
@@ -21,7 +21,7 @@ export type CallbackBundlerOperations = {
21
21
  [OperationType in CallbackBundlerOperationType]: WithOperationArgs<OperationType, BundlerOperationArgs>;
22
22
  };
23
23
  export type CallbackBundlerOperation = CallbackBundlerOperations[CallbackBundlerOperationType];
24
- export declare const BLUE_INPUT_OPERATIONS: readonly ["Blue_Borrow", "Blue_Repay", "Blue_Supply", "Blue_SupplyCollateral", "Blue_Withdraw", "Blue_WithdrawCollateral"];
24
+ export declare const BLUE_INPUT_OPERATIONS: readonly ["Blue_Borrow", "Blue_Repay", "Blue_Supply", "Blue_SupplyCollateral", "Blue_Withdraw", "Blue_WithdrawCollateral", "Blue_SetAuthorization"];
25
25
  export type BlueInputBundlerOperationType = (typeof BLUE_INPUT_OPERATIONS)[number];
26
26
  export interface BlueInputBundlerOperationArgs extends Omit<OperationArgs, (typeof CALLBACK_OPERATIONS)[number]> {
27
27
  Blue_SupplyCollateral: Omit<BlueOperationArgs["Blue_SupplyCollateral"], "callback"> & {
@@ -24,6 +24,7 @@ export const BLUE_INPUT_OPERATIONS = [
24
24
  "Blue_SupplyCollateral",
25
25
  "Blue_Withdraw",
26
26
  "Blue_WithdrawCollateral",
27
+ "Blue_SetAuthorization",
27
28
  ];
28
29
  export const METAMORPHO_INPUT_OPERATIONS = [
29
30
  "MetaMorpho_Deposit",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@morpho-org/bundler-sdk-viem",
3
3
  "description": "Viem-based extension of `@morpho-org/simulation-sdk` that exports utilities to transform simple interactions on Morpho (such as `Blue_Borrow`) and Morpho Vaults (such as `MetaMorpho_Deposit`) into the required bundles (with ERC20 approvals, transfers, etc) to submit to the bundler onchain.",
4
- "version": "3.0.0-next.1",
4
+ "version": "3.0.0-next.10",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "contributors": [
7
7
  "Rubilmax <rmilon@gmail.com>"
@@ -20,10 +20,10 @@
20
20
  ],
21
21
  "peerDependencies": {
22
22
  "viem": "^2.0.0",
23
- "@morpho-org/blue-sdk-viem": "^3.0.0-next.1",
24
- "@morpho-org/simulation-sdk": "^3.0.0-next.1",
25
- "@morpho-org/blue-sdk": "^3.0.0-next.3",
26
- "@morpho-org/morpho-ts": "^2.1.0"
23
+ "@morpho-org/blue-sdk": "^2.3.2",
24
+ "@morpho-org/blue-sdk-viem": "^2.2.2",
25
+ "@morpho-org/morpho-ts": "^2.2.0",
26
+ "@morpho-org/simulation-sdk": "^2.1.4"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@tanstack/query-core": "^5.62.16",
@@ -35,14 +35,14 @@
35
35
  "typescript": "^5.7.2",
36
36
  "viem": "^2.23.0",
37
37
  "vitest": "^3.0.5",
38
- "@morpho-org/blue-sdk": "^3.0.0-next.3",
39
- "@morpho-org/blue-sdk-viem": "^3.0.0-next.1",
38
+ "@morpho-org/blue-sdk": "^2.3.2",
39
+ "@morpho-org/blue-sdk-viem": "^2.2.2",
40
40
  "@morpho-org/morpho-test": "^2.2.1",
41
- "@morpho-org/morpho-ts": "^2.1.0",
42
- "@morpho-org/simulation-sdk": "^3.0.0-next.1",
41
+ "@morpho-org/morpho-ts": "^2.2.0",
42
+ "@morpho-org/simulation-sdk": "^2.1.4",
43
43
  "@morpho-org/simulation-sdk-wagmi": "^2.0.5",
44
- "@morpho-org/test": "^2.0.6",
45
- "@morpho-org/test-wagmi": "^2.0.4"
44
+ "@morpho-org/test-wagmi": "^2.0.4",
45
+ "@morpho-org/test": "^2.1.0"
46
46
  },
47
47
  "scripts": {
48
48
  "prepublish": "$npm_execpath build",