@aave/client 4.0.0-next.51 → 4.0.0-next.52

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.
@@ -1,9 +1,9 @@
1
1
  import { UnexpectedError, ValidationError, TimeoutError } from '@aave/core';
2
- import { HubRequest, Hub, HubsRequest, HubAssetsRequest, HubAsset, HubSummaryHistoryRequest, HubSummarySample, HubAssetInterestRateModelRequest, HubAssetInterestRateModelPoint, ChainRequest, Chain, ChainsRequest, HasProcessedKnownTransactionRequest, ExchangeRateRequest, ExchangeAmount, AssetRequest, Asset, AssetPriceHistoryRequest, AssetPriceSample, AssetSupplyHistoryRequest, AssetSupplySample, AssetBorrowHistoryRequest, AssetBorrowSample, ProtocolHistoryRequest, ProtocolHistorySample, ReserveRequest, Reserve, ReservesRequest, BorrowApyHistoryRequest, ApySample, SupplyApyHistoryRequest, UserClaimableRewardsRequest, UserClaimableReward, SpokeRequest, Spoke, SpokesRequest, SpokePositionManagersRequest, PaginatedSpokePositionManagerResult, SpokeUserPositionManagersRequest, PaginatedSpokeUserPositionManagerResult, TokenSwapQuoteRequest, TokenSwapQuoteResult, InsufficientLiquidityError, SwappableTokensRequest, Token, PrepareTokenSwapRequest, PrepareSwapOrder, InsufficientBalanceError, SupplySwapQuoteRequest, PositionSwapByIntentApprovalsRequired, BorrowSwapQuoteRequest, RepayWithSupplyQuoteRequest, WithdrawSwapQuoteRequest, PreparePositionSwapRequest, SwapStatusRequest, SwapStatus, SwapCancelled, SwapExpired, SwapFulfilled, SwapReceipt, SwapRequest, SwapTransactionRequest, PrepareSwapCancelRequest, PrepareSwapCancelResult, CancelSwapRequest, CancelSwapExecutionPlan, UserSwapsRequest, PaginatedUserSwapsResult, BorrowRequest, ExecutionPlan, SupplyRequest, RepayRequest, WithdrawRequest, RenounceSpokeUserPositionManagerRequest, TransactionRequest, UpdateUserPositionConditionsRequest, LiquidatePositionRequest, SetSpokeUserPositionManagerRequest, PreviewRequest, PreviewUserPosition, SetUserSuppliesAsCollateralRequest, ClaimRewardsRequest, ActivitiesRequest, PaginatedActivitiesResult, UserSuppliesRequest, UserSupplyItem, UserBorrowsRequest, UserBorrowItem, UserSummaryRequest, UserSummary, UserPositionsRequest, UserPosition, UserPositionRequest, UserBalancesRequest, UserBalance, UserSummaryHistoryRequest, UserSummaryHistoryItem, UserRiskPremiumBreakdownRequest, UserRiskPremiumBreakdownItem } from '@aave/graphql';
2
+ import { HubRequest, Hub, HubAssetInterestRateModelRequest, HubAssetInterestRateModelPoint, HubAssetsRequest, HubAsset, HubSummaryHistoryRequest, HubSummarySample, HubsRequest, ChainRequest, Chain, ChainsRequest, ExchangeRateRequest, ExchangeAmount, HasProcessedKnownTransactionRequest, AssetRequest, Asset, AssetBorrowHistoryRequest, AssetBorrowSample, AssetPriceHistoryRequest, AssetPriceSample, AssetSupplyHistoryRequest, AssetSupplySample, ProtocolHistoryRequest, ProtocolHistorySample, BorrowApyHistoryRequest, ApySample, ReserveRequest, Reserve, ReservesRequest, SupplyApyHistoryRequest, UserClaimableRewardsRequest, UserClaimableReward, SpokeRequest, Spoke, SpokePositionManagersRequest, PaginatedSpokePositionManagerResult, SpokeUserPositionManagersRequest, PaginatedSpokeUserPositionManagerResult, SpokesRequest, SwapCancelled, SwapExpired, SwapFulfilled, BorrowSwapQuoteRequest, PositionSwapByIntentApprovalsRequired, InsufficientLiquidityError, CancelSwapRequest, CancelSwapExecutionPlan, PreparePositionSwapRequest, PrepareSwapOrder, InsufficientBalanceError, PrepareSwapCancelRequest, PrepareSwapCancelResult, PrepareTokenSwapRequest, RepayWithSupplyQuoteRequest, SupplySwapQuoteRequest, SwapRequest, SwapTransactionRequest, SwapReceipt, SwapStatusRequest, SwapStatus, SwappableTokensRequest, Token, TokenSwapQuoteRequest, TokenSwapQuoteResult, UserSwapsRequest, PaginatedUserSwapsResult, WithdrawSwapQuoteRequest, ActivitiesRequest, PaginatedActivitiesResult, BorrowRequest, ExecutionPlan, ClaimRewardsRequest, TransactionRequest, LiquidatePositionRequest, PreviewRequest, PreviewUserPosition, RenounceSpokeUserPositionManagerRequest, RepayRequest, SetSpokeUserPositionManagerRequest, SetUserSuppliesAsCollateralRequest, SupplyRequest, UpdateUserPositionConditionsRequest, WithdrawRequest, UserBalancesRequest, UserBalance, UserBorrowsRequest, UserBorrowItem, UserPositionRequest, UserPosition, UserPositionsRequest, UserRiskPremiumBreakdownRequest, UserRiskPremiumBreakdownItem, UserSummaryRequest, UserSummary, UserSummaryHistoryRequest, UserSummaryHistoryItem, UserSuppliesRequest, UserSupplyItem, StableVaultRequest, StableVault, StableVaultAssignRateRequest, StableVaultClaimStatusRequest, StableVaultClaimStatus, StableVaultClaimSurplusRequest, StableVaultDepositRequest, StableVaultDepositExecutionPlan, StableVaultMovementsRequest, PaginatedStableVaultMovementsResult, StableVaultRateUsersRequest, PaginatedStableVaultRateUsersResult, StableVaultUnassignRateRequest, StableVaultUserPositionsRequest, StableVaultUserPosition, StableVaultWithdrawRequest, StableVaultWithdrawExecutionPlan, StableVaultWithdrawRedeemRequest, StableVaultWithdrawRedeemExecutionPlan, StableVaultsRequest } from '@aave/graphql';
3
3
  import { ResultAsync, Prettify } from '@aave/types';
4
- import { A as AaveClient } from '../AaveClient-CGksa0-v.cjs';
4
+ import { A as AaveClient } from '../AaveClient-wwfQOLJS.cjs';
5
5
  import { C as CurrencyQueryOptions, T as TimeWindowQueryOptions, R as RequestPolicyOptions, B as BatchOptions } from '../options-BX6n3sbh.cjs';
6
- import '../types-BzGr7R2Y.cjs';
6
+ import '../types-XProSTZ7.cjs';
7
7
  import '@urql/core';
8
8
 
9
9
  /**
@@ -1163,4 +1163,219 @@ declare function userSummaryHistory(client: AaveClient, request: UserSummaryHist
1163
1163
  */
