@emberai/onchain-actions-registry 1.0.0-alpha.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/dist/index.js ADDED
@@ -0,0 +1,1433 @@
1
+ // src/aave-lending-plugin/adapter.ts
2
+ import {
3
+ Pool,
4
+ PoolBundle,
5
+ InterestRate
6
+ } from "@aave/contract-helpers";
7
+ import { ethers as ethers3, utils } from "ethers";
8
+
9
+ // src/core/schemas/core.ts
10
+ import { z as z2 } from "zod";
11
+
12
+ // src/core/schemas/enums.ts
13
+ import { z } from "zod";
14
+ var ChainTypeSchema = z.enum(["UNSPECIFIED", "EVM", "SOLANA", "COSMOS"]);
15
+ var TransactionTypes = {
16
+ TRANSACTION_TYPE_UNSPECIFIED: "TRANSACTION_TYPE_UNSPECIFIED",
17
+ EVM_TX: "EVM_TX",
18
+ SOLANA_TX: "SOLANA_TX"
19
+ };
20
+ var TransactionTypeSchema = z.enum(
21
+ Object.values(TransactionTypes)
22
+ );
23
+
24
+ // src/core/schemas/core.ts
25
+ var TokenIdentifierSchema = z2.object({
26
+ chainId: z2.string(),
27
+ address: z2.string()
28
+ });
29
+ var TokenSchema = z2.object({
30
+ tokenUid: TokenIdentifierSchema,
31
+ name: z2.string(),
32
+ symbol: z2.string(),
33
+ isNative: z2.boolean(),
34
+ decimals: z2.number().int(),
35
+ iconUri: z2.string().nullish(),
36
+ isVetted: z2.boolean()
37
+ });
38
+ var ChainSchema = z2.object({
39
+ chainId: z2.string(),
40
+ type: ChainTypeSchema,
41
+ iconUri: z2.string(),
42
+ nativeToken: TokenSchema,
43
+ httpRpcUrl: z2.string(),
44
+ name: z2.string(),
45
+ blockExplorerUrls: z2.array(z2.string())
46
+ });
47
+ var FeeBreakdownSchema = z2.object({
48
+ serviceFee: z2.string(),
49
+ slippageCost: z2.string(),
50
+ total: z2.string(),
51
+ feeDenomination: z2.string()
52
+ });
53
+ var TransactionPlanSchema = z2.object({
54
+ type: TransactionTypeSchema,
55
+ to: z2.string(),
56
+ data: z2.string(),
57
+ value: z2.string(),
58
+ chainId: z2.string()
59
+ });
60
+ var TransactionPlanErrorSchema = z2.object({
61
+ code: z2.string(),
62
+ message: z2.string(),
63
+ details: z2.record(z2.string(), z2.string())
64
+ });
65
+ var ProviderTrackingInfoSchema = z2.object({
66
+ requestId: z2.string(),
67
+ providerName: z2.string(),
68
+ explorerUrl: z2.string()
69
+ });
70
+ var SwapEstimationSchema = z2.object({
71
+ effectivePrice: z2.string(),
72
+ timeEstimate: z2.string(),
73
+ expiration: z2.string()
74
+ });
75
+ var ProviderTrackingStatusSchema = z2.object({
76
+ requestId: z2.string(),
77
+ transactionId: z2.string(),
78
+ providerName: z2.string(),
79
+ explorerUrl: z2.string(),
80
+ status: z2.string()
81
+ });
82
+
83
+ // src/core/schemas/lending.ts
84
+ import { z as z3 } from "zod";
85
+ var BorrowTokensRequestSchema = z3.object({
86
+ borrowToken: TokenSchema,
87
+ amount: z3.bigint(),
88
+ walletAddress: z3.string()
89
+ });
90
+ var BorrowTokensResponseSchema = z3.object({
91
+ currentBorrowApy: z3.string(),
92
+ liquidationThreshold: z3.string(),
93
+ feeBreakdown: FeeBreakdownSchema.optional(),
94
+ transactions: z3.array(TransactionPlanSchema)
95
+ });
96
+ var RepayTokensRequestSchema = z3.object({
97
+ repayToken: TokenSchema,
98
+ amount: z3.bigint(),
99
+ walletAddress: z3.string()
100
+ });
101
+ var RepayTokensResponseSchema = z3.object({
102
+ feeBreakdown: FeeBreakdownSchema.optional(),
103
+ transactions: z3.array(TransactionPlanSchema)
104
+ });
105
+ var SupplyTokensRequestSchema = z3.object({
106
+ supplyToken: TokenSchema,
107
+ amount: z3.bigint(),
108
+ walletAddress: z3.string()
109
+ });
110
+ var SupplyTokensResponseSchema = z3.object({
111
+ feeBreakdown: FeeBreakdownSchema.optional(),
112
+ transactions: z3.array(TransactionPlanSchema)
113
+ });
114
+ var WithdrawTokensRequestSchema = z3.object({
115
+ tokenToWithdraw: TokenSchema,
116
+ amount: z3.bigint(),
117
+ walletAddress: z3.string()
118
+ });
119
+ var WithdrawTokensResponseSchema = z3.object({
120
+ feeBreakdown: FeeBreakdownSchema.optional(),
121
+ transactions: z3.array(TransactionPlanSchema)
122
+ });
123
+ var GetWalletLendingPositionsRequestSchema = z3.object({
124
+ walletAddress: z3.string()
125
+ });
126
+ var LendTokenDetailSchema = z3.object({
127
+ tokenUid: TokenIdentifierSchema,
128
+ underlyingBalance: z3.string(),
129
+ underlyingBalanceUsd: z3.string(),
130
+ variableBorrows: z3.string(),
131
+ variableBorrowsUsd: z3.string(),
132
+ totalBorrows: z3.string(),
133
+ totalBorrowsUsd: z3.string()
134
+ });
135
+ var GetWalletLendingPositionsResponseSchema = z3.object({
136
+ userReserves: z3.array(LendTokenDetailSchema),
137
+ totalLiquidityUsd: z3.string(),
138
+ totalCollateralUsd: z3.string(),
139
+ totalBorrowsUsd: z3.string(),
140
+ netWorthUsd: z3.string(),
141
+ availableBorrowsUsd: z3.string(),
142
+ currentLoanToValue: z3.string(),
143
+ currentLiquidationThreshold: z3.string(),
144
+ healthFactor: z3.string()
145
+ });
146
+
147
+ // src/core/schemas/liquidity.ts
148
+ import { z as z4 } from "zod";
149
+ var LimitedLiquidityProvisionRangeSchema = z4.object({
150
+ minPrice: z4.string(),
151
+ maxPrice: z4.string()
152
+ });
153
+ var LiquidityProvisionRangeSchema = z4.discriminatedUnion("type", [
154
+ z4.object({
155
+ type: z4.literal("full")
156
+ }),
157
+ z4.object({
158
+ type: z4.literal("limited"),
159
+ minPrice: z4.string(),
160
+ maxPrice: z4.string()
161
+ })
162
+ ]);
163
+ var LiquidityPositionRangeSchema = z4.object({
164
+ fromPrice: z4.string(),
165
+ toPrice: z4.string()
166
+ });
167
+ var LiquiditySuppliedTokenSchema = z4.object({
168
+ tokenUid: TokenIdentifierSchema,
169
+ suppliedAmount: z4.string(),
170
+ owedTokens: z4.string()
171
+ });
172
+ var LiquidityPositionSchema = z4.object({
173
+ poolIdentifier: TokenIdentifierSchema,
174
+ operator: z4.string(),
175
+ suppliedTokens: z4.array(LiquiditySuppliedTokenSchema),
176
+ price: z4.string(),
177
+ providerId: z4.string(),
178
+ positionRange: LiquidityPositionRangeSchema.optional()
179
+ });
180
+ var LiquidityPoolTokens = z4.object({
181
+ tokenUid: TokenIdentifierSchema
182
+ });
183
+ var LiquidityPoolSchema = z4.object({
184
+ identifier: TokenIdentifierSchema,
185
+ tokens: z4.array(LiquidityPoolTokens),
186
+ price: z4.string(),
187
+ providerId: z4.string()
188
+ });
189
+ var LiquidityPayTokensSchema = z4.object({
190
+ token: TokenSchema,
191
+ supplyAmount: z4.bigint()
192
+ });
193
+ var SupplyLiquidityRequestSchema = z4.object({
194
+ walletAddress: z4.string(),
195
+ poolToken: TokenSchema,
196
+ payTokens: z4.array(LiquidityPayTokensSchema),
197
+ range: LiquidityProvisionRangeSchema.optional()
198
+ });
199
+ var SupplyLiquidityResponseSchema = z4.object({
200
+ transactions: z4.array(TransactionPlanSchema),
201
+ poolIdentifier: TokenIdentifierSchema
202
+ });
203
+ var WithdrawLiquidityRequestSchema = z4.object({
204
+ poolToken: TokenSchema,
205
+ walletAddress: z4.string()
206
+ });
207
+ var WithdrawLiquidityResponseSchema = z4.object({
208
+ transactions: z4.array(TransactionPlanSchema),
209
+ chainId: z4.string()
210
+ });
211
+ var GetWalletLiquidityPositionsRequestSchema = z4.object({
212
+ walletAddress: z4.string()
213
+ });
214
+ var GetWalletLiquidityPositionsResponseSchema = z4.object({
215
+ positions: z4.array(LiquidityPositionSchema)
216
+ });
217
+ var GetLiquidityPoolsResponseSchema = z4.object({
218
+ liquidityPools: z4.array(LiquidityPoolSchema)
219
+ });
220
+
221
+ // src/core/schemas/perpetuals.ts
222
+ import { DecreasePositionSwapType, OrderType } from "@gmx-io/sdk/types/orders";
223
+ import { z as z5 } from "zod";
224
+ var DecreasePositionSwapTypeSchema = z5.nativeEnum(DecreasePositionSwapType);
225
+ var PositionSideSchema = z5.union([z5.literal("long"), z5.literal("short")]);
226
+ var PositionSchema = z5.object({
227
+ chainId: z5.string(),
228
+ key: z5.string(),
229
+ contractKey: z5.string(),
230
+ account: z5.string(),
231
+ marketAddress: z5.string(),
232
+ collateralTokenAddress: z5.string(),
233
+ sizeInUsd: z5.string(),
234
+ sizeInTokens: z5.string(),
235
+ collateralAmount: z5.string(),
236
+ pendingBorrowingFeesUsd: z5.string(),
237
+ increasedAtTime: z5.string(),
238
+ decreasedAtTime: z5.string(),
239
+ positionSide: PositionSideSchema,
240
+ isLong: z5.boolean(),
241
+ fundingFeeAmount: z5.string(),
242
+ claimableLongTokenAmount: z5.string(),
243
+ claimableShortTokenAmount: z5.string(),
244
+ isOpening: z5.boolean().optional(),
245
+ pnl: z5.string(),
246
+ positionFeeAmount: z5.string(),
247
+ traderDiscountAmount: z5.string(),
248
+ uiFeeAmount: z5.string(),
249
+ data: z5.string().optional()
250
+ });
251
+ var PositionsDataSchema = z5.array(PositionSchema);
252
+ var OrderSchema = z5.object({
253
+ chainId: z5.string(),
254
+ key: z5.string(),
255
+ account: z5.string(),
256
+ callbackContract: z5.string(),
257
+ initialCollateralTokenAddress: z5.string(),
258
+ marketAddress: z5.string(),
259
+ decreasePositionSwapType: DecreasePositionSwapTypeSchema,
260
+ receiver: z5.string(),
261
+ swapPath: z5.array(z5.string()),
262
+ contractAcceptablePrice: z5.string(),
263
+ contractTriggerPrice: z5.string(),
264
+ callbackGasLimit: z5.string(),
265
+ executionFee: z5.string(),
266
+ initialCollateralDeltaAmount: z5.string(),
267
+ minOutputAmount: z5.string(),
268
+ sizeDeltaUsd: z5.string(),
269
+ updatedAtTime: z5.string(),
270
+ isFrozen: z5.boolean(),
271
+ positionSide: PositionSideSchema,
272
+ orderType: z5.nativeEnum(OrderType),
273
+ shouldUnwrapNativeToken: z5.boolean(),
274
+ autoCancel: z5.boolean(),
275
+ data: z5.string().optional(),
276
+ uiFeeReceiver: z5.string(),
277
+ validFromTime: z5.string(),
278
+ title: z5.string().optional()
279
+ });
280
+ var OrdersDataSchema = z5.array(OrderSchema);
281
+ var CreatePerpetualsPositionRequestSchema = z5.object({
282
+ amount: z5.bigint(),
283
+ walletAddress: z5.string(),
284
+ chainId: z5.string(),
285
+ marketAddress: z5.string(),
286
+ payTokenAddress: z5.string(),
287
+ collateralTokenAddress: z5.string(),
288
+ referralCode: z5.string().optional(),
289
+ limitPrice: z5.string().optional(),
290
+ leverage: z5.string()
291
+ });
292
+ var CreatePerpetualsPositionResponseSchema = z5.object({
293
+ transactions: z5.array(TransactionPlanSchema)
294
+ });
295
+ var GetPerpetualsMarketsPositionsRequestSchema = z5.object({
296
+ walletAddress: z5.string().describe("User's wallet address")
297
+ });
298
+ var GetPerpetualsMarketsPositionsResponseSchema = z5.object({
299
+ positions: PositionsDataSchema
300
+ });
301
+ var GetPerpetualsMarketsOrdersRequestSchema = z5.object({
302
+ walletAddress: z5.string().describe("User's wallet address")
303
+ });
304
+ var GetPerpetualsMarketsOrdersResponseSchema = z5.object({
305
+ orders: OrdersDataSchema
306
+ });
307
+ var ClosePerpetualsOrdersRequestSchema = z5.object({
308
+ walletAddress: z5.string().describe("User's wallet address"),
309
+ key: z5.string()
310
+ });
311
+ var ClosePerpetualsOrdersResponseSchema = z5.object({
312
+ transactions: z5.array(TransactionPlanSchema)
313
+ });
314
+ var GetPerpetualsMarketsRequestSchema = z5.object({
315
+ chainIds: z5.array(z5.string())
316
+ });
317
+ var PerpetualMarketSchema = z5.object({
318
+ marketToken: TokenIdentifierSchema,
319
+ indexToken: TokenIdentifierSchema,
320
+ longToken: TokenIdentifierSchema,
321
+ shortToken: TokenIdentifierSchema,
322
+ longFundingFee: z5.string(),
323
+ shortFundingFee: z5.string(),
324
+ longBorrowingFee: z5.string(),
325
+ shortBorrowingFee: z5.string(),
326
+ chainId: z5.string(),
327
+ name: z5.string()
328
+ });
329
+ var GetPerpetualsMarketsResponseSchema = z5.object({
330
+ markets: z5.array(PerpetualMarketSchema)
331
+ });
332
+
333
+ // src/core/schemas/swap.ts
334
+ import { z as z6 } from "zod";
335
+ var SwapTokensRequestSchema = z6.object({
336
+ fromToken: TokenSchema,
337
+ toToken: TokenSchema,
338
+ amount: z6.bigint(),
339
+ limitPrice: z6.string().optional(),
340
+ slippageTolerance: z6.string().optional(),
341
+ expiration: z6.string().optional(),
342
+ recipient: z6.string()
343
+ });
344
+ var SwapTokensResponseSchema = z6.object({
345
+ fromToken: TokenSchema,
346
+ toToken: TokenSchema,
347
+ exactFromAmount: z6.string(),
348
+ displayFromAmount: z6.string(),
349
+ exactToAmount: z6.string(),
350
+ displayToAmount: z6.string(),
351
+ transactions: z6.array(TransactionPlanSchema),
352
+ feeBreakdown: FeeBreakdownSchema.optional(),
353
+ estimation: SwapEstimationSchema.optional(),
354
+ providerTracking: ProviderTrackingInfoSchema.optional()
355
+ });
356
+
357
+ // src/aave-lending-plugin/chain.ts
358
+ import { ethers } from "ethers";
359
+ var Chain = class {
360
+ constructor(id, rpcUrl, wrappedNativeTokenAddress) {
361
+ this.id = id;
362
+ this.rpcUrl = rpcUrl;
363
+ this.wrappedNativeTokenAddress = wrappedNativeTokenAddress;
364
+ }
365
+ /**
366
+ * Create and return an ethers.js JsonRpcProvider configured with this chain's RPC URL.
367
+ *
368
+ * This method constructs a new ethers.providers.JsonRpcProvider each time it is called.
369
+ * Consumers may cache the provider if they intend to reuse it to avoid allocating multiple instances.
370
+ *
371
+ * @returns An instance of ethers.providers.JsonRpcProvider configured with the chain's rpcUrl.
372
+ */
373
+ getProvider() {
374
+ return new ethers.providers.JsonRpcProvider(this.rpcUrl);
375
+ }
376
+ };
377
+
378
+ // src/aave-lending-plugin/dataProvider.ts
379
+ import {
380
+ LegacyUiPoolDataProvider,
381
+ UiPoolDataProvider
382
+ } from "@aave/contract-helpers";
383
+ var UI_POOL_DATA_PROVIDER_INTERFACE_PER_CHAIN = {
384
+ 11155111: LegacyUiPoolDataProvider,
385
+ 42161: UiPoolDataProvider,
386
+ 1: UiPoolDataProvider
387
+ };
388
+ var getUiPoolDataProviderImpl = (chainId) => {
389
+ const res = UI_POOL_DATA_PROVIDER_INTERFACE_PER_CHAIN[chainId];
390
+ if (!res) {
391
+ throw new Error(
392
+ "UI_POOL_DATA_PROVIDER_INTERFACE_PER_CHAIN does not contain this chain ID. Edit providers/aave/dataProvider.ts."
393
+ );
394
+ }
395
+ return res;
396
+ };
397
+
398
+ // src/aave-lending-plugin/market.ts
399
+ import * as markets from "@bgd-labs/aave-address-book";
400
+ var marketMap = {
401
+ 1: "AaveV3Ethereum",
402
+ 11155111: "AaveV3Sepolia",
403
+ 42161: "AaveV3Arbitrum",
404
+ 421614: "AaveV3ArbitrumSepolia",
405
+ 8453: "AaveV3Base",
406
+ 137: "AaveV3Polygon",
407
+ 10: "AaveV3Optimism"
408
+ };
409
+ var getMarket = (chainId) => {
410
+ const marketKey = marketMap[chainId];
411
+ if (!marketKey) {
412
+ throw new Error(
413
+ `AAVE: no market found for chain ID ${chainId}: modify providers/aave/market.ts`
414
+ );
415
+ }
416
+ const market = markets[marketKey];
417
+ if (!market) {
418
+ throw new Error(`No such market: ${marketKey}`);
419
+ }
420
+ return market;
421
+ };
422
+
423
+ // src/aave-lending-plugin/populateTransaction.ts
424
+ import { ethers as ethers2 } from "ethers";
425
+
426
+ // src/aave-lending-plugin/errors.ts
427
+ var AaveError = class extends Error {
428
+ description;
429
+ message;
430
+ constructor(code, name, description) {
431
+ const message = name + ` (${code}): ` + description;
432
+ super(message);
433
+ this.name = "AaveError";
434
+ this.description = description;
435
+ this.message = message;
436
+ Object.setPrototypeOf(this, new.target.prototype);
437
+ }
438
+ };
439
+ var AAVE_ERROR_CODES = {
440
+ "1": {
441
+ name: "CALLER_NOT_POOL_ADMIN",
442
+ description: "The caller of the function is not a pool admin"
443
+ },
444
+ "2": {
445
+ name: "CALLER_NOT_EMERGENCY_ADMIN",
446
+ description: "The caller of the function is not an emergency admin"
447
+ },
448
+ "3": {
449
+ name: "CALLER_NOT_POOL_OR_EMERGENCY_ADMIN",
450
+ description: "The caller of the function is not a pool or emergency admin"
451
+ },
452
+ "4": {
453
+ name: "CALLER_NOT_RISK_OR_POOL_ADMIN",
454
+ description: "The caller of the function is not a risk or pool admin"
455
+ },
456
+ "5": {
457
+ name: "CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN",
458
+ description: "The caller of the function is not an asset listing or pool admin"
459
+ },
460
+ "6": {
461
+ name: "CALLER_NOT_BRIDGE",
462
+ description: "The caller of the function is not a bridge"
463
+ },
464
+ "7": {
465
+ name: "ADDRESSES_PROVIDER_NOT_REGISTERED",
466
+ description: "Pool addresses provider is not registered"
467
+ },
468
+ "8": {
469
+ name: "INVALID_ADDRESSES_PROVIDER_ID",
470
+ description: "Invalid id for the pool addresses provider"
471
+ },
472
+ "9": { name: "NOT_CONTRACT", description: "Address is not a contract" },
473
+ "10": {
474
+ name: "CALLER_NOT_POOL_CONFIGURATOR",
475
+ description: "The caller of the function is not the pool configurator"
476
+ },
477
+ "11": {
478
+ name: "CALLER_NOT_ATOKEN",
479
+ description: "The caller of the function is not an AToken"
480
+ },
481
+ "12": {
482
+ name: "INVALID_ADDRESSES_PROVIDER",
483
+ description: "The address of the pool addresses provider is invalid"
484
+ },
485
+ "13": {
486
+ name: "INVALID_FLASHLOAN_EXECUTOR_RETURN",
487
+ description: "Invalid return value of the flashloan executor function"
488
+ },
489
+ "14": {
490
+ name: "RESERVE_ALREADY_ADDED",
491
+ description: "Reserve has already been added to reserve list"
492
+ },
493
+ "15": {
494
+ name: "NO_MORE_RESERVES_ALLOWED",
495
+ description: "Maximum amount of reserves in the pool reached"
496
+ },
497
+ "16": {
498
+ name: "EMODE_CATEGORY_RESERVED",
499
+ description: "Zero eMode category is reserved for volatile heterogeneous assets"
500
+ },
501
+ "17": {
502
+ name: "INVALID_EMODE_CATEGORY_ASSIGNMENT",
503
+ description: "Invalid eMode category assignment to asset"
504
+ },
505
+ "18": {
506
+ name: "RESERVE_LIQUIDITY_NOT_ZERO",
507
+ description: "The liquidity of the reserve needs to be 0"
508
+ },
509
+ "19": {
510
+ name: "FLASHLOAN_PREMIUM_INVALID",
511
+ description: "Invalid flashloan premium"
512
+ },
513
+ "20": {
514
+ name: "INVALID_RESERVE_PARAMS",
515
+ description: "Invalid risk parameters for the reserve"
516
+ },
517
+ "21": {
518
+ name: "INVALID_EMODE_CATEGORY_PARAMS",
519
+ description: "Invalid risk parameters for the eMode category"
520
+ },
521
+ "22": {
522
+ name: "BRIDGE_PROTOCOL_FEE_INVALID",
523
+ description: "Invalid bridge protocol fee"
524
+ },
525
+ "23": {
526
+ name: "CALLER_MUST_BE_POOL",
527
+ description: "The caller of this function must be a pool"
528
+ },
529
+ "24": { name: "INVALID_MINT_AMOUNT", description: "Invalid amount to mint" },
530
+ "25": { name: "INVALID_BURN_AMOUNT", description: "Invalid amount to burn" },
531
+ "26": {
532
+ name: "INVALID_AMOUNT",
533
+ description: "Amount must be greater than 0"
534
+ },
535
+ "27": {
536
+ name: "RESERVE_INACTIVE",
537
+ description: "Action requires an active reserve"
538
+ },
539
+ "28": {
540
+ name: "RESERVE_FROZEN",
541
+ description: "Action cannot be performed because the reserve is frozen"
542
+ },
543
+ "29": {
544
+ name: "RESERVE_PAUSED",
545
+ description: "Action cannot be performed because the reserve is paused"
546
+ },
547
+ "30": {
548
+ name: "BORROWING_NOT_ENABLED",
549
+ description: "Borrowing is not enabled"
550
+ },
551
+ "32": {
552
+ name: "NOT_ENOUGH_AVAILABLE_USER_BALANCE",
553
+ description: "User cannot withdraw more than the available balance"
554
+ },
555
+ "33": {
556
+ name: "INVALID_INTEREST_RATE_MODE_SELECTED",
557
+ description: "Invalid interest rate mode selected"
558
+ },
559
+ "34": {
560
+ name: "COLLATERAL_BALANCE_IS_ZERO",
561
+ description: "The collateral balance is 0"
562
+ },
563
+ "35": {
564
+ name: "HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD",
565
+ description: "Health factor is lesser than the liquidation threshold"
566
+ },
567
+ "36": {
568
+ name: "COLLATERAL_CANNOT_COVER_NEW_BORROW",
569
+ description: "There is not enough collateral to cover a new borrow"
570
+ },
571
+ "37": {
572
+ name: "COLLATERAL_SAME_AS_BORROWING_CURRENCY",
573
+ description: "Collateral is (mostly) the same currency that is being borrowed"
574
+ },
575
+ "39": {
576
+ name: "NO_DEBT_OF_SELECTED_TYPE",
577
+ description: "For repayment of a specific type of debt, the user needs to have debt that type"
578
+ },
579
+ "40": {
580
+ name: "NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF",
581
+ description: "To repay on behalf of a user an explicit amount to repay is needed"
582
+ },
583
+ "42": {
584
+ name: "NO_OUTSTANDING_VARIABLE_DEBT",
585
+ description: "User does not have outstanding variable rate debt on this reserve"
586
+ },
587
+ "43": {
588
+ name: "UNDERLYING_BALANCE_ZERO",
589
+ description: "The underlying balance needs to be greater than 0"
590
+ },
591
+ "44": {
592
+ name: "INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET",
593
+ description: "Interest rate rebalance conditions were not met"
594
+ },
595
+ "45": {
596
+ name: "HEALTH_FACTOR_NOT_BELOW_THRESHOLD",
597
+ description: "Health factor is not below the threshold"
598
+ },
599
+ "46": {
600
+ name: "COLLATERAL_CANNOT_BE_LIQUIDATED",
601
+ description: "The collateral chosen cannot be liquidated"
602
+ },
603
+ "47": {
604
+ name: "SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER",
605
+ description: "User did not borrow the specified currency"
606
+ },
607
+ "49": {
608
+ name: "INCONSISTENT_FLASHLOAN_PARAMS",
609
+ description: "Inconsistent flashloan parameters"
610
+ },
611
+ "50": { name: "BORROW_CAP_EXCEEDED", description: "Borrow cap is exceeded" },
612
+ "51": { name: "SUPPLY_CAP_EXCEEDED", description: "Supply cap is exceeded" },
613
+ "52": {
614
+ name: "UNBACKED_MINT_CAP_EXCEEDED",
615
+ description: "Unbacked mint cap is exceeded"
616
+ },
617
+ "53": {
618
+ name: "DEBT_CEILING_EXCEEDED",
619
+ description: "Debt ceiling is exceeded"
620
+ },
621
+ "54": {
622
+ name: "UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO",
623
+ description: "Claimable rights over underlying not zero (aToken supply or accruedToTreasury)"
624
+ },
625
+ "56": {
626
+ name: "VARIABLE_DEBT_SUPPLY_NOT_ZERO",
627
+ description: "Variable debt supply is not zero"
628
+ },
629
+ "57": { name: "LTV_VALIDATION_FAILED", description: "Ltv validation failed" },
630
+ "58": {
631
+ name: "INCONSISTENT_EMODE_CATEGORY",
632
+ description: "Inconsistent eMode category"
633
+ },
634
+ "59": {
635
+ name: "PRICE_ORACLE_SENTINEL_CHECK_FAILED",
636
+ description: "Price oracle sentinel validation failed"
637
+ },
638
+ "60": {
639
+ name: "ASSET_NOT_BORROWABLE_IN_ISOLATION",
640
+ description: "Asset is not borrowable in isolation mode"
641
+ },
642
+ "61": {
643
+ name: "RESERVE_ALREADY_INITIALIZED",
644
+ description: "Reserve has already been initialized"
645
+ },
646
+ "62": {
647
+ name: "USER_IN_ISOLATION_MODE_OR_LTV_ZERO",
648
+ description: "User is in isolation mode or ltv is zero"
649
+ },
650
+ "63": {
651
+ name: "INVALID_LTV",
652
+ description: "Invalid ltv parameter for the reserve"
653
+ },
654
+ "64": {
655
+ name: "INVALID_LIQ_THRESHOLD",
656
+ description: "Invalid liquidity threshold parameter for the reserve"
657
+ },
658
+ "65": {
659
+ name: "INVALID_LIQ_BONUS",
660
+ description: "Invalid liquidity bonus parameter for the reserve"
661
+ },
662
+ "66": {
663
+ name: "INVALID_DECIMALS",
664
+ description: "Invalid decimals parameter of the underlying asset of the reserve"
665
+ },
666
+ "67": {
667
+ name: "INVALID_RESERVE_FACTOR",
668
+ description: "Invalid reserve factor parameter for the reserve"
669
+ },
670
+ "68": {
671
+ name: "INVALID_BORROW_CAP",
672
+ description: "Invalid borrow cap for the reserve"
673
+ },
674
+ "69": {
675
+ name: "INVALID_SUPPLY_CAP",
676
+ description: "Invalid supply cap for the reserve"
677
+ },
678
+ "70": {
679
+ name: "INVALID_LIQUIDATION_PROTOCOL_FEE",
680
+ description: "Invalid liquidation protocol fee for the reserve"
681
+ },
682
+ "71": {
683
+ name: "INVALID_EMODE_CATEGORY",
684
+ description: "Invalid eMode category for the reserve"
685
+ },
686
+ "72": {
687
+ name: "INVALID_UNBACKED_MINT_CAP",
688
+ description: "Invalid unbacked mint cap for the reserve"
689
+ },
690
+ "73": {
691
+ name: "INVALID_DEBT_CEILING",
692
+ description: "Invalid debt ceiling for the reserve"
693
+ },
694
+ "74": { name: "INVALID_RESERVE_INDEX", description: "Invalid reserve index" },
695
+ "75": {
696
+ name: "ACL_ADMIN_CANNOT_BE_ZERO",
697
+ description: "ACL admin cannot be set to the zero address"
698
+ },
699
+ "76": {
700
+ name: "INCONSISTENT_PARAMS_LENGTH",
701
+ description: "Array parameters that should be equal length are not"
702
+ },
703
+ "77": {
704
+ name: "ZERO_ADDRESS_NOT_VALID",
705
+ description: "Zero address not valid"
706
+ },
707
+ "78": { name: "INVALID_EXPIRATION", description: "Invalid expiration" },
708
+ "79": { name: "INVALID_SIGNATURE", description: "Invalid signature" },
709
+ "80": {
710
+ name: "OPERATION_NOT_SUPPORTED",
711
+ description: "Operation not supported"
712
+ },
713
+ "81": {
714
+ name: "DEBT_CEILING_NOT_ZERO",
715
+ description: "Debt ceiling is not zero"
716
+ },
717
+ "82": { name: "ASSET_NOT_LISTED", description: "Asset is not listed" },
718
+ "83": {
719
+ name: "INVALID_OPTIMAL_USAGE_RATIO",
720
+ description: "Invalid optimal usage ratio"
721
+ },
722
+ "85": {
723
+ name: "UNDERLYING_CANNOT_BE_RESCUED",
724
+ description: "The underlying asset cannot be rescued"
725
+ },
726
+ "86": {
727
+ name: "ADDRESSES_PROVIDER_ALREADY_ADDED",
728
+ description: "Reserve has already been added to reserve list"
729
+ },
730
+ "87": {
731
+ name: "POOL_ADDRESSES_DO_NOT_MATCH",
732
+ description: "The token implementation pool address and the pool address provided by the initializing pool do not match"
733
+ },
734
+ "89": {
735
+ name: "SILOED_BORROWING_VIOLATION",
736
+ description: "User is trying to borrow multiple assets including a siloed one"
737
+ },
738
+ "90": {
739
+ name: "RESERVE_DEBT_NOT_ZERO",
740
+ description: "The total debt of the reserve needs to be 0"
741
+ },
742
+ "91": {
743
+ name: "FLASHLOAN_DISABLED",
744
+ description: "FlashLoaning for this asset is disabled"
745
+ },
746
+ "92": {
747
+ name: "INVALID_MAX_RATE",
748
+ description: "The expect maximum borrow rate is invalid"
749
+ },
750
+ "93": {
751
+ name: "WITHDRAW_TO_ATOKEN",
752
+ description: "Withdrawing to the aToken is not allowed"
753
+ },
754
+ "94": {
755
+ name: "SUPPLY_TO_ATOKEN",
756
+ description: "Supplying to the aToken is not allowed"
757
+ },
758
+ "95": {
759
+ name: "SLOPE_2_MUST_BE_GTE_SLOPE_1",
760
+ description: "Variable interest rate slope 2 can not be lower than slope 1"
761
+ },
762
+ "96": {
763
+ name: "CALLER_NOT_RISK_OR_POOL_OR_EMERGENCY_ADMIN",
764
+ description: "The caller of the function is not a risk, pool or emergency admin"
765
+ },
766
+ "97": {
767
+ name: "LIQUIDATION_GRACE_SENTINEL_CHECK_FAILED",
768
+ description: "Liquidation grace sentinel validation failed"
769
+ },
770
+ "98": {
771
+ name: "INVALID_GRACE_PERIOD",
772
+ description: "Grace period above a valid range"
773
+ },
774
+ "99": {
775
+ name: "INVALID_FREEZE_STATE",
776
+ description: "Reserve is already in the passed freeze state"
777
+ },
778
+ "100": {
779
+ name: "NOT_BORROWABLE_IN_EMODE",
780
+ description: "Asset not borrowable in eMode"
781
+ }
782
+ };
783
+ function getAaveError(code) {
784
+ const err = AAVE_ERROR_CODES[code];
785
+ if (err) {
786
+ return new AaveError(code, err.name, err.description);
787
+ }
788
+ return null;
789
+ }
790
+
791
+ // src/aave-lending-plugin/populateTransaction.ts
792
+ async function populateTransaction(tx) {
793
+ let txData = null;
794
+ try {
795
+ txData = await tx.tx();
796
+ } catch (unknownError) {
797
+ const reason = typeof unknownError === "object" && unknownError !== null && "reason" in unknownError && typeof unknownError.reason === "string" ? unknownError.reason : "";
798
+ const errorCode = reason.split(" ").pop();
799
+ const aaveError = getAaveError(errorCode);
800
+ if (aaveError !== null) {
801
+ throw aaveError;
802
+ } else {
803
+ throw unknownError;
804
+ }
805
+ }
806
+ if (!txData) {
807
+ throw new Error("Failed to populate transaction");
808
+ }
809
+ return {
810
+ value: ethers2.BigNumber.from(txData.value ?? 0),
811
+ from: txData.from,
812
+ to: txData.to,
813
+ data: txData.data
814
+ };
815
+ }
816
+
817
+ // src/aave-lending-plugin/userSummary.ts
818
+ import {
819
+ formatReserves,
820
+ formatUserSummary
821
+ } from "@aave/math-utils";
822
+ function formatNumeric(value) {
823
+ const num = parseFloat(value);
824
+ if (Number.isInteger(num)) return num.toString();
825
+ return parseFloat(num.toFixed(2)).toString();
826
+ }
827
+ var UserSummary = class {
828
+ reserves;
829
+ /**
830
+ * @param userReservesResponse - The response from getUserReservesHumanized.
831
+ * @param reservesResponse - The response from getReservesHumanized.
832
+ */
833
+ constructor(userReservesResponse, reservesResponse) {
834
+ const currentTimestamp = Date.now() / 1e3;
835
+ const formattedReserves = formatReserves({
836
+ reserves: reservesResponse.reservesData,
837
+ currentTimestamp,
838
+ marketReferenceCurrencyDecimals: reservesResponse.baseCurrencyData.marketReferenceCurrencyDecimals,
839
+ marketReferencePriceInUsd: reservesResponse.baseCurrencyData.marketReferenceCurrencyPriceInUsd
840
+ });
841
+ this.reserves = formatUserSummary({
842
+ currentTimestamp,
843
+ marketReferencePriceInUsd: reservesResponse.baseCurrencyData.marketReferenceCurrencyPriceInUsd,
844
+ marketReferenceCurrencyDecimals: reservesResponse.baseCurrencyData.marketReferenceCurrencyDecimals,
845
+ userReserves: userReservesResponse.userReserves,
846
+ formattedReserves,
847
+ userEmodeCategoryId: userReservesResponse.userEmodeCategoryId
848
+ });
849
+ }
850
+ toHumanReadable() {
851
+ let output = "User Positions:\n";
852
+ output += `Total Liquidity (USD): ${formatNumeric(this.reserves.totalLiquidityUSD)}
853
+ `;
854
+ output += `Total Collateral (USD): ${formatNumeric(this.reserves.totalCollateralUSD)}
855
+ `;
856
+ output += `Total Borrows (USD): ${formatNumeric(this.reserves.totalBorrowsUSD)}
857
+ `;
858
+ output += `Net Worth (USD): ${formatNumeric(this.reserves.netWorthUSD)}
859
+ `;
860
+ output += `Health Factor: ${formatNumeric(this.reserves.healthFactor)}
861
+
862
+ `;
863
+ output += "Deposits:\n";
864
+ for (const entry of this.reserves.userReservesData) {
865
+ if (parseFloat(entry.scaledATokenBalance) > 0) {
866
+ const underlying = entry.underlyingBalance;
867
+ const underlyingUSD = entry.underlyingBalanceUSD ? formatNumeric(entry.underlyingBalanceUSD) : "N/A";
868
+ output += `- ${entry.reserve.symbol}: ${underlying} (USD: ${underlyingUSD})
869
+ `;
870
+ }
871
+ }
872
+ output += "\nLoans:\n";
873
+ for (const entry of this.reserves.userReservesData) {
874
+ const borrow = entry.totalBorrows || "0";
875
+ if (parseFloat(borrow) > 0) {
876
+ const totalBorrows = entry.totalBorrows;
877
+ const totalBorrowsUSD = entry.totalBorrowsUSD ? formatNumeric(entry.totalBorrowsUSD) : "N/A";
878
+ output += `- ${entry.reserve.symbol}: ${totalBorrows} (USD: ${totalBorrowsUSD})
879
+ `;
880
+ }
881
+ }
882
+ return output;
883
+ }
884
+ };
885
+
886
+ // src/aave-lending-plugin/adapter.ts
887
+ var AAVE_ETH_PLACEHOLDER = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
888
+ var AAVEAdapter = class {
889
+ chain;
890
+ market;
891
+ constructor(params) {
892
+ this.chain = new Chain(params.chainId, params.rpcUrl);
893
+ this.market = getMarket(this.chain.id);
894
+ }
895
+ /**
896
+ * If the token is native, return AAVE's placeholder address instead of the ember address.
897
+ * @param token - The token to normalize.
898
+ * @returns The normalized token address.
899
+ */
900
+ normalizeTokenAddress(token) {
901
+ return token.isNative ? AAVE_ETH_PLACEHOLDER : token.tokenUid.address;
902
+ }
903
+ async createSupplyTransaction(params) {
904
+ const { supplyToken: token, amount, walletAddress } = params;
905
+ const txs = await this.supply(
906
+ this.normalizeTokenAddress(token),
907
+ amount.toString(),
908
+ walletAddress
909
+ );
910
+ return {
911
+ transactions: txs.map((t) => transactionPlanFromEthers(this.chain.id.toString(), t))
912
+ };
913
+ }
914
+ async createWithdrawTransaction(params) {
915
+ const { tokenToWithdraw, amount, walletAddress } = params;
916
+ const alphaTokenAddress = (await this.getReserves()).reservesData.find(
917
+ (reserve) => reserve.underlyingAsset === tokenToWithdraw.tokenUid.address
918
+ )?.aTokenAddress;
919
+ if (!alphaTokenAddress) {
920
+ throw new Error("No position can generate the token to withdraw");
921
+ }
922
+ const txs = await this.withdraw(alphaTokenAddress, amount, walletAddress, walletAddress);
923
+ return {
924
+ transactions: txs.map((t) => transactionPlanFromEthers(this.chain.id.toString(), t))
925
+ };
926
+ }
927
+ async createBorrowTransaction(params) {
928
+ const { borrowToken, amount, walletAddress } = params;
929
+ const normalizedTokenAddress = this.normalizeTokenAddress(borrowToken);
930
+ const poolData = await this.getPool(normalizedTokenAddress);
931
+ const reservesResponse = await this.getReserves();
932
+ let reserveLiquidationThreshold = null;
933
+ for (const reserve of reservesResponse.reservesData) {
934
+ const token = ethers3.utils.getAddress(reserve.underlyingAsset);
935
+ if (token === normalizedTokenAddress) {
936
+ reserveLiquidationThreshold = reserve.reserveLiquidationThreshold;
937
+ }
938
+ }
939
+ if (reserveLiquidationThreshold == null) {
940
+ throw new Error("Reserve not found in AAVE pool for a given token");
941
+ }
942
+ const txs = await this.borrow(normalizedTokenAddress, amount.toString(), walletAddress);
943
+ return {
944
+ liquidationThreshold: reserveLiquidationThreshold,
945
+ currentBorrowApy: poolData.variableBorrowRate,
946
+ transactions: txs.map((t) => transactionPlanFromEthers(this.chain.id.toString(), t))
947
+ };
948
+ }
949
+ async createRepayTransaction(params) {
950
+ const { repayToken, amount, walletAddress: from } = params;
951
+ const normalizedAsset = this.normalizeTokenAddress(repayToken);
952
+ const txs = await this.repay(normalizedAsset, amount.toString(), from, repayToken.decimals);
953
+ return {
954
+ transactions: txs.map((t) => transactionPlanFromEthers(this.chain.id.toString(), t))
955
+ };
956
+ }
957
+ async createRepayTransactionWithATokens(params) {
958
+ const { repayToken, amount, walletAddress: from } = params;
959
+ const normalizedAsset = this.normalizeTokenAddress(repayToken);
960
+ const txs = await this.repayWithATokens(
961
+ normalizedAsset,
962
+ amount.toString(),
963
+ from,
964
+ repayToken.decimals
965
+ );
966
+ return {
967
+ transactions: txs.map((t) => transactionPlanFromEthers(this.chain.id.toString(), t))
968
+ };
969
+ }
970
+ // Private Methods
971
+ getProvider() {
972
+ return this.chain.getProvider();
973
+ }
974
+ getPoolBundle() {
975
+ const provider = this.getProvider();
976
+ return new PoolBundle(provider, {
977
+ POOL: this.market.POOL,
978
+ WETH_GATEWAY: this.market.WETH_GATEWAY
979
+ });
980
+ }
981
+ getPoolDataProvider() {
982
+ const provider = this.getProvider();
983
+ const DataProviderImpl = getUiPoolDataProviderImpl(this.chain.id);
984
+ return new DataProviderImpl({
985
+ uiPoolDataProviderAddress: this.market.UI_POOL_DATA_PROVIDER,
986
+ provider,
987
+ chainId: this.chain.id
988
+ });
989
+ }
990
+ getPoolContract() {
991
+ const provider = this.getProvider();
992
+ return new Pool(provider, {
993
+ POOL: this.market.POOL,
994
+ WETH_GATEWAY: this.market.WETH_GATEWAY
995
+ });
996
+ }
997
+ async getPool(asset) {
998
+ const reservesResponse = await this.getReserves();
999
+ let targetAsset = asset;
1000
+ if (asset === AAVE_ETH_PLACEHOLDER) {
1001
+ const configuredWrappedNativeToken = this.chain.wrappedNativeTokenAddress;
1002
+ if (!configuredWrappedNativeToken) {
1003
+ throw new Error(`No wrapped native token configured for chain ${this.chain.id}`);
1004
+ }
1005
+ const wrappedNativeTokenReserve = reservesResponse.reservesData.find(
1006
+ (r) => ethers3.utils.getAddress(r.underlyingAsset) === configuredWrappedNativeToken
1007
+ );
1008
+ if (!wrappedNativeTokenReserve) {
1009
+ throw new Error(`Wrapped native token reserve not found for native token operations`);
1010
+ }
1011
+ targetAsset = wrappedNativeTokenReserve.underlyingAsset;
1012
+ }
1013
+ const reserve = reservesResponse.reservesData.find(
1014
+ (r) => ethers3.utils.getAddress(r.underlyingAsset) === ethers3.utils.getAddress(targetAsset)
1015
+ );
1016
+ if (!reserve) {
1017
+ throw new Error(`Asset ${asset} not found in reserves`);
1018
+ }
1019
+ return {
1020
+ tokenAddress: reserve.underlyingAsset,
1021
+ poolAddress: this.market.POOL,
1022
+ variableBorrowRate: reserve.variableBorrowRate,
1023
+ variableSupplyRate: reserve.liquidityRate,
1024
+ ltv: reserve.baseLTVasCollateral,
1025
+ availableLiquidity: reserve.availableLiquidity,
1026
+ reserveSize: reserve.availableLiquidity
1027
+ };
1028
+ }
1029
+ async getReserves() {
1030
+ const reserves = this.getPoolDataProvider().getReservesHumanized({
1031
+ lendingPoolAddressProvider: this.market.POOL_ADDRESSES_PROVIDER
1032
+ });
1033
+ return reserves;
1034
+ }
1035
+ async getUserSummary(params) {
1036
+ const userSummaryResponse = await this._getUserSummary(params.walletAddress);
1037
+ const {
1038
+ totalLiquidityUSD,
1039
+ totalCollateralUSD,
1040
+ totalBorrowsUSD,
1041
+ netWorthUSD,
1042
+ availableBorrowsUSD,
1043
+ currentLoanToValue,
1044
+ currentLiquidationThreshold,
1045
+ healthFactor,
1046
+ userReservesData
1047
+ } = userSummaryResponse.reserves;
1048
+ const userReservesFormatted = [];
1049
+ for (const {
1050
+ reserve,
1051
+ underlyingBalance,
1052
+ underlyingBalanceUSD,
1053
+ variableBorrows,
1054
+ variableBorrowsUSD,
1055
+ totalBorrows,
1056
+ totalBorrowsUSD: totalBorrowsUSD2
1057
+ } of userReservesData.filter((ur) => ur.underlyingBalanceUSD !== "0")) {
1058
+ userReservesFormatted.push({
1059
+ tokenUid: {
1060
+ address: reserve.underlyingAsset,
1061
+ chainId: this.chain.id.toString()
1062
+ },
1063
+ underlyingBalance,
1064
+ underlyingBalanceUsd: underlyingBalanceUSD,
1065
+ variableBorrows,
1066
+ variableBorrowsUsd: variableBorrowsUSD,
1067
+ totalBorrows,
1068
+ totalBorrowsUsd: totalBorrowsUSD2
1069
+ });
1070
+ }
1071
+ return {
1072
+ userReserves: userReservesFormatted,
1073
+ totalLiquidityUsd: totalLiquidityUSD,
1074
+ totalCollateralUsd: totalCollateralUSD,
1075
+ totalBorrowsUsd: totalBorrowsUSD,
1076
+ netWorthUsd: netWorthUSD,
1077
+ availableBorrowsUsd: availableBorrowsUSD,
1078
+ currentLoanToValue,
1079
+ currentLiquidationThreshold,
1080
+ healthFactor
1081
+ };
1082
+ }
1083
+ async _getUserSummary(userAddress) {
1084
+ const validatedUser = ethers3.utils.getAddress(userAddress);
1085
+ const poolDataProvider = this.getPoolDataProvider();
1086
+ const reservesResponse = await this.getReserves();
1087
+ const userReservesResponse = await poolDataProvider.getUserReservesHumanized({
1088
+ lendingPoolAddressProvider: this.market.POOL_ADDRESSES_PROVIDER,
1089
+ user: validatedUser
1090
+ });
1091
+ return new UserSummary(userReservesResponse, reservesResponse);
1092
+ }
1093
+ borrow(asset, amount, from) {
1094
+ ethers3.utils.getAddress(asset);
1095
+ ethers3.utils.getAddress(from);
1096
+ const bundle = this.getPoolBundle();
1097
+ const tx = bundle.borrowTxBuilder.generateTxData({
1098
+ user: from,
1099
+ reserve: asset,
1100
+ amount,
1101
+ interestRateMode: InterestRate.Variable
1102
+ });
1103
+ return Promise.resolve([tx]);
1104
+ }
1105
+ async createApproval({
1106
+ asset,
1107
+ amount_raw,
1108
+ user,
1109
+ spender
1110
+ }) {
1111
+ const bundle = this.getPoolBundle();
1112
+ let approvalTx = null;
1113
+ const isApprovedEnough = await bundle.erc20Service.isApproved({
1114
+ user,
1115
+ token: asset,
1116
+ spender,
1117
+ amount: amount_raw,
1118
+ nativeDecimals: true
1119
+ });
1120
+ if (!isApprovedEnough) {
1121
+ approvalTx = bundle.erc20Service.approveTxData({
1122
+ user,
1123
+ token: asset,
1124
+ spender,
1125
+ amount: amount_raw
1126
+ });
1127
+ }
1128
+ return approvalTx;
1129
+ }
1130
+ async supply(asset, amount, from) {
1131
+ ethers3.utils.getAddress(asset);
1132
+ ethers3.utils.getAddress(from);
1133
+ const bundle = this.getPoolBundle();
1134
+ const approvalTx = await this.createApproval({
1135
+ asset,
1136
+ amount_raw: amount,
1137
+ user: from,
1138
+ spender: bundle.poolAddress
1139
+ });
1140
+ const tx = bundle.supplyTxBuilder.generateTxData({
1141
+ user: from,
1142
+ reserve: asset,
1143
+ amount,
1144
+ onBehalfOf: from
1145
+ });
1146
+ return (approvalTx ? [approvalTx] : []).concat([tx]);
1147
+ }
1148
+ async repay(asset, amount_formatted, from, tokenDecimals) {
1149
+ ethers3.utils.getAddress(asset);
1150
+ ethers3.utils.getAddress(from);
1151
+ const bundle = this.getPoolBundle();
1152
+ const amount = utils.parseUnits(amount_formatted, tokenDecimals).toString();
1153
+ const tx = bundle.repayTxBuilder.generateTxData({
1154
+ user: from,
1155
+ reserve: asset,
1156
+ amount,
1157
+ interestRateMode: InterestRate.Variable,
1158
+ onBehalfOf: from
1159
+ });
1160
+ const approvalTx = await this.createApproval({
1161
+ asset,
1162
+ amount_raw: amount,
1163
+ user: from,
1164
+ spender: bundle.poolAddress
1165
+ });
1166
+ return (approvalTx ? [approvalTx] : []).concat([tx]);
1167
+ }
1168
+ async repayWithATokens(asset, amount_formatted, from, tokenDecimals) {
1169
+ ethers3.utils.getAddress(asset);
1170
+ ethers3.utils.getAddress(from);
1171
+ const bundle = this.getPoolBundle();
1172
+ const amount = utils.parseUnits(amount_formatted, tokenDecimals).toString();
1173
+ const tx = bundle.repayWithATokensTxBuilder.generateTxData({
1174
+ user: from,
1175
+ reserve: asset,
1176
+ amount,
1177
+ rateMode: InterestRate.Variable
1178
+ });
1179
+ return [tx];
1180
+ }
1181
+ async withdraw(asset, amount, to, from) {
1182
+ ethers3.utils.getAddress(asset);
1183
+ ethers3.utils.getAddress(to);
1184
+ ethers3.utils.getAddress(from);
1185
+ const pool = this.getPoolContract();
1186
+ const txs = await pool.withdraw({
1187
+ user: from,
1188
+ reserve: asset,
1189
+ amount: amount.toString()
1190
+ });
1191
+ if (txs.length !== 1) {
1192
+ throw new Error("AAVEInstance.withdraw: impossible happened");
1193
+ }
1194
+ return [await populateTransaction(txs[0])];
1195
+ }
1196
+ };
1197
+ var transactionPlanFromEthers = (chainId, tx) => {
1198
+ return {
1199
+ type: TransactionTypes.EVM_TX,
1200
+ to: tx.to,
1201
+ value: tx.value?.toString() || "0",
1202
+ data: tx.data,
1203
+ chainId
1204
+ };
1205
+ };
1206
+
1207
+ // src/aave-lending-plugin/index.ts
1208
+ async function getAaveEmberPlugin(params) {
1209
+ const adapter = new AAVEAdapter(params);
1210
+ return {
1211
+ id: `AAVE_CHAIN_${params.chainId}`,
1212
+ type: "lending",
1213
+ name: `AAVE lending for ${params.chainId}`,
1214
+ description: "Aave V3 lending protocol",
1215
+ website: "https://aave.com",
1216
+ x: "https://x.com/aave",
1217
+ actions: await getAaveActions(adapter),
1218
+ queries: {
1219
+ getPositions: adapter.getUserSummary.bind(adapter)
1220
+ }
1221
+ };
1222
+ }
1223
+ async function getAaveActions(adapter) {
1224
+ const reservesResponse = await adapter.getReserves();
1225
+ const underlyingAssets = reservesResponse.reservesData.map(
1226
+ (reserve) => reserve.underlyingAsset
1227
+ );
1228
+ const aTokens = reservesResponse.reservesData.map((reserve) => reserve.aTokenAddress);
1229
+ const borrowableAssets = reservesResponse.reservesData.filter((reserve) => reserve.borrowingEnabled).map((reserve) => reserve.underlyingAsset);
1230
+ return [
1231
+ // Supply any of the underlying assets to get aTokens
1232
+ {
1233
+ type: "lending-supply",
1234
+ name: `AAVE lending pools in chain ${adapter.chain.id}`,
1235
+ inputTokens: async () => Promise.resolve([
1236
+ {
1237
+ chainId: adapter.chain.id.toString(),
1238
+ tokens: underlyingAssets
1239
+ }
1240
+ ]),
1241
+ outputTokens: async () => Promise.resolve([
1242
+ {
1243
+ chainId: adapter.chain.id.toString(),
1244
+ tokens: aTokens
1245
+ }
1246
+ ]),
1247
+ callback: adapter.createSupplyTransaction.bind(adapter)
1248
+ },
1249
+ // Borrow any of the borrowable assets if you have some alpha tokens as collateral
1250
+ {
1251
+ type: "lending-borrow",
1252
+ name: `AAVE borrow in chain ${adapter.chain.id}`,
1253
+ inputTokens: async () => Promise.resolve([
1254
+ {
1255
+ chainId: adapter.chain.id.toString(),
1256
+ tokens: aTokens
1257
+ }
1258
+ ]),
1259
+ outputTokens: async () => Promise.resolve([
1260
+ {
1261
+ chainId: adapter.chain.id.toString(),
1262
+ tokens: borrowableAssets
1263
+ }
1264
+ ]),
1265
+ callback: adapter.createBorrowTransaction.bind(adapter)
1266
+ },
1267
+ // Repay your borrow with the underlying asset
1268
+ {
1269
+ type: "lending-repay",
1270
+ name: `AAVE repay in chain ${adapter.chain.id}`,
1271
+ inputTokens: async () => Promise.resolve([
1272
+ {
1273
+ chainId: adapter.chain.id.toString(),
1274
+ tokens: borrowableAssets
1275
+ }
1276
+ ]),
1277
+ // Empty output tokens as this doesn't generate any token
1278
+ outputTokens: async () => Promise.resolve([]),
1279
+ callback: adapter.createRepayTransaction.bind(adapter)
1280
+ },
1281
+ // Repay your borrow with aTokens
1282
+ {
1283
+ type: "lending-repay",
1284
+ name: `AAVE repay with aTokens in chain ${adapter.chain.id}`,
1285
+ inputTokens: async () => Promise.resolve([
1286
+ {
1287
+ chainId: adapter.chain.id.toString(),
1288
+ tokens: aTokens
1289
+ }
1290
+ ]),
1291
+ // Empty output tokens as this doesn't generate any token
1292
+ outputTokens: async () => Promise.resolve([]),
1293
+ callback: adapter.createRepayTransactionWithATokens.bind(adapter)
1294
+ },
1295
+ // Withdraw from your aTokens to get the underlying asset back
1296
+ {
1297
+ type: "lending-withdraw",
1298
+ name: `AAVE withdraw in chain ${adapter.chain.id}`,
1299
+ inputTokens: async () => Promise.resolve([
1300
+ {
1301
+ chainId: adapter.chain.id.toString(),
1302
+ tokens: aTokens
1303
+ }
1304
+ ]),
1305
+ outputTokens: async () => Promise.resolve([
1306
+ {
1307
+ chainId: adapter.chain.id.toString(),
1308
+ tokens: underlyingAssets
1309
+ }
1310
+ ]),
1311
+ callback: adapter.createWithdrawTransaction.bind(adapter)
1312
+ }
1313
+ ];
1314
+ }
1315
+ function registerAave(chainConfig, registry) {
1316
+ const supportedChains = [42161];
1317
+ if (!supportedChains.includes(chainConfig.chainId)) {
1318
+ return;
1319
+ }
1320
+ registry.registerDeferredPlugin(
1321
+ getAaveEmberPlugin({
1322
+ chainId: chainConfig.chainId,
1323
+ rpcUrl: chainConfig.rpcUrl,
1324
+ wrappedNativeToken: chainConfig.wrappedNativeToken
1325
+ })
1326
+ );
1327
+ }
1328
+
1329
+ // src/registry.ts
1330
+ var PublicEmberPluginRegistry = class {
1331
+ plugins = [];
1332
+ deferredPlugins = [];
1333
+ /**
1334
+ * Register a new Ember plugin.
1335
+ * @param plugin The plugin to register.
1336
+ */
1337
+ registerPlugin(plugin) {
1338
+ this.plugins.push(plugin);
1339
+ }
1340
+ /**
1341
+ * Register a new deferred Ember plugin.
1342
+ * @param pluginPromise The promise resolving to the plugin to register.
1343
+ */
1344
+ registerDeferredPlugin(pluginPromise) {
1345
+ this.deferredPlugins.push(pluginPromise);
1346
+ }
1347
+ /**
1348
+ * Iterator for the registered Ember plugins.
1349
+ */
1350
+ async *getPlugins() {
1351
+ yield* this.plugins;
1352
+ for (const pluginPromise of this.deferredPlugins) {
1353
+ const plugin = await pluginPromise;
1354
+ this.registerPlugin(plugin);
1355
+ yield plugin;
1356
+ }
1357
+ this.deferredPlugins = [];
1358
+ }
1359
+ get emberPlugins() {
1360
+ return this.plugins;
1361
+ }
1362
+ };
1363
+
1364
+ // src/index.ts
1365
+ function initializePublicRegistry(chainConfigs) {
1366
+ const registry = new PublicEmberPluginRegistry();
1367
+ for (const chainConfig of chainConfigs) {
1368
+ registerAave(chainConfig, registry);
1369
+ }
1370
+ return registry;
1371
+ }
1372
+ export {
1373
+ BorrowTokensRequestSchema,
1374
+ BorrowTokensResponseSchema,
1375
+ ChainSchema,
1376
+ ChainTypeSchema,
1377
+ ClosePerpetualsOrdersRequestSchema,
1378
+ ClosePerpetualsOrdersResponseSchema,
1379
+ CreatePerpetualsPositionRequestSchema,
1380
+ CreatePerpetualsPositionResponseSchema,
1381
+ DecreasePositionSwapTypeSchema,
1382
+ FeeBreakdownSchema,
1383
+ GetLiquidityPoolsResponseSchema,
1384
+ GetPerpetualsMarketsOrdersRequestSchema,
1385
+ GetPerpetualsMarketsOrdersResponseSchema,
1386
+ GetPerpetualsMarketsPositionsRequestSchema,
1387
+ GetPerpetualsMarketsPositionsResponseSchema,
1388
+ GetPerpetualsMarketsRequestSchema,
1389
+ GetPerpetualsMarketsResponseSchema,
1390
+ GetWalletLendingPositionsRequestSchema,
1391
+ GetWalletLendingPositionsResponseSchema,
1392
+ GetWalletLiquidityPositionsRequestSchema,
1393
+ GetWalletLiquidityPositionsResponseSchema,
1394
+ LendTokenDetailSchema,
1395
+ LimitedLiquidityProvisionRangeSchema,
1396
+ LiquidityPayTokensSchema,
1397
+ LiquidityPoolSchema,
1398
+ LiquidityPoolTokens,
1399
+ LiquidityPositionRangeSchema,
1400
+ LiquidityPositionSchema,
1401
+ LiquidityProvisionRangeSchema,
1402
+ LiquiditySuppliedTokenSchema,
1403
+ OrderSchema,
1404
+ OrdersDataSchema,
1405
+ PerpetualMarketSchema,
1406
+ PositionSchema,
1407
+ PositionSideSchema,
1408
+ PositionsDataSchema,
1409
+ ProviderTrackingInfoSchema,
1410
+ ProviderTrackingStatusSchema,
1411
+ PublicEmberPluginRegistry,
1412
+ RepayTokensRequestSchema,
1413
+ RepayTokensResponseSchema,
1414
+ SupplyLiquidityRequestSchema,
1415
+ SupplyLiquidityResponseSchema,
1416
+ SupplyTokensRequestSchema,
1417
+ SupplyTokensResponseSchema,
1418
+ SwapEstimationSchema,
1419
+ SwapTokensRequestSchema,
1420
+ SwapTokensResponseSchema,
1421
+ TokenIdentifierSchema,
1422
+ TokenSchema,
1423
+ TransactionPlanErrorSchema,
1424
+ TransactionPlanSchema,
1425
+ TransactionTypeSchema,
1426
+ TransactionTypes,
1427
+ WithdrawLiquidityRequestSchema,
1428
+ WithdrawLiquidityResponseSchema,
1429
+ WithdrawTokensRequestSchema,
1430
+ WithdrawTokensResponseSchema,
1431
+ initializePublicRegistry
1432
+ };
1433
+ //# sourceMappingURL=index.js.map