1164
1164
  declare function userRiskPremiumBreakdown(client: AaveClient, request: UserRiskPremiumBreakdownRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<UserRiskPremiumBreakdownItem[], UnexpectedError>;
1165
1165
 
1166
- export { type SwapOutcome, type UserPositionQueryOptions, type UserSummaryQueryOptions, activities, asset, assetBorrowHistory, assetPriceHistory, assetSupplyHistory, borrow, borrowApyHistory, borrowSwapQuote, cancelSwap, chain, chains, claimRewards, exchangeRate, hasProcessedKnownTransaction, hub, hubAssetInterestRateModel, hubAssets, hubSummaryHistory, hubs, liquidatePosition, preparePositionSwap, prepareSwapCancel, prepareTokenSwap, preview, protocolHistory, renounceSpokeUserPositionManager, repay, repayWithSupplyQuote, reserve, reserves, setSpokeUserPositionManager, setUserSuppliesAsCollateral, spoke, spokePositionManagers, spokeUserPositionManagers, spokes, supply, supplyApyHistory, supplySwapQuote, swap, swapStatus, swappableTokens, tokenSwapQuote, updateUserPositionConditions, userBalances, userBorrows, userClaimableRewards, userPosition, userPositions, userRiskPremiumBreakdown, userSummary, userSummaryHistory, userSupplies, userSwaps, waitForSwapOutcome, withdraw, withdrawSwapQuote };
1166
+ /**
1167
+ * Fetches a stable vault by ID.
1168
+ *
1169
+ * ```ts
1170
+ * const result = await stableVault(client, {
1171
+ * id: stableVaultId('vault-123'),
1172
+ * });
1173
+ * ```
1174
+ *
1175
+ * @param client - Aave client.
1176
+ * @param request - The stable vault request parameters.
1177
+ * @param options - The query options.
1178
+ * @returns The stable vault data, or null if not found.
1179
+ */
1180
+ declare function stableVault(client: AaveClient, request: StableVaultRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVault | null, UnexpectedError>;
1181
+ /**
1182
+ * Fetches all stable vaults managed by a given admin address.
1183
+ *
1184
+ * ```ts
1185
+ * const result = await stableVaults(client, {
1186
+ * adminAddress: evmAddress('0x1234…'),
1187
+ * });
1188
+ * ```
1189
+ *
1190
+ * @param client - Aave client.
1191
+ * @param request - The stable vaults request parameters.
1192
+ * @param options - The query options.
1193
+ * @returns Array of stable vaults.
1194
+ */
1195
+ declare function stableVaults(client: AaveClient, request: StableVaultsRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVault[], UnexpectedError>;
1196
+ /**
1197
+ * Fetches paginated list of users assigned to a specific boosted rate tier.
1198
+ *
1199
+ * ```ts
1200
+ * const result = await stableVaultRateUsers(client, {
1201
+ * vaultId: stableVaultId('vault-123'),
1202
+ * rateId: boostedRateId('gold'),
1203
+ * pageSize: 10,
1204
+ * });
1205
+ * ```
1206
+ *
1207
+ * @param client - Aave client.
1208
+ * @param request - The rate users request parameters.
1209
+ * @param options - The query options.
1210
+ * @returns Paginated list of user addresses.
1211
+ */
1212
+ declare function stableVaultRateUsers(client: AaveClient, request: StableVaultRateUsersRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<PaginatedStableVaultRateUsersResult, UnexpectedError>;
1213
+ /**
1214
+ * Creates a transaction to assign users to a boosted rate tier.
1215
+ *
1216
+ * ```ts
1217
+ * const result = await stableVaultAssignRate(client, {
1218
+ * vaultId: stableVaultId('vault-123'),
1219
+ * rateId: boostedRateId('gold'),
1220
+ * users: [evmAddress('0x1234…')],
1221
+ * }).andThen(sendWith(wallet));
1222
+ * ```
1223
+ *
1224
+ * @param client - Aave client.
1225
+ * @param request - The assign rate request parameters.
1226
+ * @param options - The query options.
1227
+ * @returns The transaction data.
1228
+ */
1229
+ declare function stableVaultAssignRate(client: AaveClient, request: StableVaultAssignRateRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<TransactionRequest, UnexpectedError>;
1230
+ /**
1231
+ * Creates a transaction to remove users from a boosted rate tier.
1232
+ *
1233
+ * ```ts
1234
+ * const result = await stableVaultUnassignRate(client, {
1235
+ * vaultId: stableVaultId('vault-123'),
1236
+ * rateId: boostedRateId('gold'),
1237
+ * users: [evmAddress('0x1234…')],
1238
+ * }).andThen(sendWith(wallet));
1239
+ * ```
1240
+ *
1241
+ * @param client - Aave client.
1242
+ * @param request - The unassign rate request parameters.
1243
+ * @param options - The query options.
1244
+ * @returns The transaction data.
1245
+ */
1246
+ declare function stableVaultUnassignRate(client: AaveClient, request: StableVaultUnassignRateRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<TransactionRequest, UnexpectedError>;
1247
+ /**
1248
+ * Creates a transaction to claim accumulated surplus from a stable vault.
1249
+ *
1250
+ * ```ts
1251
+ * const result = await stableVaultClaimSurplus(client, {
1252
+ * vaultId: stableVaultId('vault-123'),
1253
+ * claims: [{ address: evmAddress('0xUSDC…'), value: bigDecimal('1000') }],
1254
+ * }).andThen(sendWith(wallet));
1255
+ * ```
1256
+ *
1257
+ * @param client - Aave client.
1258
+ * @param request - The claim surplus request parameters.
1259
+ * @param options - The query options.
1260
+ * @returns The transaction data.
1261
+ */
1262
+ declare function stableVaultClaimSurplus(client: AaveClient, request: StableVaultClaimSurplusRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<TransactionRequest, UnexpectedError>;
1263
+ /**
1264
+ * Fetches paginated cross-chain fund movements for a stable vault.
1265
+ *
1266
+ * ```ts
1267
+ * const result = await stableVaultMovements(client, {
1268
+ * vaultId: stableVaultId('vault-123'),
1269
+ * pageSize: 10,
1270
+ * });
1271
+ * ```
1272
+ *
1273
+ * @param client - Aave client.
1274
+ * @param request - The movements request parameters.
1275
+ * @param options - The query options.
1276
+ * @returns Paginated list of token movement records.
1277
+ */
1278
+ declare function stableVaultMovements(client: AaveClient, request: StableVaultMovementsRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<PaginatedStableVaultMovementsResult, UnexpectedError>;
1279
+ /**
1280
+ * Creates a transaction to deposit into a stable vault.
1281
+ *
1282
+ * ```ts
1283
+ * const result = await stableVaultDeposit(client, {
1284
+ * vault: { id: stableVaultId('vault-123') },
1285
+ * user: evmAddress('0x1234…'),
1286
+ * amount: {
1287
+ * address: evmAddress('0xUSDC…'),
1288
+ * value: { exact: bigDecimal('1000') },
1289
+ * },
1290
+ * });
1291
+ * ```
1292
+ *
1293
+ * @param client - Aave client.
1294
+ * @param request - The deposit request parameters.
1295
+ * @returns The transaction data, approval requirements, or insufficient balance error.
1296
+ */
1297
+ declare function stableVaultDeposit(client: AaveClient, request: StableVaultDepositRequest): ResultAsync<StableVaultDepositExecutionPlan, UnexpectedError>;
1298
+ /**
1299
+ * Creates a transaction to request a withdrawal from a stable vault.
1300
+ *
1301
+ * Withdrawals may be instant if sufficient liquidity exists, or deferred
1302
+ * if funds must be bridged from earning chains.
1303
+ *
1304
+ * ```ts
1305
+ * const result = await stableVaultWithdraw(client, {
1306
+ * vault: { id: stableVaultId('vault-123') },
1307
+ * user: evmAddress('0x1234…'),
1308
+ * amount: {
1309
+ * address: evmAddress('0xUSDC…'),
1310
+ * value: { exact: bigDecimal('500') },
1311
+ * },
1312
+ * });
1313
+ * ```
1314
+ *
1315
+ * @param client - Aave client.
1316
+ * @param request - The withdraw request parameters.
1317
+ * @returns The withdraw execution plan with either an instant transaction or a deferred claim.
1318
+ */
1319
+ declare function stableVaultWithdraw(client: AaveClient, request: StableVaultWithdrawRequest): ResultAsync<StableVaultWithdrawExecutionPlan, UnexpectedError>;
1320
+ /**
1321
+ * Redeems a deferred withdrawal claim once funds become available.
1322
+ *
1323
+ * ```ts
1324
+ * const result = await stableVaultWithdrawRedeem(client, {
1325
+ * claimId: stableVaultWithdrawClaimId('claim-456'),
1326
+ * }).andThen(sendWith(wallet));
1327
+ * ```
1328
+ *
1329
+ * @param client - Aave client.
1330
+ * @param request - The redeem request with the claim ID.
1331
+ * @returns The redeem execution plan.
1332
+ */
1333
+ declare function stableVaultWithdrawRedeem(client: AaveClient, request: StableVaultWithdrawRedeemRequest): ResultAsync<StableVaultWithdrawRedeemExecutionPlan, UnexpectedError>;
1334
+ /**
1335
+ * Checks the status of a deferred withdrawal claim.
1336
+ *
1337
+ * ```ts
1338
+ * const result = await stableVaultClaimStatus(client, {
1339
+ * claimId: stableVaultWithdrawClaimId('claim-456'),
1340
+ * });
1341
+ * ```
1342
+ *
1343
+ * @param client - Aave client.
1344
+ * @param request - The claim status request parameters.
1345
+ * @param options - The query options.
1346
+ * @returns The claim status (READY, PENDING, or UNKNOWN).
1347
+ */
1348
+ declare function stableVaultClaimStatus(client: AaveClient, request: StableVaultClaimStatusRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVaultClaimStatus, UnexpectedError>;
1349
+ /**
1350
+ * Fetches all stable vault positions for a given user.
1351
+ *
1352
+ * ```ts
1353
+ * const result = await stableVaultUserPositions(client, {
1354
+ * user: evmAddress('0x1234…'),
1355
+ * });
1356
+ * ```
1357
+ *
1358
+ * @param client - Aave client.
1359
+ * @param request - The user positions request parameters.
1360
+ * @param options - The query options.
1361
+ * @returns Array of stable vault positions with principal, interests, and APY.
1362
+ */
1363
+ declare function stableVaultUserPositions(client: AaveClient, request: StableVaultUserPositionsRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVaultUserPosition[], UnexpectedError>;
1364
+ /**
1365
+ * Waits for a deferred withdrawal claim to become ready for redemption.
1366
+ *
1367
+ * Polls the claim status until it reaches `READY`, then resolves.
1368
+ *
1369
+ * ```ts
1370
+ * const result = await waitForStableVaultWithdrawClaim(client, {
1371
+ * claimId: plan.claimId,
1372
+ * });
1373
+ * ```
1374
+ *
1375
+ * @param client - Aave client configured with polling settings.
1376
+ * @param request - The claim status request with the claim ID.
1377
+ * @returns Resolves when the claim is ready, or rejects with a TimeoutError.
1378
+ */
1379
+ declare function waitForStableVaultWithdrawClaim(client: AaveClient, request: StableVaultClaimStatusRequest): ResultAsync<void, TimeoutError | UnexpectedError>;
1380
+
1381
+ export { type SwapOutcome, type UserPositionQueryOptions, type UserSummaryQueryOptions, activities, asset, assetBorrowHistory, assetPriceHistory, assetSupplyHistory, borrow, borrowApyHistory, borrowSwapQuote, cancelSwap, chain, chains, claimRewards, exchangeRate, hasProcessedKnownTransaction, hub, hubAssetInterestRateModel, hubAssets, hubSummaryHistory, hubs, liquidatePosition, preparePositionSwap, prepareSwapCancel, prepareTokenSwap, preview, protocolHistory, renounceSpokeUserPositionManager, repay, repayWithSupplyQuote, reserve, reserves, setSpokeUserPositionManager, setUserSuppliesAsCollateral, spoke, spokePositionManagers, spokeUserPositionManagers, spokes, stableVault, stableVaultAssignRate, stableVaultClaimStatus, stableVaultClaimSurplus, stableVaultDeposit, stableVaultMovements, stableVaultRateUsers, stableVaultUnassignRate, stableVaultUserPositions, stableVaultWithdraw, stableVaultWithdrawRedeem, stableVaults, supply, supplyApyHistory, supplySwapQuote, swap, swapStatus, swappableTokens, tokenSwapQuote, updateUserPositionConditions, userBalances, userBorrows, userClaimableRewards, userPosition, userPositions, userRiskPremiumBreakdown, userSummary, userSummaryHistory, userSupplies, userSwaps, waitForStableVaultWithdrawClaim, waitForSwapOutcome, withdraw, withdrawSwapQuote };
@@ -1,9 +1,9 @@
1
1
  import { UnexpectedError, ValidationError, TimeoutError } from '@aave/core';
2
- import { HubRequest, Hub, HubsRequest, HubAssetsRequest, HubAsset, HubSummaryHistoryRequest, HubSummarySample, HubAssetInterestRateModelRequest, HubAssetInterestRateModelPoint, ChainRequest, Chain, ChainsRequest, HasProcessedKnownTransactionRequest, ExchangeRateRequest, ExchangeAmount, AssetRequest, Asset, AssetPriceHistoryRequest, AssetPriceSample, AssetSupplyHistoryRequest, AssetSupplySample, AssetBorrowHistoryRequest, AssetBorrowSample, ProtocolHistoryRequest, ProtocolHistorySample, ReserveRequest, Reserve, ReservesRequest, BorrowApyHistoryRequest, ApySample, SupplyApyHistoryRequest, UserClaimableRewardsRequest, UserClaimableReward, SpokeRequest, Spoke, SpokesRequest, SpokePositionManagersRequest, PaginatedSpokePositionManagerResult, SpokeUserPositionManagersRequest, PaginatedSpokeUserPositionManagerResult, TokenSwapQuoteRequest, TokenSwapQuoteResult, InsufficientLiquidityError, SwappableTokensRequest, Token, PrepareTokenSwapRequest, PrepareSwapOrder, InsufficientBalanceError, SupplySwapQuoteRequest, PositionSwapByIntentApprovalsRequired, BorrowSwapQuoteRequest, RepayWithSupplyQuoteRequest, WithdrawSwapQuoteRequest, PreparePositionSwapRequest, SwapStatusRequest, SwapStatus, SwapCancelled, SwapExpired, SwapFulfilled, SwapReceipt, SwapRequest, SwapTransactionRequest, PrepareSwapCancelRequest, PrepareSwapCancelResult, CancelSwapRequest, CancelSwapExecutionPlan, UserSwapsRequest, PaginatedUserSwapsResult, BorrowRequest, ExecutionPlan, SupplyRequest, RepayRequest, WithdrawRequest, RenounceSpokeUserPositionManagerRequest, TransactionRequest, UpdateUserPositionConditionsRequest, LiquidatePositionRequest, SetSpokeUserPositionManagerRequest, PreviewRequest, PreviewUserPosition, SetUserSuppliesAsCollateralRequest, ClaimRewardsRequest, ActivitiesRequest, PaginatedActivitiesResult, UserSuppliesRequest, UserSupplyItem, UserBorrowsRequest, UserBorrowItem, UserSummaryRequest, UserSummary, UserPositionsRequest, UserPosition, UserPositionRequest, UserBalancesRequest, UserBalance, UserSummaryHistoryRequest, UserSummaryHistoryItem, UserRiskPremiumBreakdownRequest, UserRiskPremiumBreakdownItem } from '@aave/graphql';
2
+ import { HubRequest, Hub, HubAssetInterestRateModelRequest, HubAssetInterestRateModelPoint, HubAssetsRequest, HubAsset, HubSummaryHistoryRequest, HubSummarySample, HubsRequest, ChainRequest, Chain, ChainsRequest, ExchangeRateRequest, ExchangeAmount, HasProcessedKnownTransactionRequest, AssetRequest, Asset, AssetBorrowHistoryRequest, AssetBorrowSample, AssetPriceHistoryRequest, AssetPriceSample, AssetSupplyHistoryRequest, AssetSupplySample, ProtocolHistoryRequest, ProtocolHistorySample, BorrowApyHistoryRequest, ApySample, ReserveRequest, Reserve, ReservesRequest, SupplyApyHistoryRequest, UserClaimableRewardsRequest, UserClaimableReward, SpokeRequest, Spoke, SpokePositionManagersRequest, PaginatedSpokePositionManagerResult, SpokeUserPositionManagersRequest, PaginatedSpokeUserPositionManagerResult, SpokesRequest, SwapCancelled, SwapExpired, SwapFulfilled, BorrowSwapQuoteRequest, PositionSwapByIntentApprovalsRequired, InsufficientLiquidityError, CancelSwapRequest, CancelSwapExecutionPlan, PreparePositionSwapRequest, PrepareSwapOrder, InsufficientBalanceError, PrepareSwapCancelRequest, PrepareSwapCancelResult, PrepareTokenSwapRequest, RepayWithSupplyQuoteRequest, SupplySwapQuoteRequest, SwapRequest, SwapTransactionRequest, SwapReceipt, SwapStatusRequest, SwapStatus, SwappableTokensRequest, Token, TokenSwapQuoteRequest, TokenSwapQuoteResult, UserSwapsRequest, PaginatedUserSwapsResult, WithdrawSwapQuoteRequest, ActivitiesRequest, PaginatedActivitiesResult, BorrowRequest, ExecutionPlan, ClaimRewardsRequest, TransactionRequest, LiquidatePositionRequest, PreviewRequest, PreviewUserPosition, RenounceSpokeUserPositionManagerRequest, RepayRequest, SetSpokeUserPositionManagerRequest, SetUserSuppliesAsCollateralRequest, SupplyRequest, UpdateUserPositionConditionsRequest, WithdrawRequest, UserBalancesRequest, UserBalance, UserBorrowsRequest, UserBorrowItem, UserPositionRequest, UserPosition, UserPositionsRequest, UserRiskPremiumBreakdownRequest, UserRiskPremiumBreakdownItem, UserSummaryRequest, UserSummary, UserSummaryHistoryRequest, UserSummaryHistoryItem, UserSuppliesRequest, UserSupplyItem, StableVaultRequest, StableVault, StableVaultAssignRateRequest, StableVaultClaimStatusRequest, StableVaultClaimStatus, StableVaultClaimSurplusRequest, StableVaultDepositRequest, StableVaultDepositExecutionPlan, StableVaultMovementsRequest, PaginatedStableVaultMovementsResult, StableVaultRateUsersRequest, PaginatedStableVaultRateUsersResult, StableVaultUnassignRateRequest, StableVaultUserPositionsRequest, StableVaultUserPosition, StableVaultWithdrawRequest, StableVaultWithdrawExecutionPlan, StableVaultWithdrawRedeemRequest, StableVaultWithdrawRedeemExecutionPlan, StableVaultsRequest } from '@aave/graphql';
3
3
  import { ResultAsync, Prettify } from '@aave/types';
4
- import { A as AaveClient } from '../AaveClient-DpWiYPGY.js';
4
+ import { A as AaveClient } from '../AaveClient-C7hQU3qX.js';
5
5
  import { C as CurrencyQueryOptions, T as TimeWindowQueryOptions, R as RequestPolicyOptions, B as BatchOptions } from '../options-BX6n3sbh.js';
6
- import '../types-BzGr7R2Y.js';
6
+ import '../types-XProSTZ7.js';
7
7
  import '@urql/core';
8
8
 
9
9
  /**
@@ -1163,4 +1163,219 @@ declare function userSummaryHistory(client: AaveClient, request: UserSummaryHist
1163
1163
  */
1164
1164
  declare function userRiskPremiumBreakdown(client: AaveClient, request: UserRiskPremiumBreakdownRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<UserRiskPremiumBreakdownItem[], UnexpectedError>;
1165
1165
 
1166
- export { type SwapOutcome, type UserPositionQueryOptions, type UserSummaryQueryOptions, activities, asset, assetBorrowHistory, assetPriceHistory, assetSupplyHistory, borrow, borrowApyHistory, borrowSwapQuote, cancelSwap, chain, chains, claimRewards, exchangeRate, hasProcessedKnownTransaction, hub, hubAssetInterestRateModel, hubAssets, hubSummaryHistory, hubs, liquidatePosition, preparePositionSwap, prepareSwapCancel, prepareTokenSwap, preview, protocolHistory, renounceSpokeUserPositionManager, repay, repayWithSupplyQuote, reserve, reserves, setSpokeUserPositionManager, setUserSuppliesAsCollateral, spoke, spokePositionManagers, spokeUserPositionManagers, spokes, supply, supplyApyHistory, supplySwapQuote, swap, swapStatus, swappableTokens, tokenSwapQuote, updateUserPositionConditions, userBalances, userBorrows, userClaimableRewards, userPosition, userPositions, userRiskPremiumBreakdown, userSummary, userSummaryHistory, userSupplies, userSwaps, waitForSwapOutcome, withdraw, withdrawSwapQuote };
1166
+ /**
1167
+ * Fetches a stable vault by ID.
1168
+ *
1169
+ * ```ts
1170
+ * const result = await stableVault(client, {
1171
+ * id: stableVaultId('vault-123'),
1172
+ * });
1173
+ * ```
1174
+ *
1175
+ * @param client - Aave client.
1176
+ * @param request - The stable vault request parameters.
1177
+ * @param options - The query options.
1178
+ * @returns The stable vault data, or null if not found.
1179
+ */
1180
+ declare function stableVault(client: AaveClient, request: StableVaultRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVault | null, UnexpectedError>;
1181
+ /**
1182
+ * Fetches all stable vaults managed by a given admin address.
1183
+ *
1184
+ * ```ts
1185
+ * const result = await stableVaults(client, {
1186
+ * adminAddress: evmAddress('0x1234…'),
1187
+ * });
1188
+ * ```
1189
+ *
1190
+ * @param client - Aave client.
1191
+ * @param request - The stable vaults request parameters.
1192
+ * @param options - The query options.
1193
+ * @returns Array of stable vaults.
1194
+ */
1195
+ declare function stableVaults(client: AaveClient, request: StableVaultsRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVault[], UnexpectedError>;
1196
+ /**
1197
+ * Fetches paginated list of users assigned to a specific boosted rate tier.
1198
+ *
1199
+ * ```ts
1200
+ * const result = await stableVaultRateUsers(client, {
1201
+ * vaultId: stableVaultId('vault-123'),
1202
+ * rateId: boostedRateId('gold'),
1203
+ * pageSize: 10,
1204
+ * });
1205
+ * ```
1206
+ *
1207
+ * @param client - Aave client.
1208
+ * @param request - The rate users request parameters.
1209
+ * @param options - The query options.
1210
+ * @returns Paginated list of user addresses.
1211
+ */
1212
+ declare function stableVaultRateUsers(client: AaveClient, request: StableVaultRateUsersRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<PaginatedStableVaultRateUsersResult, UnexpectedError>;
1213
+ /**
1214
+ * Creates a transaction to assign users to a boosted rate tier.
1215
+ *
1216
+ * ```ts
1217
+ * const result = await stableVaultAssignRate(client, {
1218
+ * vaultId: stableVaultId('vault-123'),
1219
+ * rateId: boostedRateId('gold'),
1220
+ * users: [evmAddress('0x1234…')],
1221
+ * }).andThen(sendWith(wallet));
1222
+ * ```
1223
+ *
1224
+ * @param client - Aave client.
1225
+ * @param request - The assign rate request parameters.
1226
+ * @param options - The query options.
1227
+ * @returns The transaction data.
1228
+ */
1229
+ declare function stableVaultAssignRate(client: AaveClient, request: StableVaultAssignRateRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<TransactionRequest, UnexpectedError>;
1230
+ /**
1231
+ * Creates a transaction to remove users from a boosted rate tier.
1232
+ *
1233
+ * ```ts
1234
+ * const result = await stableVaultUnassignRate(client, {
1235
+ * vaultId: stableVaultId('vault-123'),
1236
+ * rateId: boostedRateId('gold'),
1237
+ * users: [evmAddress('0x1234…')],
1238
+ * }).andThen(sendWith(wallet));
1239
+ * ```
1240
+ *
1241
+ * @param client - Aave client.
1242
+ * @param request - The unassign rate request parameters.
1243
+ * @param options - The query options.
1244
+ * @returns The transaction data.
1245
+ */
1246
+ declare function stableVaultUnassignRate(client: AaveClient, request: StableVaultUnassignRateRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<TransactionRequest, UnexpectedError>;
1247
+ /**
1248
+ * Creates a transaction to claim accumulated surplus from a stable vault.
1249
+ *
1250
+ * ```ts
1251
+ * const result = await stableVaultClaimSurplus(client, {
1252
+ * vaultId: stableVaultId('vault-123'),
1253
+ * claims: [{ address: evmAddress('0xUSDC…'), value: bigDecimal('1000') }],
1254
+ * }).andThen(sendWith(wallet));
1255
+ * ```
1256
+ *
1257
+ * @param client - Aave client.
1258
+ * @param request - The claim surplus request parameters.
1259
+ * @param options - The query options.
1260
+ * @returns The transaction data.
1261
+ */
1262
+ declare function stableVaultClaimSurplus(client: AaveClient, request: StableVaultClaimSurplusRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<TransactionRequest, UnexpectedError>;
1263
+ /**
1264
+ * Fetches paginated cross-chain fund movements for a stable vault.
1265
+ *
1266
+ * ```ts
1267
+ * const result = await stableVaultMovements(client, {
1268
+ * vaultId: stableVaultId('vault-123'),
1269
+ * pageSize: 10,
1270
+ * });
1271
+ * ```
1272
+ *
1273
+ * @param client - Aave client.
1274
+ * @param request - The movements request parameters.
1275
+ * @param options - The query options.
1276
+ * @returns Paginated list of token movement records.
1277
+ */
1278
+ declare function stableVaultMovements(client: AaveClient, request: StableVaultMovementsRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<PaginatedStableVaultMovementsResult, UnexpectedError>;
1279
+ /**
1280
+ * Creates a transaction to deposit into a stable vault.
1281
+ *
1282
+ * ```ts
1283
+ * const result = await stableVaultDeposit(client, {
1284
+ * vault: { id: stableVaultId('vault-123') },
1285
+ * user: evmAddress('0x1234…'),
1286
+ * amount: {
1287
+ * address: evmAddress('0xUSDC…'),
1288
+ * value: { exact: bigDecimal('1000') },
1289
+ * },
1290
+ * });
1291
+ * ```
1292
+ *
1293
+ * @param client - Aave client.
1294
+ * @param request - The deposit request parameters.
1295
+ * @returns The transaction data, approval requirements, or insufficient balance error.
1296
+ */
1297
+ declare function stableVaultDeposit(client: AaveClient, request: StableVaultDepositRequest): ResultAsync<StableVaultDepositExecutionPlan, UnexpectedError>;
1298
+ /**
1299
+ * Creates a transaction to request a withdrawal from a stable vault.
1300
+ *
1301
+ * Withdrawals may be instant if sufficient liquidity exists, or deferred
1302
+ * if funds must be bridged from earning chains.
1303
+ *
1304
+ * ```ts
1305
+ * const result = await stableVaultWithdraw(client, {
1306
+ * vault: { id: stableVaultId('vault-123') },
1307
+ * user: evmAddress('0x1234…'),
1308
+ * amount: {
1309
+ * address: evmAddress('0xUSDC…'),
1310
+ * value: { exact: bigDecimal('500') },
1311
+ * },
1312
+ * });
1313
+ * ```
1314
+ *
1315
+ * @param client - Aave client.
1316
+ * @param request - The withdraw request parameters.
1317
+ * @returns The withdraw execution plan with either an instant transaction or a deferred claim.
1318
+ */
1319
+ declare function stableVaultWithdraw(client: AaveClient, request: StableVaultWithdrawRequest): ResultAsync<StableVaultWithdrawExecutionPlan, UnexpectedError>;
1320
+ /**
1321
+ * Redeems a deferred withdrawal claim once funds become available.
1322
+ *
1323
+ * ```ts
1324
+ * const result = await stableVaultWithdrawRedeem(client, {
1325
+ * claimId: stableVaultWithdrawClaimId('claim-456'),
1326
+ * }).andThen(sendWith(wallet));
1327
+ * ```
1328
+ *
1329
+ * @param client - Aave client.
1330
+ * @param request - The redeem request with the claim ID.
1331
+ * @returns The redeem execution plan.
1332
+ */
1333
+ declare function stableVaultWithdrawRedeem(client: AaveClient, request: StableVaultWithdrawRedeemRequest): ResultAsync<StableVaultWithdrawRedeemExecutionPlan, UnexpectedError>;
1334
+ /**
1335
+ * Checks the status of a deferred withdrawal claim.
1336
+ *
1337
+ * ```ts
1338
+ * const result = await stableVaultClaimStatus(client, {
1339
+ * claimId: stableVaultWithdrawClaimId('claim-456'),
1340
+ * });
1341
+ * ```
1342
+ *
1343
+ * @param client - Aave client.
1344
+ * @param request - The claim status request parameters.
1345
+ * @param options - The query options.
1346
+ * @returns The claim status (READY, PENDING, or UNKNOWN).
1347
+ */
1348
+ declare function stableVaultClaimStatus(client: AaveClient, request: StableVaultClaimStatusRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVaultClaimStatus, UnexpectedError>;
1349
+ /**
1350
+ * Fetches all stable vault positions for a given user.
1351
+ *
1352
+ * ```ts
1353
+ * const result = await stableVaultUserPositions(client, {
1354
+ * user: evmAddress('0x1234…'),
1355
+ * });
1356
+ * ```
1357
+ *
1358
+ * @param client - Aave client.
1359
+ * @param request - The user positions request parameters.
1360
+ * @param options - The query options.
1361
+ * @returns Array of stable vault positions with principal, interests, and APY.
1362
+ */
1363
+ declare function stableVaultUserPositions(client: AaveClient, request: StableVaultUserPositionsRequest, { requestPolicy, }?: RequestPolicyOptions): ResultAsync<StableVaultUserPosition[], UnexpectedError>;
1364
+ /**
1365
+ * Waits for a deferred withdrawal claim to become ready for redemption.
1366
+ *
1367
+ * Polls the claim status until it reaches `READY`, then resolves.
1368
+ *
1369
+ * ```ts
1370
+ * const result = await waitForStableVaultWithdrawClaim(client, {
1371
+ * claimId: plan.claimId,
1372
+ * });
1373
+ * ```
1374
+ *
1375
+ * @param client - Aave client configured with polling settings.
1376
+ * @param request - The claim status request with the claim ID.
1377
+ * @returns Resolves when the claim is ready, or rejects with a TimeoutError.
1378
+ */
1379
+ declare function waitForStableVaultWithdrawClaim(client: AaveClient, request: StableVaultClaimStatusRequest): ResultAsync<void, TimeoutError | UnexpectedError>;
1380
+
1381
+ export { type SwapOutcome, type UserPositionQueryOptions, type UserSummaryQueryOptions, activities, asset, assetBorrowHistory, assetPriceHistory, assetSupplyHistory, borrow, borrowApyHistory, borrowSwapQuote, cancelSwap, chain, chains, claimRewards, exchangeRate, hasProcessedKnownTransaction, hub, hubAssetInterestRateModel, hubAssets, hubSummaryHistory, hubs, liquidatePosition, preparePositionSwap, prepareSwapCancel, prepareTokenSwap, preview, protocolHistory, renounceSpokeUserPositionManager, repay, repayWithSupplyQuote, reserve, reserves, setSpokeUserPositionManager, setUserSuppliesAsCollateral, spoke, spokePositionManagers, spokeUserPositionManagers, spokes, stableVault, stableVaultAssignRate, stableVaultClaimStatus, stableVaultClaimSurplus, stableVaultDeposit, stableVaultMovements, stableVaultRateUsers, stableVaultUnassignRate, stableVaultUserPositions, stableVaultWithdraw, stableVaultWithdrawRedeem, stableVaults, supply, supplyApyHistory, supplySwapQuote, swap, swapStatus, swappableTokens, tokenSwapQuote, updateUserPositionConditions, userBalances, userBorrows, userClaimableRewards, userPosition, userPositions, userRiskPremiumBreakdown, userSummary, userSummaryHistory, userSupplies, userSwaps, waitForStableVaultWithdrawClaim, waitForSwapOutcome, withdraw, withdrawSwapQuote };
@@ -1,2 +1,2 @@
1
- export{X as activities,k as asset,n as assetBorrowHistory,l as assetPriceHistory,m as assetSupplyHistory,M as borrow,r as borrowApyHistory,C as borrowSwapQuote,K as cancelSwap,g as chain,h as chains,W as claimRewards,j as exchangeRate,i as hasProcessedKnownTransaction,b as hub,f as hubAssetInterestRateModel,d as hubAssets,e as hubSummaryHistory,c as hubs,S as liquidatePosition,F as preparePositionSwap,J as prepareSwapCancel,A as prepareTokenSwap,U as preview,o as protocolHistory,Q as renounceSpokeUserPositionManager,O as repay,D as repayWithSupplyQuote,p as reserve,q as reserves,T as setSpokeUserPositionManager,V as setUserSuppliesAsCollateral,u as spoke,w as spokePositionManagers,x as spokeUserPositionManagers,v as spokes,N as supply,s as supplyApyHistory,B as supplySwapQuote,I as swap,G as swapStatus,z as swappableTokens,y as tokenSwapQuote,R as updateUserPositionConditions,ba as userBalances,Z as userBorrows,t as userClaimableRewards,aa as userPosition,$ as userPositions,da as userRiskPremiumBreakdown,_ as userSummary,ca as userSummaryHistory,Y as userSupplies,L as userSwaps,H as waitForSwapOutcome,P as withdraw,E as withdrawSwapQuote}from'../chunk-RM3HEVPN.js';//# sourceMappingURL=index.js.map
1
+ export{X as activities,k as asset,n as assetBorrowHistory,l as assetPriceHistory,m as assetSupplyHistory,M as borrow,r as borrowApyHistory,C as borrowSwapQuote,K as cancelSwap,g as chain,h as chains,W as claimRewards,j as exchangeRate,i as hasProcessedKnownTransaction,b as hub,f as hubAssetInterestRateModel,d as hubAssets,e as hubSummaryHistory,c as hubs,S as liquidatePosition,F as preparePositionSwap,J as prepareSwapCancel,A as prepareTokenSwap,U as preview,o as protocolHistory,Q as renounceSpokeUserPositionManager,O as repay,D as repayWithSupplyQuote,p as reserve,q as reserves,T as setSpokeUserPositionManager,V as setUserSuppliesAsCollateral,u as spoke,w as spokePositionManagers,x as spokeUserPositionManagers,v as spokes,ea as stableVault,ha as stableVaultAssignRate,oa as stableVaultClaimStatus,ja as stableVaultClaimSurplus,la as stableVaultDeposit,ka as stableVaultMovements,ga as stableVaultRateUsers,ia as stableVaultUnassignRate,pa as stableVaultUserPositions,ma as stableVaultWithdraw,na as stableVaultWithdrawRedeem,fa as stableVaults,N as supply,s as supplyApyHistory,B as supplySwapQuote,I as swap,G as swapStatus,z as swappableTokens,y as tokenSwapQuote,R as updateUserPositionConditions,ba as userBalances,Z as userBorrows,t as userClaimableRewards,aa as userPosition,$ as userPositions,da as userRiskPremiumBreakdown,_ as userSummary,ca as userSummaryHistory,Y as userSupplies,L as userSwaps,qa as waitForStableVaultWithdrawClaim,H as waitForSwapOutcome,P as withdraw,E as withdrawSwapQuote}from'../chunk-LCNG3LBO.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import {a}from'./chunk-N4LXBTGY.js';import {g}from'./chunk-RM3HEVPN.js';import {SigningError,CancelError,TransactionError,UnexpectedError,ValidationError}from'@aave/core';import {chainId,ResultAsync,okAsync,invariant,txHash,errAsync,isObject,signatureFrom}from'@aave/types';import {defineChain,SwitchChainError,UserRejectedRequestError,TransactionExecutionError}from'viem';import {waitForTransactionReceipt,sendTransaction,estimateGas}from'viem/actions';import {sepolia,mainnet}from'viem/chains';function m(n){return isObject(n)&&"code"in n&&"message"in n}function F(n){return isObject(n)&&"name"in n&&"message"in n&&"originalError"in n?m(n.originalError)&&"code"in n.originalError:true}function R(n,e){return invariant(n.account,"Wallet account is required to sign typed data"),ResultAsync.fromPromise(n.signTypedData({account:n.account,domain:e.domain,types:e.types,primaryType:e.primaryType,message:e.message}),r=>r instanceof UserRejectedRequestError?CancelError.from(r):SigningError.from(r)).map(signatureFrom)}function v(n){switch(n.chainId){case chainId(mainnet.id):return mainnet;case chainId(sepolia.id):return sepolia}return defineChain({id:n.chainId,name:n.name,nativeCurrency:{name:n.nativeInfo.name,symbol:n.nativeInfo.symbol,decimals:n.nativeInfo.decimals},rpcUrls:{default:{http:[n.rpcUrl]}},blockExplorers:{default:{name:`${n.name} Explorer`,url:n.explorerUrl}}})}function Y(n){return n.map(v)}function Z(n,e,r){return ResultAsync.fromPromise(e.getChainId(),t=>SigningError.from(t)).andThen(t=>t===r.chainId?okAsync():g(n,{chainId:r.chainId},{batch:false}).andThen(a=>(invariant(a,`Chain ${r.chainId} is not supported`),ResultAsync.fromPromise(e.switchChain({id:r.chainId}),i=>SigningError.from(i)).orElse(i=>(m(i.cause)?i.cause.code:F(i.cause)?i.cause.data?.originalError?.code:void 0)===SwitchChainError.code?ResultAsync.fromPromise(e.addChain({chain:v(a)}),u=>m(u)&&u.code===UserRejectedRequestError.code?CancelError.from(u):SigningError.from(u)):i.asResultAsync()))))}function G(n,e){return ResultAsync.fromPromise(estimateGas(n,{account:n.account,data:e.data,to:e.to,value:BigInt(e.value),prepare:false}),r=>SigningError.from(r)).map(r=>r*115n/100n)}function $(n,e){return G(n,e).andThen(r=>ResultAsync.fromPromise(sendTransaction(n,{account:n.account,data:e.data,to:e.to,value:BigInt(e.value),chain:n.chain,gas:r}),t=>{if(t instanceof TransactionExecutionError){let a=t.walk(i=>i instanceof UserRejectedRequestError);if(a)return CancelError.from(a)}return SigningError.from(t)})).map(txHash)}function j(n){return n.account!==void 0}function B(n,e){return invariant(j(n),"Wallet client with account is required"),$(n,e)}function _(n,e,r){let t=n?.blockExplorers?.default?.url,a=t&&new URL(`/tx/${e}`,t).toString();return TransactionError.new({txHash:e,request:r,link:a})}function w(n,e,r){return ResultAsync.fromPromise(waitForTransactionReceipt(n,{hash:r,pollingInterval:100,retryCount:20,retryDelay:50}),t=>UnexpectedError.from(t)).andThen(t=>{let a=txHash(t.transactionHash);switch(t.status){case "reverted":return r!==a?errAsync(CancelError.from(`Transaction replaced by ${a}`)):errAsync(_(n.chain,a,e));case "success":return okAsync({txHash:a,operations:e.operations})}})}function s(n,e){return B(n,e).andThen(r=>w(n,e,r))}function C(n,e){switch(e.__typename){case "TransactionRequest":return s(n,e);case "Erc20ApprovalRequired":return e.approvals.reduce((r,t)=>r.andThen(()=>s(n,t.byTransaction)),okAsync(void 0)).andThen(()=>s(n,e.originalTransaction));case "PreContractActionRequired":return s(n,e.transaction).andThen(()=>s(n,e.originalTransaction));case "InsufficientBalanceError":return errAsync(ValidationError.fromGqlNode(e))}}function nn(n,e){return e?C(n,e):C.bind(null,n)}function L(n,e){return e===void 0?R.bind(null,n):R(n,e)}function en(n,e){return e().andThen(r=>{if(a(r)){let t=r.approvals[0].bySignature;return L(n,t).map(a=>({deadline:t.message.deadline,value:a})).andThen(a=>e(a))}return okAsync(r)})}export{v as a,Y as b,Z as c,B as d,_ as e,w as f,nn as g,L as h,en as i};//# sourceMappingURL=chunk-CMTDTGTS.js.map
2
- //# sourceMappingURL=chunk-CMTDTGTS.js.map
1
+ import {a}from'./chunk-N4LXBTGY.js';import {g}from'./chunk-LCNG3LBO.js';import {SigningError,CancelError,TransactionError,UnexpectedError,ValidationError}from'@aave/core';import {chainId,ResultAsync,okAsync,invariant,txHash,errAsync,isObject,signatureFrom}from'@aave/types';import {defineChain,SwitchChainError,UserRejectedRequestError,TransactionExecutionError}from'viem';import {waitForTransactionReceipt,sendTransaction,estimateGas}from'viem/actions';import {sepolia,mainnet}from'viem/chains';function m(n){return isObject(n)&&"code"in n&&"message"in n}function F(n){return isObject(n)&&"name"in n&&"message"in n&&"originalError"in n?m(n.originalError)&&"code"in n.originalError:true}function R(n,e){return invariant(n.account,"Wallet account is required to sign typed data"),ResultAsync.fromPromise(n.signTypedData({account:n.account,domain:e.domain,types:e.types,primaryType:e.primaryType,message:e.message}),r=>r instanceof UserRejectedRequestError?CancelError.from(r):SigningError.from(r)).map(signatureFrom)}function v(n){switch(n.chainId){case chainId(mainnet.id):return mainnet;case chainId(sepolia.id):return sepolia}return defineChain({id:n.chainId,name:n.name,nativeCurrency:{name:n.nativeInfo.name,symbol:n.nativeInfo.symbol,decimals:n.nativeInfo.decimals},rpcUrls:{default:{http:[n.rpcUrl]}},blockExplorers:{default:{name:`${n.name} Explorer`,url:n.explorerUrl}}})}function Y(n){return n.map(v)}function Z(n,e,r){return ResultAsync.fromPromise(e.getChainId(),t=>SigningError.from(t)).andThen(t=>t===r.chainId?okAsync():g(n,{chainId:r.chainId},{batch:false}).andThen(a=>(invariant(a,`Chain ${r.chainId} is not supported`),ResultAsync.fromPromise(e.switchChain({id:r.chainId}),i=>SigningError.from(i)).orElse(i=>(m(i.cause)?i.cause.code:F(i.cause)?i.cause.data?.originalError?.code:void 0)===SwitchChainError.code?ResultAsync.fromPromise(e.addChain({chain:v(a)}),u=>m(u)&&u.code===UserRejectedRequestError.code?CancelError.from(u):SigningError.from(u)):i.asResultAsync()))))}function G(n,e){return ResultAsync.fromPromise(estimateGas(n,{account:n.account,data:e.data,to:e.to,value:BigInt(e.value),prepare:false}),r=>SigningError.from(r)).map(r=>r*115n/100n)}function $(n,e){return G(n,e).andThen(r=>ResultAsync.fromPromise(sendTransaction(n,{account:n.account,data:e.data,to:e.to,value:BigInt(e.value),chain:n.chain,gas:r}),t=>{if(t instanceof TransactionExecutionError){let a=t.walk(i=>i instanceof UserRejectedRequestError);if(a)return CancelError.from(a)}return SigningError.from(t)})).map(txHash)}function j(n){return n.account!==void 0}function B(n,e){return invariant(j(n),"Wallet client with account is required"),$(n,e)}function _(n,e,r){let t=n?.blockExplorers?.default?.url,a=t&&new URL(`/tx/${e}`,t).toString();return TransactionError.new({txHash:e,request:r,link:a})}function w(n,e,r){return ResultAsync.fromPromise(waitForTransactionReceipt(n,{hash:r,pollingInterval:100,retryCount:20,retryDelay:50}),t=>UnexpectedError.from(t)).andThen(t=>{let a=txHash(t.transactionHash);switch(t.status){case "reverted":return r!==a?errAsync(CancelError.from(`Transaction replaced by ${a}`)):errAsync(_(n.chain,a,e));case "success":return okAsync({txHash:a,operations:e.operations})}})}function s(n,e){return B(n,e).andThen(r=>w(n,e,r))}function C(n,e){switch(e.__typename){case "TransactionRequest":return s(n,e);case "Erc20ApprovalRequired":return e.approvals.reduce((r,t)=>r.andThen(()=>s(n,t.byTransaction)),okAsync(void 0)).andThen(()=>s(n,e.originalTransaction));case "PreContractActionRequired":return s(n,e.transaction).andThen(()=>s(n,e.originalTransaction));case "InsufficientBalanceError":return errAsync(ValidationError.fromGqlNode(e))}}function nn(n,e){return e?C(n,e):C.bind(null,n)}function L(n,e){return e===void 0?R.bind(null,n):R(n,e)}function en(n,e){return e().andThen(r=>{if(a(r)){let t=r.approvals[0].bySignature;return L(n,t).map(a=>({deadline:t.message.deadline,value:a})).andThen(a=>e(a))}return okAsync(r)})}export{v as a,Y as b,Z as c,B as d,_ as e,w as f,nn as g,L as h,en as i};//# sourceMappingURL=chunk-7THMGPSC.js.map
2
+ //# sourceMappingURL=chunk-7THMGPSC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/viem.ts"],"names":["isRpcError","err","isObject","isProviderRpcError","signTypedData","walletClient","data","invariant","ResultAsync","UserRejectedRequestError","CancelError","SigningError","signatureFrom","toViemChain","chain","chainId","mainnet","sepolia","defineChain","viemChainsFrom","chains","ensureChain","aaveClient","request","okAsync","SwitchChainError","estimateGas","estimateGasWithViem","gas","sendEip1559Transaction","sendTransactionWithViem","TransactionExecutionError","rejected","txHash","isWalletClientWithAccount","sendTransaction","transactionError","baseUrl","link","TransactionError","waitForTransactionResult","initialTxHash","waitForTransactionReceipt","UnexpectedError","receipt","hash","errAsync","sendTransactionAndWait","executePlan","result","approval","ValidationError","sendWith","signTypedDataWith","permitWith","action","supportsPermit","permitTypedData","signature","permitSig"],"mappings":"gfAsDA,SAASA,CAAAA,CAAWC,EAA+B,CACjD,OAAOC,SAASD,CAAG,CAAA,EAAK,SAAUA,CAAAA,EAAO,SAAA,GAAaA,CACxD,CAEA,SAASE,EACPF,CAAAA,CAC+D,CAC/D,OAAOC,QAAAA,CAASD,CAAG,GACjB,MAAA,GAAUA,CAAAA,EACV,YAAaA,CAAAA,EACb,eAAA,GAAmBA,EACjBD,CAAAA,CAAWC,CAAAA,CAAI,aAAa,CAAA,EAAK,MAAA,GAAUA,EAAI,aAAA,CAC/C,IACN,CAEA,SAASG,CAAAA,CACPC,CAAAA,CACAC,CAAAA,CAC4C,CAC5C,OAAAC,UACEF,CAAAA,CAAa,OAAA,CACb,+CACF,CAAA,CAEOG,WAAAA,CAAY,YACjBH,CAAAA,CAAa,aAAA,CAAc,CACzB,OAAA,CAASA,CAAAA,CAAa,QACtB,MAAA,CAAQC,CAAAA,CAAK,OACb,KAAA,CAAOA,CAAAA,CAAK,MACZ,WAAA,CAAaA,CAAAA,CAAK,YAClB,OAAA,CAASA,CAAAA,CAAK,OAChB,CAAC,CAAA,CACAL,GACKA,CAAAA,YAAeQ,wBAAAA,CACVC,YAAY,IAAA,CAAKT,CAAG,EAEtBU,YAAAA,CAAa,IAAA,CAAKV,CAAG,CAEhC,CAAA,CAAE,IAAIW,aAAa,CACrB,CAKO,SAASC,CAAAA,CAAYC,EAAyB,CAEnD,OAAQA,EAAM,OAAA,EACZ,KAAKC,OAAAA,CAAQC,OAAAA,CAA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AK,4BACH,OAAOF,CAAAA,CAAuB1C,EAAc4C,CAAAA,CAAO,WAAW,EAAE,OAAA,CAC9D,IAAMF,EAAuB1C,CAAAA,CAAc4C,CAAAA,CAAO,mBAAmB,CACvE,CAAA,CAEF,KAAK,2BACH,OAAOH,QAAAA,CAASK,gBAAgB,WAAA,CAAYF,CAAM,CAAC,CACvD,CACF,CAaO,SAASG,EAAAA,CACd/C,EACA4C,CAAAA,CAC+D,CAC/D,OAAOA,CAAAA,CACHD,CAAAA,CAAY3C,EAAc4C,CAAM,CAAA,CAChCD,EAAY,IAAA,CAAK,IAAA,CAAM3C,CAAY,CACzC,CA+BO,SAASgD,CAAAA,CACdhD,CAAAA,CACAC,EACiD,CACjD,OAAIA,IAAS,MAAA,CACJF,CAAAA,CAAc,KAAK,IAAA,CAAMC,CAAY,EAEvCD,CAAAA,CAAcC,CAAAA,CAAcC,CAAI,CACzC,CAyBO,SAASgD,EAAAA,CACdjD,CAAAA,CACAkD,CAAAA,CACoD,CACpD,OAAOA,CAAAA,GAAS,OAAA,CAASN,CAAAA,EAAW,CAClC,GAAIO,CAAAA,CAAeP,CAAM,CAAA,CAAG,CAC1B,IAAMQ,CAAAA,CAAkBR,CAAAA,CAAO,UAAU,CAAC,CAAA,CAAE,YAE5C,OAAOI,CAAAA,CAAkBhD,EAAcoD,CAAe,CAAA,CACnD,IAAKC,CAAAA,GAAe,CACnB,SAAUD,CAAAA,CAAgB,OAAA,CAAQ,SAClC,KAAA,CAAOC,CACT,EAAE,CAAA,CACD,OAAA,CAASC,GAAcJ,CAAAA,CAAOI,CAAS,CAAC,CAC7C,CACA,OAAOnC,OAAAA,CAAQyB,CAAM,CACvB,CAAC,CACH","file":"chunk-CMTDTGTS.js","sourcesContent":["import {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n Chain,\n ERC20PermitSignature,\n ExecutionPlan,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n chainId,\n errAsync,\n invariant,\n isObject,\n okAsync,\n ResultAsync,\n type Signature,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport {\n type Account,\n defineChain,\n type ProviderRpcError,\n type RpcError,\n SwitchChainError,\n TransactionExecutionError,\n type Transport,\n UserRejectedRequestError,\n type Chain as ViemChain,\n type WalletClient,\n} from 'viem';\nimport {\n estimateGas as estimateGasWithViem,\n sendTransaction as sendTransactionWithViem,\n waitForTransactionReceipt,\n} from 'viem/actions';\nimport { mainnet, sepolia } from 'viem/chains';\nimport type { AaveClient } from './AaveClient';\nimport { chain as fetchChain } from './actions';\nimport { supportsPermit } from './adapters';\nimport type {\n ExecutionPlanHandler,\n SignTypedDataError,\n TransactionResult,\n TypedData,\n TypedDataHandler,\n} from './types';\n\nfunction isRpcError(err: unknown): err is RpcError {\n return isObject(err) && 'code' in err && 'message' in err;\n}\n\nfunction isProviderRpcError(\n err: unknown,\n): err is ProviderRpcError<{ originalError?: { code: number } }> {\n return isObject(err) &&\n 'name' in err &&\n 'message' in err &&\n 'originalError' in err\n ? isRpcError(err.originalError) && 'code' in err.originalError\n : true;\n}\n\nfunction signTypedData(\n walletClient: WalletClient,\n data: TypedData,\n): ResultAsync<Signature, SignTypedDataError> {\n invariant(\n walletClient.account,\n 'Wallet account is required to sign typed data',\n );\n\n return ResultAsync.fromPromise(\n walletClient.signTypedData({\n account: walletClient.account,\n domain: data.domain,\n types: data.types,\n primaryType: data.primaryType,\n message: data.message,\n }),\n (err) => {\n if (err instanceof UserRejectedRequestError) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n ).map(signatureFrom);\n}\n\n/**\n * @internal\n */\nexport function toViemChain(chain: Chain): ViemChain {\n // known chains\n switch (chain.chainId) {\n case chainId(mainnet.id):\n return mainnet;\n\n case chainId(sepolia.id):\n return sepolia;\n }\n\n // most likely a tenderly fork\n return defineChain({\n id: chain.chainId,\n name: chain.name,\n nativeCurrency: {\n name: chain.nativeInfo.name,\n symbol: chain.nativeInfo.symbol,\n decimals: chain.nativeInfo.decimals,\n },\n rpcUrls: { default: { http: [chain.rpcUrl] } },\n blockExplorers: {\n default: {\n name: `${chain.name} Explorer`,\n url: chain.explorerUrl,\n },\n },\n });\n}\n\n/**\n * @internal\n */\nexport function viemChainsFrom(chains: Chain[]): ViemChain[] {\n return chains.map(toViemChain);\n}\n\n/**\n * @internal\n */\nexport function ensureChain(\n aaveClient: AaveClient,\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<void, CancelError | SigningError | UnexpectedError> {\n return ResultAsync.fromPromise(walletClient.getChainId(), (err) =>\n SigningError.from(err),\n ).andThen((chainId) => {\n if (chainId === request.chainId) {\n return okAsync();\n }\n\n return fetchChain(\n aaveClient,\n { chainId: request.chainId },\n { batch: false },\n ).andThen((chain) => {\n invariant(chain, `Chain ${request.chainId} is not supported`);\n\n return ResultAsync.fromPromise(\n walletClient.switchChain({ id: request.chainId }),\n (err) => SigningError.from(err),\n ).orElse((err) => {\n const code = isRpcError(err.cause)\n ? err.cause.code\n : // Unwrapping for MetaMask Mobile\n // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719\n isProviderRpcError(err.cause)\n ? err.cause.data?.originalError?.code\n : undefined;\n\n if (code === SwitchChainError.code) {\n return ResultAsync.fromPromise(\n walletClient.addChain({ chain: toViemChain(chain) }),\n (err) => {\n if (\n isRpcError(err) &&\n err.code === UserRejectedRequestError.code\n ) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n );\n }\n\n return err.asResultAsync();\n });\n });\n });\n}\n\nfunction estimateGas(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<bigint, SigningError> {\n return ResultAsync.fromPromise(\n estimateGasWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n prepare: false,\n }),\n (err) => SigningError.from(err),\n ).map((gas) => (gas * 115n) / 100n); // 15% buffer\n}\n\nfunction sendEip1559Transaction(\n walletClient: WalletClient<Transport, ViemChain, Account>,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n return estimateGas(walletClient, request)\n .andThen((gas) =>\n ResultAsync.fromPromise(\n sendTransactionWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n chain: walletClient.chain,\n gas,\n }),\n (err) => {\n if (err instanceof TransactionExecutionError) {\n const rejected = err.walk(\n (err) => err instanceof UserRejectedRequestError,\n );\n\n if (rejected) {\n return CancelError.from(rejected);\n }\n }\n return SigningError.from(err);\n },\n ),\n )\n .map(txHash);\n}\n\nfunction isWalletClientWithAccount(\n walletClient: WalletClient,\n): walletClient is WalletClient<Transport, ViemChain, Account> {\n return walletClient.account !== undefined;\n}\n\n/**\n * @internal\n */\nexport function sendTransaction(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n invariant(\n isWalletClientWithAccount(walletClient),\n 'Wallet client with account is required',\n );\n\n return sendEip1559Transaction(walletClient, request);\n}\n\n/**\n * @internal\n */\nexport function transactionError(\n chain: ViemChain | undefined,\n txHash: TxHash,\n request: TransactionRequest,\n): TransactionError {\n const baseUrl = chain?.blockExplorers?.default?.url;\n const link = baseUrl && new URL(`/tx/${txHash}`, baseUrl).toString();\n\n return TransactionError.new({ txHash, request, link });\n}\n\n/**\n * @internal\n */\nexport function waitForTransactionResult(\n walletClient: WalletClient,\n request: TransactionRequest,\n initialTxHash: TxHash,\n): ResultAsync<\n TransactionResult,\n CancelError | TransactionError | UnexpectedError\n> {\n return ResultAsync.fromPromise(\n waitForTransactionReceipt(walletClient, {\n hash: initialTxHash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n (err) => UnexpectedError.from(err),\n ).andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n switch (receipt.status) {\n case 'reverted':\n if (initialTxHash !== hash) {\n return errAsync(CancelError.from(`Transaction replaced by ${hash}`));\n }\n return errAsync(transactionError(walletClient.chain, hash, request));\n case 'success':\n return okAsync({\n // viem's waitForTransactionReceipt supports transaction replacement\n // so it's important to use the transaction hash from the receipt\n txHash: hash,\n operations: request.operations,\n });\n }\n });\n}\n\nfunction sendTransactionAndWait(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResult,\n CancelError | SigningError | TransactionError | UnexpectedError\n> {\n return sendTransaction(walletClient, request).andThen((hash) =>\n waitForTransactionResult(walletClient, request, hash),\n );\n}\n\nfunction executePlan(\n walletClient: WalletClient,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(walletClient, result);\n\n case 'Erc20ApprovalRequired':\n return result.approvals\n .reduce<ReturnType<typeof sendTransactionAndWait>>(\n (chain, approval) =>\n chain.andThen(() =>\n sendTransactionAndWait(walletClient, approval.byTransaction),\n ),\n okAsync(undefined as never),\n )\n .andThen(() =>\n sendTransactionAndWait(walletClient, result.originalTransaction),\n );\n\n case 'PreContractActionRequired':\n return sendTransactionAndWait(walletClient, result.transaction).andThen(\n () => sendTransactionAndWait(walletClient, result.originalTransaction),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the provided wallet client.\n */\nexport function sendWith(walletClient: WalletClient): ExecutionPlanHandler;\n/**\n * Sends execution plan transactions using the provided wallet client.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(walletClient, result)\n : executePlan.bind(null, walletClient);\n}\n\n/**\n * Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided wallet client.\n *\n * @param walletClient - The wallet client to use for signing.\n * @returns A function that takes typed data and returns a ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await prepareSwapCancel(client, request)\n * .andThen(signTypedDataWith(wallet));\n * ```\n */\nexport function signTypedDataWith(walletClient: WalletClient): TypedDataHandler;\n\n/**\n * Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided wallet client.\n *\n * @param walletClient - The wallet client to use for signing.\n * @param data - The typed data to sign.\n * @returns A ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await signTypedDataWith(wallet, typedData);\n * ```\n */\nexport function signTypedDataWith(\n walletClient: WalletClient,\n data: TypedData,\n): ReturnType<TypedDataHandler>;\n\nexport function signTypedDataWith(\n walletClient: WalletClient,\n data?: TypedData,\n): TypedDataHandler | ReturnType<TypedDataHandler> {\n if (data === undefined) {\n return signTypedData.bind(null, walletClient);\n }\n return signTypedData(walletClient, data);\n}\n\n/**\n * Handles ERC20 permit signing for actions that require token approval.\n *\n * Calls the action to get an initial execution plan. If the plan requires ERC20 approval\n * and the token supports permit signatures, signs the permit and re-calls the action\n * with the signature to get a new plan that can be sent directly.\n *\n * ```ts\n * const result = await permitWith(walletClient, (permitSig) =>\n * supply(client, {\n * reserve: reserve.id,\n * amount: { erc20: { value: amount, permitSig } },\n * sender: evmAddress(walletClient.account.address),\n * })\n * )\n * .andThen(sendWith(walletClient))\n * .andThen(client.waitForTransaction);\n * ```\n *\n * @param walletClient - The wallet client to use for signing permits.\n * @param action - A function that returns an execution plan, accepting an optional permit signature.\n * @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.\n */\nexport function permitWith<E>(\n walletClient: WalletClient,\n action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>,\n): ResultAsync<ExecutionPlan, E | SignTypedDataError> {\n return action().andThen((result) => {\n if (supportsPermit(result)) {\n const permitTypedData = result.approvals[0].bySignature;\n // Sign and wrap with deadline\n return signTypedDataWith(walletClient, permitTypedData)\n .map((signature) => ({\n deadline: permitTypedData.message.deadline as number,\n value: signature,\n }))\n .andThen((permitSig) => action(permitSig));\n }\n return okAsync(result);\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/viem.ts"],"names":["isRpcError","err","isObject","isProviderRpcError","signTypedData","walletClient","data","invariant","ResultAsync","UserRejectedRequestError","CancelError","SigningError","signatureFrom","toViemChain","chain","chainId","mainnet","sepolia","defineChain","viemChainsFrom","chains","ensureChain","aaveClient","request","okAsync","SwitchChainError","estimateGas","estimateGasWithViem","gas","sendEip1559Transaction","sendTransactionWithViem","TransactionExecutionError","rejected","txHash","isWalletClientWithAccount","sendTransaction","transactionError","baseUrl","link","TransactionError","waitForTransactionResult","initialTxHash","waitForTransactionReceipt","UnexpectedError","receipt","hash","errAsync","sendTransactionAndWait","executePlan","result","approval","ValidationError","sendWith","signTypedDataWith","permitWith","action","supportsPermit","permitTypedData","signature","permitSig"],"mappings":"gfAsDA,SAASA,CAAAA,CAAWC,EAA+B,CACjD,OAAOC,SAASD,CAAG,CAAA,EAAK,SAAUA,CAAAA,EAAO,SAAA,GAAaA,CACxD,CAEA,SAASE,EACPF,CAAAA,CAC+D,CAC/D,OAAOC,QAAAA,CAASD,CAAG,GACjB,MAAA,GAAUA,CAAAA,EACV,YAAaA,CAAAA,EACb,eAAA,GAAmBA,EACjBD,CAAAA,CAAWC,CAAAA,CAAI,aAAa,CAAA,EAAK,MAAA,GAAUA,EAAI,aAAA,CAC/C,IACN,CAEA,SAASG,CAAAA,CACPC,CAAAA,CACAC,CAAAA,CAC4C,CAC5C,OAAAC,UACEF,CAAAA,CAAa,OAAA,CACb,+CACF,CAAA,CAEOG,WAAAA,CAAY,YACjBH,CAAAA,CAAa,aAAA,CAAc,CACzB,OAAA,CAASA,CAAAA,CAAa,QACtB,MAAA,CAAQC,CAAAA,CAAK,OACb,KAAA,CAAOA,CAAAA,CAAK,MACZ,WAAA,CAAaA,CAAAA,CAAK,YAClB,OAAA,CAASA,CAAAA,CAAK,OAChB,CAAC,CAAA,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AC,CAC7C,CACA,OAAOnC,OAAAA,CAAQyB,CAAM,CACvB,CAAC,CACH","file":"chunk-7THMGPSC.js","sourcesContent":["import {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n Chain,\n ERC20PermitSignature,\n ExecutionPlan,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n chainId,\n errAsync,\n invariant,\n isObject,\n okAsync,\n ResultAsync,\n type Signature,\n signatureFrom,\n type TxHash,\n txHash,\n} from '@aave/types';\nimport {\n type Account,\n defineChain,\n type ProviderRpcError,\n type RpcError,\n SwitchChainError,\n TransactionExecutionError,\n type Transport,\n UserRejectedRequestError,\n type Chain as ViemChain,\n type WalletClient,\n} from 'viem';\nimport {\n estimateGas as estimateGasWithViem,\n sendTransaction as sendTransactionWithViem,\n waitForTransactionReceipt,\n} from 'viem/actions';\nimport { mainnet, sepolia } from 'viem/chains';\nimport type { AaveClient } from './AaveClient';\nimport { chain as fetchChain } from './actions';\nimport { supportsPermit } from './adapters';\nimport type {\n ExecutionPlanHandler,\n SignTypedDataError,\n TransactionResult,\n TypedData,\n TypedDataHandler,\n} from './types';\n\nfunction isRpcError(err: unknown): err is RpcError {\n return isObject(err) && 'code' in err && 'message' in err;\n}\n\nfunction isProviderRpcError(\n err: unknown,\n): err is ProviderRpcError<{ originalError?: { code: number } }> {\n return isObject(err) &&\n 'name' in err &&\n 'message' in err &&\n 'originalError' in err\n ? isRpcError(err.originalError) && 'code' in err.originalError\n : true;\n}\n\nfunction signTypedData(\n walletClient: WalletClient,\n data: TypedData,\n): ResultAsync<Signature, SignTypedDataError> {\n invariant(\n walletClient.account,\n 'Wallet account is required to sign typed data',\n );\n\n return ResultAsync.fromPromise(\n walletClient.signTypedData({\n account: walletClient.account,\n domain: data.domain,\n types: data.types,\n primaryType: data.primaryType,\n message: data.message,\n }),\n (err) => {\n if (err instanceof UserRejectedRequestError) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n ).map(signatureFrom);\n}\n\n/**\n * @internal\n */\nexport function toViemChain(chain: Chain): ViemChain {\n // known chains\n switch (chain.chainId) {\n case chainId(mainnet.id):\n return mainnet;\n\n case chainId(sepolia.id):\n return sepolia;\n }\n\n // most likely a tenderly fork\n return defineChain({\n id: chain.chainId,\n name: chain.name,\n nativeCurrency: {\n name: chain.nativeInfo.name,\n symbol: chain.nativeInfo.symbol,\n decimals: chain.nativeInfo.decimals,\n },\n rpcUrls: { default: { http: [chain.rpcUrl] } },\n blockExplorers: {\n default: {\n name: `${chain.name} Explorer`,\n url: chain.explorerUrl,\n },\n },\n });\n}\n\n/**\n * @internal\n */\nexport function viemChainsFrom(chains: Chain[]): ViemChain[] {\n return chains.map(toViemChain);\n}\n\n/**\n * @internal\n */\nexport function ensureChain(\n aaveClient: AaveClient,\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<void, CancelError | SigningError | UnexpectedError> {\n return ResultAsync.fromPromise(walletClient.getChainId(), (err) =>\n SigningError.from(err),\n ).andThen((chainId) => {\n if (chainId === request.chainId) {\n return okAsync();\n }\n\n return fetchChain(\n aaveClient,\n { chainId: request.chainId },\n { batch: false },\n ).andThen((chain) => {\n invariant(chain, `Chain ${request.chainId} is not supported`);\n\n return ResultAsync.fromPromise(\n walletClient.switchChain({ id: request.chainId }),\n (err) => SigningError.from(err),\n ).orElse((err) => {\n const code = isRpcError(err.cause)\n ? err.cause.code\n : // Unwrapping for MetaMask Mobile\n // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719\n isProviderRpcError(err.cause)\n ? err.cause.data?.originalError?.code\n : undefined;\n\n if (code === SwitchChainError.code) {\n return ResultAsync.fromPromise(\n walletClient.addChain({ chain: toViemChain(chain) }),\n (err) => {\n if (\n isRpcError(err) &&\n err.code === UserRejectedRequestError.code\n ) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n );\n }\n\n return err.asResultAsync();\n });\n });\n });\n}\n\nfunction estimateGas(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<bigint, SigningError> {\n return ResultAsync.fromPromise(\n estimateGasWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n prepare: false,\n }),\n (err) => SigningError.from(err),\n ).map((gas) => (gas * 115n) / 100n); // 15% buffer\n}\n\nfunction sendEip1559Transaction(\n walletClient: WalletClient<Transport, ViemChain, Account>,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n return estimateGas(walletClient, request)\n .andThen((gas) =>\n ResultAsync.fromPromise(\n sendTransactionWithViem(walletClient, {\n account: walletClient.account,\n data: request.data,\n to: request.to,\n value: BigInt(request.value),\n chain: walletClient.chain,\n gas,\n }),\n (err) => {\n if (err instanceof TransactionExecutionError) {\n const rejected = err.walk(\n (err) => err instanceof UserRejectedRequestError,\n );\n\n if (rejected) {\n return CancelError.from(rejected);\n }\n }\n return SigningError.from(err);\n },\n ),\n )\n .map(txHash);\n}\n\nfunction isWalletClientWithAccount(\n walletClient: WalletClient,\n): walletClient is WalletClient<Transport, ViemChain, Account> {\n return walletClient.account !== undefined;\n}\n\n/**\n * @internal\n */\nexport function sendTransaction(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<TxHash, CancelError | SigningError> {\n invariant(\n isWalletClientWithAccount(walletClient),\n 'Wallet client with account is required',\n );\n\n return sendEip1559Transaction(walletClient, request);\n}\n\n/**\n * @internal\n */\nexport function transactionError(\n chain: ViemChain | undefined,\n txHash: TxHash,\n request: TransactionRequest,\n): TransactionError {\n const baseUrl = chain?.blockExplorers?.default?.url;\n const link = baseUrl && new URL(`/tx/${txHash}`, baseUrl).toString();\n\n return TransactionError.new({ txHash, request, link });\n}\n\n/**\n * @internal\n */\nexport function waitForTransactionResult(\n walletClient: WalletClient,\n request: TransactionRequest,\n initialTxHash: TxHash,\n): ResultAsync<\n TransactionResult,\n CancelError | TransactionError | UnexpectedError\n> {\n return ResultAsync.fromPromise(\n waitForTransactionReceipt(walletClient, {\n hash: initialTxHash,\n pollingInterval: 100,\n retryCount: 20,\n retryDelay: 50,\n }),\n (err) => UnexpectedError.from(err),\n ).andThen((receipt) => {\n const hash = txHash(receipt.transactionHash);\n\n switch (receipt.status) {\n case 'reverted':\n if (initialTxHash !== hash) {\n return errAsync(CancelError.from(`Transaction replaced by ${hash}`));\n }\n return errAsync(transactionError(walletClient.chain, hash, request));\n case 'success':\n return okAsync({\n // viem's waitForTransactionReceipt supports transaction replacement\n // so it's important to use the transaction hash from the receipt\n txHash: hash,\n operations: request.operations,\n });\n }\n });\n}\n\nfunction sendTransactionAndWait(\n walletClient: WalletClient,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResult,\n CancelError | SigningError | TransactionError | UnexpectedError\n> {\n return sendTransaction(walletClient, request).andThen((hash) =>\n waitForTransactionResult(walletClient, request, hash),\n );\n}\n\nfunction executePlan(\n walletClient: WalletClient,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(walletClient, result);\n\n case 'Erc20ApprovalRequired':\n return result.approvals\n .reduce<ReturnType<typeof sendTransactionAndWait>>(\n (chain, approval) =>\n chain.andThen(() =>\n sendTransactionAndWait(walletClient, approval.byTransaction),\n ),\n okAsync(undefined as never),\n )\n .andThen(() =>\n sendTransactionAndWait(walletClient, result.originalTransaction),\n );\n\n case 'PreContractActionRequired':\n return sendTransactionAndWait(walletClient, result.transaction).andThen(\n () => sendTransactionAndWait(walletClient, result.originalTransaction),\n );\n\n case 'InsufficientBalanceError':\n return errAsync(ValidationError.fromGqlNode(result));\n }\n}\n\n/**\n * Creates an execution plan handler that sends transactions using the provided wallet client.\n */\nexport function sendWith(walletClient: WalletClient): ExecutionPlanHandler;\n/**\n * Sends execution plan transactions using the provided wallet client.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n walletClient: WalletClient,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result\n ? executePlan(walletClient, result)\n : executePlan.bind(null, walletClient);\n}\n\n/**\n * Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided wallet client.\n *\n * @param walletClient - The wallet client to use for signing.\n * @returns A function that takes typed data and returns a ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await prepareSwapCancel(client, request)\n * .andThen(signTypedDataWith(wallet));\n * ```\n */\nexport function signTypedDataWith(walletClient: WalletClient): TypedDataHandler;\n\n/**\n * Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided wallet client.\n *\n * @param walletClient - The wallet client to use for signing.\n * @param data - The typed data to sign.\n * @returns A ResultAsync containing the raw signature.\n *\n * ```ts\n * const result = await signTypedDataWith(wallet, typedData);\n * ```\n */\nexport function signTypedDataWith(\n walletClient: WalletClient,\n data: TypedData,\n): ReturnType<TypedDataHandler>;\n\nexport function signTypedDataWith(\n walletClient: WalletClient,\n data?: TypedData,\n): TypedDataHandler | ReturnType<TypedDataHandler> {\n if (data === undefined) {\n return signTypedData.bind(null, walletClient);\n }\n return signTypedData(walletClient, data);\n}\n\n/**\n * Handles ERC20 permit signing for actions that require token approval.\n *\n * Calls the action to get an initial execution plan. If the plan requires ERC20 approval\n * and the token supports permit signatures, signs the permit and re-calls the action\n * with the signature to get a new plan that can be sent directly.\n *\n * ```ts\n * const result = await permitWith(walletClient, (permitSig) =>\n * supply(client, {\n * reserve: reserve.id,\n * amount: { erc20: { value: amount, permitSig } },\n * sender: evmAddress(walletClient.account.address),\n * })\n * )\n * .andThen(sendWith(walletClient))\n * .andThen(client.waitForTransaction);\n * ```\n *\n * @param walletClient - The wallet client to use for signing permits.\n * @param action - A function that returns an execution plan, accepting an optional permit signature.\n * @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.\n */\nexport function permitWith<E>(\n walletClient: WalletClient,\n action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>,\n): ResultAsync<ExecutionPlan, E | SignTypedDataError> {\n return action().andThen((result) => {\n if (supportsPermit(result)) {\n const permitTypedData = result.approvals[0].bySignature;\n // Sign and wrap with deadline\n return signTypedDataWith(walletClient, permitTypedData)\n .map((signature) => ({\n deadline: permitTypedData.message.deadline as number,\n value: signature,\n }))\n .andThen((permitSig) => action(permitSig));\n }\n return okAsync(result);\n });\n}\n"]}