@aave/client 4.0.0-next.8 → 4.0.0

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.
Files changed (54) hide show
  1. package/dist/{AaveClient-CgHY2iS9.d.ts → AaveClient-C7hQU3qX.d.ts} +14 -17
  2. package/dist/{AaveClient-L3v8kWvn.d.cts → AaveClient-wwfQOLJS.d.cts} +14 -17
  3. package/dist/actions/index.cjs +1 -1
  4. package/dist/actions/index.cjs.map +1 -1
  5. package/dist/actions/index.d.cts +485 -144
  6. package/dist/actions/index.d.ts +485 -144
  7. package/dist/actions/index.js +1 -1
  8. package/dist/chunk-HH6OAH2K.js +2 -0
  9. package/dist/chunk-HH6OAH2K.js.map +1 -0
  10. package/dist/chunk-N4LXBTGY.js +2 -0
  11. package/dist/chunk-N4LXBTGY.js.map +1 -0
  12. package/dist/chunk-SXZ2BGUZ.js +2 -0
  13. package/dist/chunk-SXZ2BGUZ.js.map +1 -0
  14. package/dist/ethers.cjs +1 -1
  15. package/dist/ethers.cjs.map +1 -1
  16. package/dist/ethers.d.cts +45 -11
  17. package/dist/ethers.d.ts +45 -11
  18. package/dist/ethers.js +1 -1
  19. package/dist/ethers.js.map +1 -1
  20. package/dist/index.cjs +2 -2
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +20 -3
  23. package/dist/index.d.ts +20 -3
  24. package/dist/index.js +2 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/privy.cjs +1 -2
  27. package/dist/privy.cjs.map +1 -1
  28. package/dist/privy.d.cts +49 -12
  29. package/dist/privy.d.ts +49 -12
  30. package/dist/privy.js +1 -1
  31. package/dist/privy.js.map +1 -1
  32. package/dist/testing.d.ts +3675 -29
  33. package/dist/testing.js +52 -289
  34. package/dist/testing.js.map +1 -1
  35. package/dist/thirdweb.cjs +1 -2
  36. package/dist/thirdweb.cjs.map +1 -1
  37. package/dist/thirdweb.d.cts +49 -20
  38. package/dist/thirdweb.d.ts +49 -20
  39. package/dist/thirdweb.js +1 -2
  40. package/dist/thirdweb.js.map +1 -1
  41. package/dist/types-XProSTZ7.d.cts +33 -0
  42. package/dist/types-XProSTZ7.d.ts +33 -0
  43. package/dist/viem.cjs +1 -2
  44. package/dist/viem.cjs.map +1 -1
  45. package/dist/viem.d.cts +51 -23
  46. package/dist/viem.d.ts +51 -23
  47. package/dist/viem.js +1 -1
  48. package/package.json +7 -6
  49. package/dist/chunk-3VL3Y3IZ.js +0 -2
  50. package/dist/chunk-3VL3Y3IZ.js.map +0 -1
  51. package/dist/chunk-X2C2UEY7.js +0 -3
  52. package/dist/chunk-X2C2UEY7.js.map +0 -1
  53. package/dist/types-Bu63z0x6.d.cts +0 -21
  54. package/dist/types-Bu63z0x6.d.ts +0 -21
package/dist/ethers.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { CancelError, SigningError, UnexpectedError, TransactionError } from '@aave/core';
2
- import { TransactionRequest, ExecutionPlan, SwapByIntentTypedData, CancelSwapTypedData } from '@aave/graphql';
2
+ import { ERC20PermitSignature, ExecutionPlan, TransactionRequest } from '@aave/graphql';
3
3
  import { ResultAsync } from '@aave/types';
4
4
  import { Signer, TransactionResponse } from 'ethers';
5
- import { T as TransactionResult, E as ExecutionPlanHandler, a as ERC20PermitHandler, S as SwapSignatureHandler } from './types-Bu63z0x6.js';
5
+ import { S as SignTypedDataError, E as ExecutionPlanHandler, T as TypedDataHandler, a as TypedData, b as TransactionResult } from './types-XProSTZ7.js';
6
6
 
7
7
  /**
8
8
  * @internal
@@ -21,18 +21,52 @@ declare function sendWith<T extends ExecutionPlan = ExecutionPlan>(signer: Signe
21
21
  */
22
22
  declare function sendWith<T extends ExecutionPlan = ExecutionPlan>(signer: Signer, result: T): ReturnType<ExecutionPlanHandler<T>>;
23
23
  /**
24
- * Creates an ERC20 permit handler that signs ERC20 permits using the provided ethers signer.
24
+ * Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided ethers signer.
25
+ *
26
+ * @param signer - The ethers signer to use for signing.
27
+ * @returns A function that takes typed data and returns a ResultAsync containing the raw signature.
28
+ *
29
+ * ```ts
30
+ * const result = await prepareSwapCancel(client, request)
31
+ * .andThen(signTypedDataWith(signer));
32
+ * ```
25
33
  */
26
- declare function signERC20PermitWith(signer: Signer): ERC20PermitHandler;
34
+ declare function signTypedDataWith(signer: Signer): TypedDataHandler;
27
35
  /**
28
- * @internal
29
- * Creates a swap signature handler that signs swap typed data using the provided ethers signer.
36
+ * Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided ethers signer.
37
+ *
38
+ * @param signer - The ethers signer to use for signing.
39
+ * @param data - The typed data to sign.
40
+ * @returns A ResultAsync containing the raw signature.
41
+ *
42
+ * ```ts
43
+ * const result = await signTypedDataWith(signer, typedData);
44
+ * ```
30
45
  */
31
- declare function signSwapTypedDataWith(signer: Signer): SwapSignatureHandler;
46
+ declare function signTypedDataWith(signer: Signer, data: TypedData): ReturnType<TypedDataHandler>;
32
47
  /**
33
- * @internal
34
- * Signs swap typed data using the provided ethers signer.
48
+ * Handles ERC20 permit signing for actions that require token approval.
49
+ *
50
+ * Calls the action to get an initial execution plan. If the plan requires ERC20 approval
51
+ * and the token supports permit signatures, signs the permit and re-calls the action
52
+ * with the signature to get a new plan that can be sent directly.
53
+ *
54
+ * ```ts
55
+ * const result = await permitWith(signer, (permitSig) =>
56
+ * supply(client, {
57
+ * reserve: reserve.id,
58
+ * amount: { erc20: { value: amount, permitSig } },
59
+ * sender: evmAddress(await signer.getAddress()),
60
+ * })
61
+ * )
62
+ * .andThen(sendWith(signer))
63
+ * .andThen(client.waitForTransaction);
64
+ * ```
65
+ *
66
+ * @param signer - The ethers signer to use for signing permits.
67
+ * @param action - A function that returns an execution plan, accepting an optional permit signature.
68
+ * @returns A ResultAsync containing the resolved ExecutionPlan ready to be sent with `sendWith`.
35
69
  */
36
- declare function signSwapTypedDataWith(signer: Signer, result: SwapByIntentTypedData | CancelSwapTypedData): ReturnType<SwapSignatureHandler>;
70
+ declare function permitWith<E>(signer: Signer, action: (permitSig?: ERC20PermitSignature) => ResultAsync<ExecutionPlan, E>): ResultAsync<ExecutionPlan, E | SignTypedDataError>;
37
71
 
38
- export { sendTransaction, sendWith, signERC20PermitWith, signSwapTypedDataWith, waitForTransactionResult };
72
+ export { permitWith, sendTransaction, sendWith, signTypedDataWith, waitForTransactionResult };
package/dist/ethers.js CHANGED
@@ -1,2 +1,2 @@
1
- import {UnexpectedError,TransactionError,CancelError,SigningError,ValidationError}from'@aave/core';import {ResultAsync,txHash,nonNullable,errAsync,okAsync,invariant,chainId,signatureFrom}from'@aave/types';import {isError}from'ethers';function x(e,n){return invariant(e.provider,"Detached signer, the signer MUST have a provider"),ResultAsync.fromPromise(e.provider.getNetwork(),r=>UnexpectedError.from(r)).andThen(r=>chainId(r.chainId)===n.chainId?okAsync(e):errAsync(new UnexpectedError(`Signer is on chain ${chainId(r.chainId)} but the request is for chain ${n.chainId}.`)))}function h(e,n){return ResultAsync.fromPromise(e.sendTransaction({to:n.to,data:n.data,value:n.value,from:n.from}),r=>isError(r,"ACTION_REJECTED")?CancelError.from(r):SigningError.from(r))}function P(e,n){return x(e,n).andThen(r=>h(e,n))}function w(e,n){return ResultAsync.fromPromise(n.wait(),r=>UnexpectedError.from(r)).andThen(r=>{let a=txHash(nonNullable(r?.hash));return r?.status===0?errAsync(TransactionError.new({txHash:a,request:e})):okAsync({txHash:a,operations:e.operations})})}function i(e,n){return P(e,n).andThen(r=>w(n,r))}function d(e,n){switch(n.__typename){case "TransactionRequest":return i(e,n);case "Erc20ApprovalRequired":case "PreContractActionRequired":return i(e,n.transaction).andThen(()=>i(e,n.originalTransaction));case "InsufficientBalanceError":return errAsync(ValidationError.fromGqlNode(n))}}function v(e,n){return n?d(e,n):d.bind(null,e)}function D(e,n){return ResultAsync.fromPromise(e.signTypedData(n.domain,n.types,n.message),r=>SigningError.from(r)).map(r=>({deadline:n.message.deadline,value:signatureFrom(r)}))}function I(e){return D.bind(null,e)}function u(e,n){let r=JSON.parse(n.message);return ResultAsync.fromPromise(e.signTypedData(n.domain,n.types,r),a=>SigningError.from(a)).map(a=>({deadline:r.deadline,value:signatureFrom(a)}))}function W(e,n){return n?u(e,n):u.bind(null,e)}export{P as sendTransaction,v as sendWith,I as signERC20PermitWith,W as signSwapTypedDataWith,w as waitForTransactionResult};//# sourceMappingURL=ethers.js.map
1
+ import {a}from'./chunk-N4LXBTGY.js';import {UnexpectedError,TransactionError,CancelError,SigningError,ValidationError}from'@aave/core';import {ResultAsync,txHash,nonNullable,errAsync,okAsync,signatureFrom,invariant,chainId}from'@aave/types';import {isError}from'ethers';function P(e,n){return invariant(e.provider,"Detached signer, the signer MUST have a provider"),ResultAsync.fromPromise(e.provider.getNetwork(),r=>UnexpectedError.from(r)).andThen(r=>chainId(r.chainId)===n.chainId?okAsync(e):errAsync(new UnexpectedError(`Signer is on chain ${chainId(r.chainId)} but the request is for chain ${n.chainId}.`)))}function A(e,n){return ResultAsync.fromPromise(e.sendTransaction({to:n.to,data:n.data,value:n.value,from:n.from}),r=>isError(r,"ACTION_REJECTED")?CancelError.from(r):SigningError.from(r))}function H(e,n){return P(e,n).andThen(r=>A(e,n))}function v(e,n){return ResultAsync.fromPromise(n.wait(),r=>UnexpectedError.from(r)).andThen(r=>{let a=txHash(nonNullable(r?.hash));return r?.status===0?errAsync(TransactionError.new({txHash:a,request:e})):okAsync({txHash:a,operations:e.operations})})}function i(e,n){return H(e,n).andThen(r=>v(n,r))}function y(e,n){switch(n.__typename){case "TransactionRequest":return i(e,n);case "Erc20ApprovalRequired":return n.approvals.reduce((r,a)=>r.andThen(()=>i(e,a.byTransaction)),okAsync(void 0)).andThen(()=>i(e,n.originalTransaction));case "PreContractActionRequired":return i(e,n.transaction).andThen(()=>i(e,n.originalTransaction));case "InsufficientBalanceError":return errAsync(ValidationError.fromGqlNode(n))}}function U(e,n){return n?y(e,n):y.bind(null,e)}function E(e,n){let r=n.domain,a=n.types,t=n.message;return ResultAsync.fromPromise(e.signTypedData(r,a,t),c=>isError(c,"ACTION_REJECTED")?CancelError.from(c):SigningError.from(c))}function C(e,n){return n===void 0?r=>E(e,r).map(signatureFrom):E(e,n).map(signatureFrom)}function k(e,n){return n().andThen(r=>{if(a(r)){let a=r.approvals[0].bySignature;return C(e,a).map(t=>({deadline:a.message.deadline,value:signatureFrom(t)})).andThen(t=>n(t))}return okAsync(r)})}export{k as permitWith,H as sendTransaction,U as sendWith,C as signTypedDataWith,v as waitForTransactionResult};//# sourceMappingURL=ethers.js.map
2
2
  //# sourceMappingURL=ethers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ethers.ts"],"names":["ensureChain","signer","request","invariant","ResultAsync","err","UnexpectedError","network","chainId","okAsync","errAsync","sendEip1559Transaction","isError","CancelError","SigningError","sendTransaction","_","waitForTransactionResult","response","receipt","hash","txHash","nonNullable","TransactionError","sendTransactionAndWait","tx","executePlan","result","ValidationError","sendWith","signERC20Permit","signature","signatureFrom","signERC20PermitWith","signSwapTypedData","message","signSwapTypedDataWith"],"mappings":"0OAgCA,SAASA,EACPC,CAAAA,CACAC,CAAAA,CACsC,CACtC,OAAAC,SAAAA,CACEF,EAAO,QAAA,CACP,kDACF,EAEOG,WAAAA,CAAY,WAAA,CAAYH,EAAO,QAAA,CAAS,UAAA,GAAeI,CAAAA,EAC5DC,eAAAA,CAAgB,KAAKD,CAAG,CAC1B,EAAE,OAAA,CAASE,CAAAA,EACLC,QAAQD,CAAAA,CAAQ,OAAO,IAAML,CAAAA,CAAQ,OAAA,CAChCO,QAAQR,CAAM,CAAA,CAEhBS,SACL,IAAIJ,eAAAA,CACF,sBAAsBE,OAAAA,CAAQD,CAAAA,CAAQ,OAAO,CAAC,CAAA,8BAAA,EAAiCL,EAAQ,OAAO,CAAA,CAAA,CAChG,CACF,CACD,CACH,CAEA,SAASS,CAAAA,CACPV,EACAC,CAAAA,CAC8D,CAC9D,OAAOE,WAAAA,CAAY,WAAA,CACjBH,EAA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K0B,CAAAA,GAAe,CACpB,QAAA,CAAUI,CAAAA,CAAQ,SAClB,KAAA,CAAOH,aAAAA,CAAcD,CAAS,CAChC,CAAA,CAAE,CACJ,CAeO,SAASK,EACdnC,CAAAA,CACA0B,CAAAA,CACyD,CACzD,OAAOA,CAAAA,CACHO,EAAkBjC,CAAAA,CAAQ0B,CAAM,EAChCO,CAAAA,CAAkB,IAAA,CAAK,IAAA,CAAMjC,CAAM,CACzC","file":"ethers.js","sourcesContent":["import {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n CancelSwapTypedData,\n ExecutionPlan,\n PermitTypedDataResponse,\n SwapByIntentTypedData,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n chainId,\n errAsync,\n invariant,\n nonNullable,\n okAsync,\n ResultAsync,\n signatureFrom,\n txHash,\n} from '@aave/types';\nimport { isError, type Signer, type TransactionResponse } from 'ethers';\nimport type {\n ERC20PermitHandler,\n ExecutionPlanHandler,\n SwapSignatureHandler,\n TransactionResult,\n} from './types';\n\nfunction ensureChain(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<Signer, UnexpectedError> {\n invariant(\n signer.provider,\n 'Detached signer, the signer MUST have a provider',\n );\n\n return ResultAsync.fromPromise(signer.provider.getNetwork(), (err) =>\n UnexpectedError.from(err),\n ).andThen((network) => {\n if (chainId(network.chainId) === request.chainId) {\n return okAsync(signer);\n }\n return errAsync(\n new UnexpectedError(\n `Signer is on chain ${chainId(network.chainId)} but the request is for chain ${request.chainId}.`,\n ),\n );\n });\n}\n\nfunction sendEip1559Transaction(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<TransactionResponse, CancelError | SigningError> {\n return ResultAsync.fromPromise(\n signer.sendTransaction({\n to: request.to,\n data: request.data,\n value: request.value,\n from: request.from,\n }),\n (err) => {\n if (isError(err, 'ACTION_REJECTED')) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n );\n}\n\n/**\n * @internal\n */\nexport function sendTransaction(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResponse,\n CancelError | SigningError | UnexpectedError\n> {\n return ensureChain(signer, request).andThen((_) =>\n sendEip1559Transaction(signer, request),\n );\n}\n\n/**\n * @internal\n */\nexport function waitForTransactionResult(\n request: TransactionRequest,\n response: TransactionResponse,\n): ResultAsync<TransactionResult, TransactionError | UnexpectedError> {\n return ResultAsync.fromPromise(response.wait(), (err) =>\n UnexpectedError.from(err),\n ).andThen((receipt) => {\n const hash = txHash(nonNullable(receipt?.hash));\n\n if (receipt?.status === 0) {\n return errAsync(\n TransactionError.new({\n txHash: hash,\n request,\n }),\n );\n }\n return okAsync({\n txHash: hash,\n operations: request.operations,\n });\n });\n}\n\nfunction sendTransactionAndWait(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResult,\n CancelError | SigningError | TransactionError | UnexpectedError\n> {\n return sendTransaction(signer, request).andThen((tx) =>\n waitForTransactionResult(request, tx),\n );\n}\n\nfunction executePlan(\n signer: Signer,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(signer, result);\n\n case 'Erc20ApprovalRequired':\n case 'PreContractActionRequired':\n return sendTransactionAndWait(signer, result.transaction).andThen(() =>\n sendTransactionAndWait(signer, 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 ethers signer.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n signer: Signer,\n): ExecutionPlanHandler<T>;\n/**\n * Sends execution plan transactions using the provided ethers signer.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n signer: Signer,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n signer: Signer,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result ? executePlan(signer, result) : executePlan.bind(null, signer);\n}\n\nfunction signERC20Permit(\n signer: Signer,\n result: PermitTypedDataResponse,\n): ReturnType<ERC20PermitHandler> {\n return ResultAsync.fromPromise(\n signer.signTypedData(result.domain, result.types, result.message),\n (err) => SigningError.from(err),\n ).map((signature) => ({\n deadline: result.message.deadline,\n value: signatureFrom(signature),\n }));\n}\n\n/**\n * Creates an ERC20 permit handler that signs ERC20 permits using the provided ethers signer.\n */\nexport function signERC20PermitWith(signer: Signer): ERC20PermitHandler {\n return signERC20Permit.bind(null, signer);\n}\n\nfunction signSwapTypedData(\n signer: Signer,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler> {\n const message = JSON.parse(result.message);\n return ResultAsync.fromPromise(\n signer.signTypedData(result.domain, result.types, message),\n (err) => SigningError.from(err),\n ).map((signature) => ({\n deadline: message.deadline,\n value: signatureFrom(signature),\n }));\n}\n\n/**\n * @internal\n * Creates a swap signature handler that signs swap typed data using the provided ethers signer.\n */\nexport function signSwapTypedDataWith(signer: Signer): SwapSignatureHandler;\n/**\n * @internal\n * Signs swap typed data using the provided ethers signer.\n */\nexport function signSwapTypedDataWith(\n signer: Signer,\n result: SwapByIntentTypedData | CancelSwapTypedData,\n): ReturnType<SwapSignatureHandler>;\nexport function signSwapTypedDataWith(\n signer: Signer,\n result?: SwapByIntentTypedData | CancelSwapTypedData,\n): SwapSignatureHandler | ReturnType<SwapSignatureHandler> {\n return result\n ? signSwapTypedData(signer, result)\n : signSwapTypedData.bind(null, signer);\n}\n"]}
1
+ {"version":3,"sources":["../src/ethers.ts"],"names":["ensureChain","signer","request","invariant","ResultAsync","err","UnexpectedError","network","chainId","okAsync","errAsync","sendEip1559Transaction","isError","CancelError","SigningError","sendTransaction","_","waitForTransactionResult","response","receipt","hash","txHash","nonNullable","TransactionError","sendTransactionAndWait","tx","executePlan","result","chain","approval","ValidationError","sendWith","signTypedData","data","domain","types","message","signTypedDataWith","typedData","signatureFrom","permitWith","action","supportsPermit","permitTypedData","signature","permitSig"],"mappings":"8QAsCA,SAASA,CAAAA,CACPC,CAAAA,CACAC,CAAAA,CACsC,CACtC,OAAAC,SAAAA,CACEF,CAAAA,CAAO,QAAA,CACP,kDACF,CAAA,CAEOG,YAAY,WAAA,CAAYH,CAAAA,CAAO,QAAA,CAAS,UAAA,EAAW,CAAII,CAAAA,EAC5DC,gBAAgB,IAAA,CAAKD,CAAG,CAC1B,CAAA,CAAE,OAAA,CAASE,GACLC,OAAAA,CAAQD,CAAAA,CAAQ,OAAO,CAAA,GAAML,CAAAA,CAAQ,OAAA,CAChCO,QAAQR,CAAM,CAAA,CAEhBS,SACL,IAAIJ,eAAAA,CACF,sBAAsBE,OAAAA,CAAQD,CAAAA,CAAQ,OAAO,CAAC,CAAA,8BAAA,EAAiCL,CAAAA,CAAQ,OAAO,CAAA,CAAA,CAChG,CACF,CACD,CACH,CAEA,SAASS,CAAAA,CACPV,CAAAA,CACAC,CAAAA,CAC8D,CAC9D,OAAOE,WAAAA,CAAY,YACjBH,CAAAA,CAAO,eAAA,CAAgB,CACrB,EAAA,CAAIC,CAAAA,CAAQ,EAAA,CACZ,KAAMA,CAAAA,CAAQ,IAAA,CACd,KAAA,CAAOA,CAAAA,CAAQ,KAAA,CACf,IAAA,CAAMA,EAAQ,IAChB,CAAC,EACAG,CAAAA,EACKO,OAAAA,CAAQP,EAAK,iBAAiB,CAAA,CACzBQ,WAAAA,CAAY,IAAA,CAAKR,CAAG,CAAA,CAEtBS,aAAa,IAAA,CAAKT,CAAG,CAEhC,CACF,CAKO,SAASU,CAAAA,CACdd,CAAAA,CACAC,CAAAA,CAIA,CACA,OAAOF,CAAAA,CAAYC,EAAQC,CAAO,CAAA,CAAE,QAASc,CAAAA,EAC3CL,CAAAA,CAAuBV,EAAQC,CAAO,CACxC,CACF,CAKO,SAASe,CAAAA,CACdf,EACAgB,CAAAA,CACoE,CACpE,OAAOd,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Q0C,CAAe,CAAA,CAC7C,IAAKC,CAAAA,GAAe,CACnB,SAAUD,CAAAA,CAAgB,OAAA,CAAQ,SAClC,KAAA,CAAOJ,aAAAA,CAAcK,CAAS,CAChC,CAAA,CAAE,CAAA,CACD,QAASC,CAAAA,EAAcJ,CAAAA,CAAOI,CAAS,CAAC,CAC7C,CACA,OAAOpC,OAAAA,CAAQkB,CAAM,CACvB,CAAC,CACH","file":"ethers.js","sourcesContent":["import {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n ERC20PermitSignature,\n ExecutionPlan,\n TransactionRequest,\n} from '@aave/graphql';\nimport {\n chainId,\n errAsync,\n invariant,\n nonNullable,\n okAsync,\n ResultAsync,\n signatureFrom,\n txHash,\n} from '@aave/types';\nimport {\n isError,\n type Signer,\n type TransactionResponse,\n type TypedDataDomain,\n type TypedDataField,\n} from 'ethers';\nimport { supportsPermit } from './adapters';\nimport type {\n ExecutionPlanHandler,\n SignTypedDataError,\n TransactionResult,\n TypedData,\n TypedDataHandler,\n} from './types';\n\nfunction ensureChain(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<Signer, UnexpectedError> {\n invariant(\n signer.provider,\n 'Detached signer, the signer MUST have a provider',\n );\n\n return ResultAsync.fromPromise(signer.provider.getNetwork(), (err) =>\n UnexpectedError.from(err),\n ).andThen((network) => {\n if (chainId(network.chainId) === request.chainId) {\n return okAsync(signer);\n }\n return errAsync(\n new UnexpectedError(\n `Signer is on chain ${chainId(network.chainId)} but the request is for chain ${request.chainId}.`,\n ),\n );\n });\n}\n\nfunction sendEip1559Transaction(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<TransactionResponse, CancelError | SigningError> {\n return ResultAsync.fromPromise(\n signer.sendTransaction({\n to: request.to,\n data: request.data,\n value: request.value,\n from: request.from,\n }),\n (err) => {\n if (isError(err, 'ACTION_REJECTED')) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n );\n}\n\n/**\n * @internal\n */\nexport function sendTransaction(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResponse,\n CancelError | SigningError | UnexpectedError\n> {\n return ensureChain(signer, request).andThen((_) =>\n sendEip1559Transaction(signer, request),\n );\n}\n\n/**\n * @internal\n */\nexport function waitForTransactionResult(\n request: TransactionRequest,\n response: TransactionResponse,\n): ResultAsync<TransactionResult, TransactionError | UnexpectedError> {\n return ResultAsync.fromPromise(response.wait(), (err) =>\n UnexpectedError.from(err),\n ).andThen((receipt) => {\n const hash = txHash(nonNullable(receipt?.hash));\n\n if (receipt?.status === 0) {\n return errAsync(\n TransactionError.new({\n txHash: hash,\n request,\n }),\n );\n }\n return okAsync({\n txHash: hash,\n operations: request.operations,\n });\n });\n}\n\nfunction sendTransactionAndWait(\n signer: Signer,\n request: TransactionRequest,\n): ResultAsync<\n TransactionResult,\n CancelError | SigningError | TransactionError | UnexpectedError\n> {\n return sendTransaction(signer, request).andThen((tx) =>\n waitForTransactionResult(request, tx),\n );\n}\n\nfunction executePlan(\n signer: Signer,\n result: ExecutionPlan,\n): ReturnType<ExecutionPlanHandler> {\n switch (result.__typename) {\n case 'TransactionRequest':\n return sendTransactionAndWait(signer, result);\n\n case 'Erc20ApprovalRequired':\n return result.approvals\n .reduce<ReturnType<typeof sendTransactionAndWait>>(\n (chain, approval) =>\n chain.andThen(() =>\n sendTransactionAndWait(signer, approval.byTransaction),\n ),\n okAsync(undefined as never),\n )\n .andThen(() =>\n sendTransactionAndWait(signer, result.originalTransaction),\n );\n\n case 'PreContractActionRequired':\n return sendTransactionAndWait(signer, result.transaction).andThen(() =>\n sendTransactionAndWait(signer, 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 ethers signer.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n signer: Signer,\n): ExecutionPlanHandler<T>;\n/**\n * Sends execution plan transactions using the provided ethers signer.\n */\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n signer: Signer,\n result: T,\n): ReturnType<ExecutionPlanHandler<T>>;\nexport function sendWith<T extends ExecutionPlan = ExecutionPlan>(\n signer: Signer,\n result?: T,\n): ExecutionPlanHandler<T> | ReturnType<ExecutionPlanHandler<T>> {\n return result ? executePlan(signer, result) : executePlan.bind(null, signer);\n}\n\nfunction signTypedData(\n signer: Signer,\n data: TypedData,\n): ResultAsync<string, CancelError | SigningError> {\n // Cast to ethers types since TypedData uses JsonObject for types/domain/message\n const domain = data.domain as unknown as TypedDataDomain;\n const types = data.types as unknown as Record<string, TypedDataField[]>;\n const message = data.message as unknown as Record<string, unknown>;\n\n return ResultAsync.fromPromise(\n signer.signTypedData(domain, types, message),\n (err) => {\n if (isError(err, 'ACTION_REJECTED')) {\n return CancelError.from(err);\n }\n return SigningError.from(err);\n },\n );\n}\n\n/**\n * Creates a function that signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided ethers signer.\n *\n * @param signer - The ethers signer 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(signer));\n * ```\n */\nexport function signTypedDataWith(signer: Signer): TypedDataHandler;\n\n/**\n * Signs EIP-712 typed data (ERC-20 permits, swap intents, etc.) using the provided ethers signer.\n *\n * @param signer - The ethers signer 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(signer, typedData);\n * ```\n */\nexport function signTypedDataWith(\n signer: Signer,\n data: TypedData,\n): ReturnType<TypedDataHandler>;\n\nexport function signTypedDataWith(\n signer: Signer,\n data?: TypedData,\n): TypedDataHandler | ReturnType<TypedDataHandler> {\n if (data === undefined) {\n return (typedData: TypedData) =>\n signTypedData(signer, typedData).map(signatureFrom);\n }\n return signTypedData(signer, data).map(signatureFrom);\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(signer, (permitSig) =>\n * supply(client, {\n * reserve: reserve.id,\n * amount: { erc20: { value: amount, permitSig } },\n * sender: evmAddress(await signer.getAddress()),\n * })\n * )\n * .andThen(sendWith(signer))\n * .andThen(client.waitForTransaction);\n * ```\n *\n * @param signer - The ethers signer 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 signer: Signer,\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(signer, permitTypedData)\n .map((signature) => ({\n deadline: permitTypedData.message.deadline as number,\n value: signatureFrom(signature),\n }))\n .andThen((permitSig) => action(permitSig));\n }\n return okAsync(result);\n });\n}\n"]}
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var core=require('@aave/core'),graphql=require('@aave/graphql'),types=require('@aave/types'),b=require('@aave/graphql/schema'),exchangeGraphcache=require('@urql/exchange-graphcache');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var b__default=/*#__PURE__*/_interopDefault(b);var _={currency:graphql.Currency.Usd,timeWindow:graphql.TimeWindow.LastDay,requestPolicy:"cache-and-network",batch:true};function f(e,t){return e.query(graphql.HasProcessedKnownTransactionQuery,{request:t},{requestPolicy:"network-only",batch:false})}var y=(e,t,n,a)=>BigInt(e[a.fieldName]),s=(e,t,n,a)=>types.BigDecimal.new(e[a.fieldName]),l=(e,t,n,a)=>{let i=e[a.fieldName];return i==null?null:s(e,t,n,a)},r=(e,t,n,a)=>new Date(e[a.fieldName]),U=(e,t,n,a)=>{let i=e[a.fieldName];return i==null?null:r(e,t,n,a)},h=exchangeGraphcache.cacheExchange({schema:b__default.default,resolvers:{PercentNumber:{onChainValue:y,value:s,normalized:s},DecimalNumber:{onChainValue:y,value:s},ExchangeAmount:{value:s},AssetPriceSample:{price:s,date:r},Reserve:{borrowCap:s,supplyCap:s},HealthFactorError:{current:l,after:l},HealthFactorVariation:{current:l,after:l},HealthFactorWithChange:{current:l},UserSummary:{lowestHealthFactor:l},UserSummaryHistoryItem:{healthFactor:l,date:r},TransactionRequest:{value:y},ApySample:{date:r},AssetBorrowSample:{date:r},AssetSupplySample:{date:r},ProtocolHistorySample:{date:r},BorrowActivity:{timestamp:r},LiquidatedActivity:{timestamp:r},RepayActivity:{timestamp:r},SupplyActivity:{timestamp:r},WithdrawActivity:{timestamp:r},UsingAsCollateralActivity:{timestamp:r},UpdatedDynamicConfigActivity:{timestamp:r},UpdatedRiskPremiumActivity:{timestamp:r},SpokeUserPositionManager:{approvedOn:r},SwapCancelled:{createdAt:r,cancelledAt:U},SwapExpired:{createdAt:r,expiredAt:r},SwapFulfilled:{createdAt:r,fulfilledAt:r},SwapOpen:{createdAt:r,deadline:r},SwapPendingSignature:{createdAt:r,deadline:r},SwapReceipt:{createdAt:r},Query:{hub:(e,{request:t})=>graphql.isHubInputVariant(t.query)?{__typename:"Hub",id:graphql.encodeHubId(t.query.hubInput)}:{__typename:"Hub",id:t.query.hubId},activities:(e,t,n)=>{if(!graphql.isTxHashInputVariant(t.request.query))return n.resolve("Query","activities",t);let{txHash:a,chainId:i}=t.request.query.txHash,m=n.inspectFields("Query").filter(o=>o.fieldName==="activities").reduce((o,d)=>{let u=n.resolve("Query",d.fieldKey);if(!u)return o;let p=n.resolve(u,"items");if(!p)return o;for(let c of p)o.add(c);return o},new Set).values().toArray().filter(o=>{if(n.resolve(o,"txHash")!==a)return false;let u=n.resolve(o,"spoke");if(u){let p=n.resolve(u,"chain"),c=p?n.resolve(p,"chainId"):void 0;if(typeof c=="number")return c===i}return true});if(m.length!==0)return {__typename:"PaginatedActivitiesResult",items:m,pageInfo:{__typename:"PaginatedResultInfo",prev:null,next:null}}}}},keys:{Hub:e=>e.id,HubAsset:e=>e.id,Reserve:e=>e.id,ReserveInfo:e=>e.id,Spoke:e=>e.id,BorrowActivity:e=>e.id,LiquidatedActivity:e=>e.id,SupplyActivity:e=>e.id,SwapByIntent:e=>e.quote.quoteId,SwapByIntentWithApprovalRequired:e=>e.quote.quoteId,SwapByTransaction:e=>e.quote.quoteId,UserPosition:e=>e.id,UpdatedDynamicConfigActivity:e=>e.id,UpdatedRiskPremiumActivity:e=>e.id,UsingAsCollateralActivity:e=>e.id,WithdrawActivity:e=>e.id,RepayActivity:e=>e.id,TokenInfo:e=>e.id,Erc20Token:e=>e.address,Chain:e=>e.chainId.toString(),NativeToken:e=>e.chain.chainId.toString(),PaginatedActivitiesResult:()=>null,PaginatedResultInfo:()=>null,PaginatedSpokePositionManagerResult:()=>null,PaginatedSpokeUserPositionManagerResult:()=>null,PaginatedUserSwapsResult:()=>null,SpokePositionManger:()=>null,SpokeUserPositionManager:()=>null,SwapReceipt:()=>null,SwapTransactionRequest:()=>null,ApySample:()=>null,Asset:()=>null,AssetBorrowSample:()=>null,AssetPriceSample:()=>null,AssetSummary:()=>null,AssetSupplySample:()=>null,CancelSwapTypedData:()=>null,CancelSwapTypeDefinition:()=>null,DecimalNumber:()=>null,DecimalNumberWithChange:()=>null,DomainData:()=>null,Erc20Amount:()=>null,Erc20ApprovalRequired:()=>null,ExchangeAmount:()=>null,ExchangeAmountValueVariation:()=>null,ExchangeAmountWithChange:()=>null,ForkTopUpResponse:()=>null,HealthFactorError:()=>null,HealthFactorVariation:()=>null,HealthFactorWithChange:()=>null,HubAssetSettings:()=>null,HubAssetSummary:()=>null,HubAssetUserState:()=>null,HubSummary:()=>null,InsufficientBalanceError:()=>null,NativeAmount:()=>null,PercentNumber:()=>null,PercentNumberVariation:()=>null,PercentNumberWithChange:()=>null,PermitMessageData:()=>null,PermitTypedDataResponse:()=>null,PreContractActionRequired:()=>null,PrepareSwapCancelResult:()=>null,PreviewUserPosition:()=>null,ProtocolHistorySample:()=>null,ReserveSettings:()=>null,ReserveStatus:()=>null,ReserveSummary:()=>null,ReserveUserState:()=>null,SwapApprovalRequired:()=>null,SwapByIntentTypedData:()=>null,SwapByIntentTypeDefinition:()=>null,SwapCancelled:()=>null,SwapExpired:()=>null,SwapFulfilled:()=>null,SwapOpen:()=>null,SwapPendingSignature:()=>null,SwapQuote:()=>null,SwapQuoteCosts:()=>null,TransactionRequest:()=>null,TypeDefinition:()=>null,TypeField:()=>null,UserBalance:()=>null,UserBorrowItem:()=>null,UserSummary:()=>null,UserSummaryHistoryItem:()=>null,UserSupplyItem:()=>null}});var v={name:"production",backend:"https://api.v4.aave.com/graphql",indexingTimeout:6e4,pollingInterval:100,exchangeRateInterval:1e4},j={name:"staging",backend:"https://api.v4.staging.aave.com/graphql",indexingTimeout:6e4,pollingInterval:500,exchangeRateInterval:1e4},J={name:"local",backend:"http://localhost:3007/graphql",indexingTimeout:6e4,pollingInterval:1e3,exchangeRateInterval:1e4};function g({environment:e=v,headers:t,cache:n=true,debug:a=false,fragments:i=[]}){return {displayName:"AaveClient",environment:e,headers:t,cache:n?h:null,debug:a,fragments:i}}function A(e){return e.operations!==null&&e.operations.length>0}var x=class e extends core.GqlClient{static create(t){return new e(g(t??{}))}waitForTransaction=t=>(types.invariant(A(t),"Received a transaction result for an untracked operation. Make sure you're following the instructions in the docs."),types.ResultAsync.fromPromise(this.pollTransactionStatus(t),n=>n instanceof core.TimeoutError||n instanceof core.UnexpectedError?n:core.UnexpectedError.from(n)));async refreshQueryWhere(t,n){await this.refreshWhere(async a=>{if(a.query===t){let i=await this.query(t,a.variables,{requestPolicy:"cache-only"});return i.isErr()?false:n(a.variables,i.value)}return false});}async pollTransactionStatus(t){let n=Date.now();for(;Date.now()-n<this.context.environment.indexingTimeout;){if(await f(this,t).match(i=>i,i=>{throw i}))return t.txHash;await core.delay(this.context.environment.pollingInterval);}throw core.TimeoutError.from(`Timeout waiting for transaction ${t.txHash} to be processed.`)}};
2
- exports.AaveClient=x;exports.DEFAULT_QUERY_OPTIONS=_;exports.local=J;exports.production=v;exports.staging=j;Object.keys(core).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return core[k]}})});Object.keys(graphql).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return graphql[k]}})});Object.keys(types).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return types[k]}})});//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var core=require('@aave/core'),graphql=require('@aave/graphql'),types=require('@aave/types'),q=require('@aave/graphql/schema'),exchangeGraphcache=require('@urql/exchange-graphcache');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var q__default=/*#__PURE__*/_interopDefault(q);var L={currency:graphql.Currency.Usd,timeWindow:graphql.TimeWindow.LastDay,requestPolicy:"cache-and-network",batch:true};function S(e,r){return e.query(graphql.HasProcessedKnownTransactionQuery,{request:r},{requestPolicy:"network-only",batch:false})}var y=(e,r,n,a)=>BigInt(e[a.fieldName]),s=(e,r,n,a)=>types.BigDecimal.new(e[a.fieldName]),p=(e,r,n,a)=>{let i=e[a.fieldName];return i==null?null:s(e,r,n,a)},t=(e,r,n,a)=>new Date(e[a.fieldName]),l=(e,r,n,a)=>{let i=e[a.fieldName];return i==null?null:t(e,r,n,a)},R=exchangeGraphcache.cacheExchange({schema:q__default.default,resolvers:{PercentNumber:{onChainValue:y,value:s,normalized:s},DecimalNumber:{onChainValue:y,value:s},ExchangeAmount:{value:s},AssetPriceSample:{price:s,date:t},PermitTypedData:{signedAmount:s},HealthFactorError:{current:p,after:p},HealthFactorVariation:{current:p,after:p},HealthFactorWithChange:{current:p},UserSummary:{lowestHealthFactor:p},UserSummaryHistoryItem:{healthFactor:p,date:t},TransactionRequest:{value:y},ApySample:{date:t},AssetBorrowSample:{date:t},AssetSupplySample:{date:t},HubSummarySample:{date:t},BorrowPointsReward:{startDate:t,endDate:l},PreviewBorrowPointsReward:{startDate:t,endDate:l},PreviewMerklBorrowReward:{startDate:t,endDate:t},PreviewMerklSupplyReward:{startDate:t,endDate:t},PreviewSupplyPointsReward:{startDate:t,endDate:l},SupplyPointsReward:{startDate:t,endDate:l},ProtocolHistorySample:{date:t},BorrowActivity:{timestamp:t},LiquidatedActivity:{timestamp:t},MerklBorrowReward:{startDate:t,endDate:t},MerklSupplyReward:{startDate:t,endDate:t},RepayActivity:{timestamp:t},SupplyActivity:{timestamp:t},WithdrawActivity:{timestamp:t},UsingAsCollateralActivity:{timestamp:t},UpdatedDynamicConfigActivity:{timestamp:t},UpdatedRiskPremiumActivity:{timestamp:t},TokenSwapActivity:{timestamp:t},SupplySwapActivity:{timestamp:t},BorrowSwapActivity:{timestamp:t},RepayWithSupplyActivity:{timestamp:t},WithdrawSwapActivity:{timestamp:t},UserMerklClaimableReward:{startDate:t,endDate:t,claimUntil:t},UserPosition:{createdAt:t},UserBorrowItem:{createdAt:l},UserSupplyItem:{createdAt:l},SpokeUserPositionManager:{approvedOn:t},SwapCancelled:{createdAt:t,cancelledAt:l},SwapCancelledResult:{createdAt:t,cancelledAt:l},SwapExpired:{createdAt:t,expiredAt:t},SwapFulfilled:{createdAt:t,fulfilledAt:t},SwapOpen:{createdAt:t,deadline:t},SwapPendingSignature:{createdAt:t,deadline:t},SwapReceipt:{createdAt:t},StableVaultSummary:{shares:y,totalDeposits:s,userCount:y},StableVaultWithdrawClaim:{executableAfter:t},TokenMovementRecord:{timestamp:t},StableVaultPendingAvailability:{executableAfter:t},Query:{hub:(e,{request:r})=>graphql.isHubInputVariant(r.query)?{__typename:"Hub",id:graphql.encodeHubId(r.query.hubInput)}:{__typename:"Hub",id:r.query.hubId},reserve:(e,{request:r})=>graphql.isReserveInputVariant(r.query)?{__typename:"Reserve",id:graphql.encodeReserveId(r.query.reserveInput)}:{__typename:"Reserve",id:r.query.reserveId},userPosition:(e,{request:r})=>{if("userSpoke"in r&&r.userSpoke){let{chainId:n,address:a}=graphql.decodeSpokeId(r.userSpoke.spoke);return {__typename:"UserPosition",id:graphql.encodeUserPositionId({chainId:n,spoke:a,user:r.userSpoke.user})}}if("id"in r&&r.id)return {__typename:"UserPosition",id:r.id}},activities:(e,r,n)=>{if(!graphql.isTxHashInputVariant(r.request.query))return n.resolve("Query","activities",r);let{txHash:a,chainId:i}=r.request.query.txHash,v=n.inspectFields("Query").filter(o=>o.fieldName==="activities").reduce((o,w)=>{let u=n.resolve("Query",w.fieldKey);if(!u)return o;let c=n.resolve(u,"items");if(!c)return o;for(let d of c)o.add(d);return o},new Set).values().toArray().filter(o=>{if(n.resolve(o,"txHash")!==a)return false;let u=n.resolve(o,"spoke");if(u){let c=n.resolve(u,"chain"),d=c?n.resolve(c,"chainId"):void 0;if(typeof d=="number")return d===i}return true});if(v.length!==0)return {__typename:"PaginatedActivitiesResult",items:v,pageInfo:{__typename:"PaginatedResultInfo",prev:null,next:null}}}}},keys:{Asset:e=>e.id,BorrowActivity:e=>e.id,BorrowPointsReward:e=>e.id,BorrowSwapActivity:e=>e.id,BoostedRate:e=>e.id,Hub:e=>e.id,HubAsset:e=>e.id,LiquidatedActivity:e=>e.id,MerklBorrowReward:e=>e.id,MerklGenericCriteria:e=>e.id,MerklSupplyReward:e=>e.id,PointsGenericCriteria:e=>e.id,PointsProgram:e=>e.id,RepayActivity:e=>e.id,RepayWithSupplyActivity:e=>e.id,Reserve:e=>e.id,ReserveInfo:e=>e.id,Spoke:e=>e.id,StableVault:e=>e.id,StableVaultUserPosition:e=>e.id,SupplyActivity:e=>e.id,SupplyPointsReward:e=>e.id,SupplySwapActivity:e=>e.id,TokenInfo:e=>e.id,TokenMovementRecord:e=>e.id,TokenSwapActivity:e=>e.id,UpdatedDynamicConfigActivity:e=>e.id,UpdatedRiskPremiumActivity:e=>e.id,UserMerklClaimableReward:e=>e.id,UserPosition:e=>e.id,UsingAsCollateralActivity:e=>e.id,WithdrawActivity:e=>e.id,WithdrawSwapActivity:e=>e.id,Erc20Token:e=>e.address,Chain:e=>e.chainId.toString(),NativeToken:e=>e.chain.chainId.toString(),ApySample:()=>null,AssetAmountWithChange:()=>null,AssetBorrowSample:()=>null,AssetPriceSample:()=>null,AssetSampleBreakdown:()=>null,AssetSummary:()=>null,AssetSupplySample:()=>null,BorrowSwap:()=>null,BorrowSwapQuoteResult:()=>null,CollateralFactorVariation:()=>null,DecimalNumber:()=>null,DecimalNumberWithChange:()=>null,DomainData:()=>null,Erc20Amount:()=>null,Erc20Approval:()=>null,Erc20ApprovalRequired:()=>null,ExchangeAmount:()=>null,ExchangeAmountVariation:()=>null,ExchangeAmountWithChange:()=>null,ForkTopUpResponse:()=>null,HealthFactorError:()=>null,HealthFactorVariation:()=>null,HealthFactorWithChange:()=>null,HubAssetInterestRateModelPoint:()=>null,HubAssetInterestRateModelResult:()=>null,HubAssetSettings:()=>null,HubAssetSummary:()=>null,HubAssetUserState:()=>null,HubSummary:()=>null,HubSummarySample:()=>null,InsufficientBalanceError:()=>null,InsufficientLiquidityError:()=>null,LiquidationFeeVariation:()=>null,MaxLiquidationBonusVariation:()=>null,NativeAmount:()=>null,PaginatedActivitiesResult:()=>null,PaginatedResultInfo:()=>null,PaginatedSpokePositionManagerResult:()=>null,PaginatedSpokeUserPositionManagerResult:()=>null,PaginatedStableVaultMovementsResult:()=>null,PaginatedStableVaultRateUsersResult:()=>null,PaginatedUserSwapsResult:()=>null,PercentNumber:()=>null,PercentNumberChangeSnapshot:()=>null,PercentNumberVariation:()=>null,PercentNumberWithChange:()=>null,PermitTypedData:()=>null,PositionAmount:()=>null,PositionSwapAdapterContractApproval:()=>null,PositionSwapByIntentApprovalsRequired:()=>null,PositionSwapPositionManagerApproval:()=>null,PreContractActionRequired:()=>null,PrepareSwapCancelResult:()=>null,PrepareSwapOrder:()=>null,PreviewBorrowPointsReward:()=>null,PreviewMerklBorrowReward:()=>null,PreviewMerklSupplyReward:()=>null,PreviewReserveRates:()=>null,PreviewRewardOutcome:()=>null,PreviewSupplyPointsReward:()=>null,PreviewUserPosition:()=>null,ProtocolHistorySample:()=>null,RepayWithSupply:()=>null,RepayWithSupplyQuoteResult:()=>null,ReserveSettings:()=>null,ReserveStatus:()=>null,ReserveSummary:()=>null,ReserveUserState:()=>null,SpokePositionManager:()=>null,SpokeUserPositionManager:()=>null,StableVaultPendingAvailability:()=>null,StableVaultRates:()=>null,StableVaultSummary:()=>null,StableVaultWithdrawClaim:()=>null,SupplySwap:()=>null,SupplySwapQuoteResult:()=>null,SwapByIntent:()=>null,SwapByIntentWithApprovalRequired:()=>null,SwapByTransaction:()=>null,SwapCancelled:()=>null,SwapCancelledResult:()=>null,SwapExpired:()=>null,SwapFulfilled:()=>null,SwapOpen:()=>null,SwapPendingSignature:()=>null,SwapQuote:()=>null,SwapQuoteCosts:()=>null,SwapReceipt:()=>null,SwapTransactionRequest:()=>null,SwapTypedData:()=>null,TokenMovementAllocate:()=>null,TokenMovementBridgeIn:()=>null,TokenMovementBridgeOut:()=>null,TokenMovementDeallocate:()=>null,TokenMovementRebalance:()=>null,TokenMovementSwap:()=>null,TokenSwap:()=>null,TokenSwapQuoteResult:()=>null,TransactionRequest:()=>null,UserBalance:()=>null,UserBorrowItem:()=>null,UserPositionRiskPremium:()=>null,UserRiskPremiumBreakdownItem:()=>null,UserSummary:()=>null,UserSummaryHistoryItem:()=>null,UserSupplyItem:()=>null,WithdrawSwap:()=>null,WithdrawSwapQuoteResult:()=>null}});var A={name:"production",backend:"https://api.aave.com/graphql",indexingTimeout:6e4,pollingInterval:100,exchangeRateInterval:1e4,swapQuoteInterval:3e4,swapStatusInterval:5e3},ne={name:"staging",backend:"https://api.staging.aave.com/graphql",indexingTimeout:6e4,pollingInterval:500,exchangeRateInterval:1e4,swapQuoteInterval:3e4,swapStatusInterval:5e3},ae={name:"local",backend:"http://localhost:3007/graphql",indexingTimeout:6e4,pollingInterval:1e3,exchangeRateInterval:1e4,swapQuoteInterval:3e4,swapStatusInterval:5e3};function f({environment:e=A,headers:r,cache:n=true,batch:a=true,debug:i=false}){return {displayName:"AaveClient",environment:e,headers:r,cache:n?R:null,batch:a,debug:i}}function h(e){return e.operations!==null&&e.operations.length>0}function m(e){return {__typename:"TransactionReceipt",txHash:e}}var T=class e extends core.GqlClient{static create(r){return new e(f(r??{}))}waitForTransaction=r=>(types.invariant(h(r),"AaveClient.waitForTransaction called with an non-tracked operation. See the documentation for correct tracking setup."),types.ResultAsync.fromPromise(this.pollTransactionStatus(r),n=>n instanceof core.TimeoutError||n instanceof core.UnexpectedError?n:core.UnexpectedError.from(n)));async pollTransactionStatus(r){let n=Date.now();for(;Date.now()-n<this.context.environment.indexingTimeout;){if(await S(this,r).match(i=>i,i=>{throw i}))return m(r.txHash);await core.delay(this.context.environment.pollingInterval);}throw core.TimeoutError.from(`Timeout waiting for transaction ${r.txHash} to be processed.`)}};function F(e){return typeof e=="object"&&e!==null&&"approvals"in e&&Array.isArray(e.approvals)}function Se(e){return F(e)&&types.isOneEntryArray(e.approvals)&&!!e.approvals[0].bySignature}
2
+ exports.AaveClient=T;exports.DEFAULT_QUERY_OPTIONS=L;exports.local=ae;exports.production=A;exports.staging=ne;exports.supportsPermit=Se;exports.transactionReceipt=m;Object.keys(core).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return core[k]}})});Object.keys(graphql).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return graphql[k]}})});Object.keys(types).forEach(function(k){if(k!=='default'&&!Object.prototype.hasOwnProperty.call(exports,k))Object.defineProperty(exports,k,{enumerable:true,get:function(){return types[k]}})});//# sourceMappingURL=index.cjs.map
3
3
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/options.ts","../src/actions/misc.ts","../src/cache.ts","../src/environments.ts","../src/config.ts","../src/types.ts","../src/AaveClient.ts"],"names":["DEFAULT_QUERY_OPTIONS","Currency","TimeWindow","hasProcessedKnownTransaction","client","request","HasProcessedKnownTransactionQuery","transformToBigInt","parent","_args","_cache","info","transformToBigDecimal","BigDecimal","transformToNullableBigDecimal","value","transformToDate","transformToNullableDate","exchange","cacheExchange","introspectedSchema","_","isHubInputVariant","encodeHubId","_parent","args","cache","isTxHashInputVariant","txHash","chainId","matches","f","set","pageRef","itemRefs","ref","spokeRef","chainRef","itemChainId","data","production","staging","local","configureContext","environment","headers","debug","fragments","isHasProcessedKnownTransactionRequest","result","AaveClient","_AaveClient","GqlClient","options","invariant","ResultAsync","err","TimeoutError","UnexpectedError","document","predicate","op","startedAt","ok","delay"],"mappings":"oTA+CO,IAAMA,EAAwB,CACnC,QAAA,CAAUC,gBAAAA,CAAS,GAAA,CACnB,UAAA,CAAYC,kBAAAA,CAAW,OAAA,CACvB,aAAA,CAAe,mBAAA,CACf,KAAA,CAAO,IACT,ECgCO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACuC,CACvC,OAAOD,CAAAA,CAAO,KAAA,CACZE,yCAAAA,CACA,CAAE,OAAA,CAAAD,CAAQ,CAAA,CACV,CACE,aAAA,CAAe,cAAA,CACf,KAAA,CAAO,KACT,CACF,CACF,CC3DA,IAAME,CAAAA,CAA8B,CAACC,CAAAA,CAAQC,CAAAA,CAAOC,EAAQC,CAAAA,GACnD,MAAA,CAAOH,CAAAA,CAAOG,CAAAA,CAAK,SAAS,CAAW,CAAA,CAG1CC,CAAAA,CAAkC,CAACJ,CAAAA,CAAQC,CAAAA,CAAOC,CAAAA,CAAQC,CAAAA,GACvDE,gBAAAA,CAAW,GAAA,CAAIL,CAAAA,CAAOG,EAA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CAAY,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,eAAA,EAAiB,CAQxE,GAPkB,MAAM3D,CAAAA,CAA6B,IAAA,CAAME,CAAO,CAAA,CAAE,KAAA,CACjE0D,CAAAA,EAAOA,CAAAA,CACPP,CAAAA,EAAQ,CACP,MAAMA,CACR,CACF,CAAA,CAGE,OAAOnD,EAAQ,MAAA,CAGjB,MAAM2D,UAAAA,CAAM,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,eAAe,EACtD,CACA,MAAMP,iBAAAA,CAAa,IAAA,CACjB,CAAA,gCAAA,EAAmCpD,CAAAA,CAAQ,MAAM,CAAA,iBAAA,CACnD,CACF,CACF","file":"index.cjs","sourcesContent":["import { Currency, TimeWindow } from '@aave/graphql';\nimport type { RequestPolicy } from '@urql/core';\n\nexport type CurrencyQueryOptions = {\n /**\n * The currency for fiat amounts.\n *\n * @defaultValue {@link Currency.Usd}\n */\n currency?: Currency;\n};\n\nexport type TimeWindowQueryOptions = {\n /**\n * The time window for historical data changes.\n *\n * @defaultValue {@link TimeWindow.LastDay}\n */\n timeWindow?: TimeWindow;\n};\n\n/**\n * @internal\n */\nexport type RequestPolicyOptions = {\n /**\n * The request policy to use.\n *\n * @internal This is used for testing purposes and could be changed without notice.\n * @defaultValue `cache-and-network`\n */\n requestPolicy?: RequestPolicy;\n};\n\n/**\n * @internal\n */\nexport type BatchOptions = {\n /**\n * Whether to batch the query or not.\n *\n * @internal This is used to turn off batching for a single query.\n * @defaultValue `true`\n */\n batch?: boolean;\n};\n\nexport const DEFAULT_QUERY_OPTIONS = {\n currency: Currency.Usd,\n timeWindow: TimeWindow.LastDay,\n requestPolicy: 'cache-and-network',\n batch: true,\n} as const;\n","import type { UnexpectedError } from '@aave/core';\nimport {\n type Chain,\n ChainQuery,\n type ChainRequest,\n ChainsQuery,\n type ChainsRequest,\n type ExchangeAmount,\n ExchangeRateQuery,\n type ExchangeRateRequest,\n HasProcessedKnownTransactionQuery,\n type HasProcessedKnownTransactionRequest,\n} from '@aave/graphql';\nimport type { ResultAsync } from '@aave/types';\nimport type { AaveClient } from '../AaveClient';\nimport { type BatchOptions, DEFAULT_QUERY_OPTIONS } from '../options';\n\n/**\n * Fetches a specific chain by chain ID.\n *\n * ```ts\n * const result = await chain(client, {\n * chainId: chainId(1),\n * });\n * ```\n *\n * @param client - Aave client.\n * @param request - The chain request parameters.\n * @returns The chain data, or null if not found.\n */\n\nexport function chain(\n client: AaveClient,\n request: ChainRequest,\n): ResultAsync<Chain | null, UnexpectedError>;\n/**\n * @internal\n */\nexport function chain(\n client: AaveClient,\n request: ChainRequest,\n options: BatchOptions,\n): ResultAsync<Chain | null, UnexpectedError>;\nexport function chain(\n client: AaveClient,\n request: ChainRequest,\n { batch }: BatchOptions = DEFAULT_QUERY_OPTIONS,\n): ResultAsync<Chain | null, UnexpectedError> {\n return client.query(ChainQuery, { request }, { batch });\n}\n\n/**\n * Fetches the list of supported chains.\n *\n * ```ts\n * const chains = await chains(client, {\n * query: { filter: ChainsFilter.ALL }\n * });\n * ```\n *\n * ```ts\n * const chains = await chains(client, {\n * query: { chainIds: [chainId(1), chainId(137)] }\n * });\n * ```\n *\n * @param client - Aave client.\n * @param request - The chains request parameters.\n * @returns Array of supported chains.\n */\nexport function chains(\n client: AaveClient,\n request: ChainsRequest,\n): ResultAsync<Chain[], UnexpectedError> {\n return client.query(ChainsQuery, { request });\n}\n\n/**\n * Check if a transaction has been processed by the Aave API.\n *\n * @param client - Aave client.\n * @param request - The request containing transaction hash and operations to check.\n * @returns True if the transaction has been processed, false otherwise.\n */\nexport function hasProcessedKnownTransaction(\n client: AaveClient,\n request: HasProcessedKnownTransactionRequest,\n): ResultAsync<boolean, UnexpectedError> {\n return client.query(\n HasProcessedKnownTransactionQuery,\n { request },\n {\n requestPolicy: 'network-only', // alwats hit the network\n batch: false, // never batch, always run ASAP\n },\n );\n}\n\n/**\n * Fetches the exchange rate between tokens and fiat currencies.\n *\n * ```ts\n * const result = await exchangeRate(client, {\n * from: { erc20: { chainId: chainId(1), address: evmAddress('0xA0b86a33E6...') } },\n * to: Currency.Usd,\n * });\n * ```\n *\n * @param client - Aave client.\n * @param request - The exchange rate request parameters.\n * @returns The exchange rate information as a fiat amount.\n */\nexport function exchangeRate(\n client: AaveClient,\n request: ExchangeRateRequest,\n): ResultAsync<ExchangeAmount, UnexpectedError> {\n return client.query(ExchangeRateQuery, { request });\n}\n","import {\n type ActivitiesQuery,\n type BorrowActivity,\n type Chain,\n type Erc20Token,\n encodeHubId,\n type Hub,\n type HubAsset,\n type HubQuery,\n isHubInputVariant,\n isTxHashInputVariant,\n type LiquidatedActivity,\n type NativeToken,\n type RepayActivity,\n type Reserve,\n type ReserveInfo,\n type Spoke,\n type SupplyActivity,\n type SwapByIntent,\n type SwapByIntentWithApprovalRequired,\n type SwapByTransaction,\n type TokenInfo,\n type UpdatedDynamicConfigActivity,\n type UpdatedRiskPremiumActivity,\n type UserPosition,\n type UsingAsCollateralActivity,\n type VariablesOf,\n type WithdrawActivity,\n} from '@aave/graphql';\nimport introspectedSchema from '@aave/graphql/schema';\nimport { BigDecimal, type TxHash } from '@aave/types';\nimport {\n cacheExchange,\n type Resolver,\n type Scalar,\n} from '@urql/exchange-graphcache';\n\nconst transformToBigInt: Resolver = (parent, _args, _cache, info) => {\n return BigInt(parent[info.fieldName] as string) as unknown as Scalar;\n};\n\nconst transformToBigDecimal: Resolver = (parent, _args, _cache, info) => {\n return BigDecimal.new(parent[info.fieldName] as string);\n};\n\nconst transformToNullableBigDecimal: Resolver = (\n parent,\n _args,\n _cache,\n info,\n) => {\n const value = parent[info.fieldName];\n if (value === null || value === undefined) {\n return null;\n }\n return transformToBigDecimal(parent, _args, _cache, info);\n};\n\nconst transformToDate: Resolver = (parent, _args, _cache, info) => {\n return new Date(parent[info.fieldName] as string);\n};\n\nconst transformToNullableDate: Resolver = (parent, _args, _cache, info) => {\n const value = parent[info.fieldName];\n if (value === null || value === undefined) {\n return null;\n }\n return transformToDate(parent, _args, _cache, info);\n};\n\nexport const exchange = cacheExchange({\n schema: introspectedSchema,\n resolvers: {\n PercentNumber: {\n onChainValue: transformToBigInt,\n value: transformToBigDecimal,\n normalized: transformToBigDecimal,\n },\n DecimalNumber: {\n onChainValue: transformToBigInt,\n value: transformToBigDecimal,\n },\n ExchangeAmount: {\n value: transformToBigDecimal,\n },\n AssetPriceSample: {\n price: transformToBigDecimal,\n date: transformToDate,\n },\n Reserve: {\n borrowCap: transformToBigDecimal,\n supplyCap: transformToBigDecimal,\n },\n HealthFactorError: {\n current: transformToNullableBigDecimal,\n after: transformToNullableBigDecimal,\n },\n HealthFactorVariation: {\n current: transformToNullableBigDecimal,\n after: transformToNullableBigDecimal,\n },\n HealthFactorWithChange: {\n current: transformToNullableBigDecimal,\n },\n UserSummary: {\n lowestHealthFactor: transformToNullableBigDecimal,\n },\n UserSummaryHistoryItem: {\n healthFactor: transformToNullableBigDecimal,\n date: transformToDate,\n },\n TransactionRequest: {\n value: transformToBigInt,\n },\n ApySample: {\n date: transformToDate,\n },\n AssetBorrowSample: {\n date: transformToDate,\n },\n AssetSupplySample: {\n date: transformToDate,\n },\n ProtocolHistorySample: {\n date: transformToDate,\n },\n BorrowActivity: {\n timestamp: transformToDate,\n },\n LiquidatedActivity: {\n timestamp: transformToDate,\n },\n RepayActivity: {\n timestamp: transformToDate,\n },\n SupplyActivity: {\n timestamp: transformToDate,\n },\n WithdrawActivity: {\n timestamp: transformToDate,\n },\n UsingAsCollateralActivity: {\n timestamp: transformToDate,\n },\n UpdatedDynamicConfigActivity: {\n timestamp: transformToDate,\n },\n UpdatedRiskPremiumActivity: {\n timestamp: transformToDate,\n },\n SpokeUserPositionManager: {\n approvedOn: transformToDate,\n },\n SwapCancelled: {\n createdAt: transformToDate,\n cancelledAt: transformToNullableDate,\n },\n SwapExpired: {\n createdAt: transformToDate,\n expiredAt: transformToDate,\n },\n SwapFulfilled: {\n createdAt: transformToDate,\n fulfilledAt: transformToDate,\n },\n SwapOpen: {\n createdAt: transformToDate,\n deadline: transformToDate,\n },\n SwapPendingSignature: {\n createdAt: transformToDate,\n deadline: transformToDate,\n },\n SwapReceipt: {\n createdAt: transformToDate,\n },\n // Intentionally omitted to keep it as BigIntString\n // PermitMessageData: {\n // value: transformToBigInt,\n // nonce: transformToBigInt,\n // },\n\n Query: {\n hub: (_, { request }: VariablesOf<typeof HubQuery>) => {\n if (isHubInputVariant(request.query)) {\n return {\n __typename: 'Hub',\n id: encodeHubId(request.query.hubInput),\n };\n }\n return {\n __typename: 'Hub',\n id: request.query.hubId,\n };\n },\n\n activities: (\n _parent,\n args: VariablesOf<typeof ActivitiesQuery>,\n cache,\n ) => {\n // Bail out if not a txHash filter lookup\n if (!isTxHashInputVariant(args.request.query)) {\n return cache.resolve('Query', 'activities', args);\n }\n\n const { txHash, chainId } = args.request.query.txHash;\n\n // Collect all cached activities matching txHash\n const matches = cache\n .inspectFields('Query')\n .filter((f) => f.fieldName === 'activities')\n .reduce((set, f) => {\n const pageRef = cache.resolve('Query', f.fieldKey) as string | null;\n if (!pageRef) return set;\n\n const itemRefs = cache.resolve(pageRef, 'items') as string[] | null;\n if (!itemRefs) return set;\n\n for (const ref of itemRefs) {\n set.add(ref);\n }\n return set;\n }, new Set<string>())\n .values()\n .toArray()\n .filter((ref) => {\n const itemTxHash = cache.resolve(ref, 'txHash') as TxHash;\n if (itemTxHash !== txHash) return false;\n\n // Verify chainId via spoke.chain.chainId if present\n const spokeRef = cache.resolve(ref, 'spoke') as string | null;\n if (spokeRef) {\n const chainRef = cache.resolve(spokeRef, 'chain') as\n | string\n | null;\n const itemChainId = chainRef\n ? (cache.resolve(chainRef, 'chainId') as number | undefined)\n : undefined;\n if (typeof itemChainId === 'number') {\n return itemChainId === chainId;\n }\n }\n return true;\n });\n\n if (matches.length === 0) return undefined;\n\n return {\n __typename: 'PaginatedActivitiesResult',\n items: matches,\n pageInfo: {\n __typename: 'PaginatedResultInfo',\n prev: null,\n next: null,\n },\n };\n },\n },\n },\n keys: {\n // Entitied with composite key\n Hub: (data: Hub) => data.id,\n HubAsset: (data: HubAsset) => data.id,\n Reserve: (data: Reserve) => data.id,\n ReserveInfo: (data: ReserveInfo) => data.id,\n Spoke: (data: Spoke) => data.id,\n\n // Entities with id field as key\n BorrowActivity: (data: BorrowActivity) => data.id,\n LiquidatedActivity: (data: LiquidatedActivity) => data.id,\n SupplyActivity: (data: SupplyActivity) => data.id,\n SwapByIntent: (data: SwapByIntent) => data.quote.quoteId,\n SwapByIntentWithApprovalRequired: (\n data: SwapByIntentWithApprovalRequired,\n ) => data.quote.quoteId,\n SwapByTransaction: (data: SwapByTransaction) => data.quote.quoteId,\n UserPosition: (data: UserPosition) => data.id,\n UpdatedDynamicConfigActivity: (data: UpdatedDynamicConfigActivity) =>\n data.id,\n UpdatedRiskPremiumActivity: (data: UpdatedRiskPremiumActivity) => data.id,\n UsingAsCollateralActivity: (data: UsingAsCollateralActivity) => data.id,\n WithdrawActivity: (data: WithdrawActivity) => data.id,\n RepayActivity: (data: RepayActivity) => data.id,\n TokenInfo: (data: TokenInfo) => data.id,\n\n // Entities with address field as key\n Erc20Token: (data: Erc20Token) => data.address,\n\n // Entities with other fields as key\n Chain: (data: Chain) => data.chainId.toString(),\n NativeToken: (data: NativeToken) => data.chain.chainId.toString(),\n\n // Entities without keys will be embedded directly on the parent entity\n PaginatedActivitiesResult: () => null,\n PaginatedResultInfo: () => null,\n PaginatedSpokePositionManagerResult: () => null,\n PaginatedSpokeUserPositionManagerResult: () => null,\n PaginatedUserSwapsResult: () => null,\n SpokePositionManger: () => null,\n SpokeUserPositionManager: () => null,\n SwapReceipt: () => null,\n SwapTransactionRequest: () => null,\n\n // Value objects and result types\n ApySample: () => null,\n Asset: () => null,\n AssetBorrowSample: () => null,\n AssetPriceSample: () => null,\n AssetSummary: () => null,\n AssetSupplySample: () => null,\n CancelSwapTypedData: () => null,\n CancelSwapTypeDefinition: () => null,\n DecimalNumber: () => null,\n DecimalNumberWithChange: () => null,\n DomainData: () => null,\n Erc20Amount: () => null,\n Erc20ApprovalRequired: () => null,\n ExchangeAmount: () => null,\n ExchangeAmountValueVariation: () => null,\n ExchangeAmountWithChange: () => null,\n ForkTopUpResponse: () => null,\n HealthFactorError: () => null,\n HealthFactorVariation: () => null,\n HealthFactorWithChange: () => null,\n HubAssetSettings: () => null,\n HubAssetSummary: () => null,\n HubAssetUserState: () => null,\n HubSummary: () => null,\n InsufficientBalanceError: () => null,\n NativeAmount: () => null,\n PercentNumber: () => null,\n PercentNumberVariation: () => null,\n PercentNumberWithChange: () => null,\n PermitMessageData: () => null,\n PermitTypedDataResponse: () => null,\n PreContractActionRequired: () => null,\n PrepareSwapCancelResult: () => null,\n PreviewUserPosition: () => null,\n ProtocolHistorySample: () => null,\n ReserveSettings: () => null,\n ReserveStatus: () => null,\n ReserveSummary: () => null,\n ReserveUserState: () => null,\n SwapApprovalRequired: () => null,\n SwapByIntentTypedData: () => null,\n SwapByIntentTypeDefinition: () => null,\n SwapCancelled: () => null,\n SwapExpired: () => null,\n SwapFulfilled: () => null,\n SwapOpen: () => null,\n SwapPendingSignature: () => null,\n SwapQuote: () => null,\n SwapQuoteCosts: () => null,\n TransactionRequest: () => null,\n TypeDefinition: () => null,\n TypeField: () => null,\n UserBalance: () => null,\n UserBorrowItem: () => null,\n UserSummary: () => null,\n UserSummaryHistoryItem: () => null,\n UserSupplyItem: () => null,\n },\n});\n","import type { EnvironmentConfig } from '@aave/core';\n\n/**\n * The production environment configuration.\n */\nexport const production: EnvironmentConfig = {\n name: 'production',\n backend: 'https://api.v4.aave.com/graphql',\n indexingTimeout: 60_000,\n pollingInterval: 100,\n exchangeRateInterval: 10000,\n};\n\n/**\n * @internal\n */\nexport const staging: EnvironmentConfig = {\n name: 'staging',\n backend: 'https://api.v4.staging.aave.com/graphql',\n indexingTimeout: 60_000,\n pollingInterval: 500,\n exchangeRateInterval: 10000,\n};\n\n/**\n * @internal\n */\nexport const local: EnvironmentConfig = {\n name: 'local',\n backend: 'http://localhost:3007/graphql',\n indexingTimeout: 60_000,\n pollingInterval: 1000,\n exchangeRateInterval: 10000,\n};\n","import type { Context } from '@aave/core';\nimport type { TypedDocumentNode } from '@urql/core';\nimport type { EnvironmentConfig } from '../../core/src/types';\nimport { exchange } from './cache';\nimport { production } from './environments';\n\n/**\n * The client configuration.\n */\nexport type ClientConfig = {\n /**\n * @internal\n * @defaultValue `production`\n */\n environment?: EnvironmentConfig;\n /**\n * @internal\n */\n headers?: Record<string, string>;\n /**\n * Whether to enable caching.\n *\n * @defaultValue `true`\n */\n cache?: boolean;\n /**\n * Whether to enable debug mode.\n *\n * @defaultValue `false`\n */\n debug?: boolean;\n /**\n * The custom fragments to use.\n *\n * @experimental This is an experimental API and may be subject to breaking changes.\n */\n fragments?: TypedDocumentNode[];\n};\n\n/**\n * @internal\n */\nexport function configureContext({\n environment = production,\n headers,\n cache = true,\n debug = false,\n fragments = [],\n}: ClientConfig): Context {\n return {\n displayName: 'AaveClient',\n environment,\n headers,\n cache: cache ? exchange : null,\n debug,\n fragments,\n };\n}\n","import type {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n CancelSwapTypedData,\n ERC20PermitSignature,\n ExecutionPlan,\n HasProcessedKnownTransactionRequest,\n InsufficientBalanceError,\n OperationType,\n PermitTypedDataResponse,\n SwapByIntentTypedData,\n} from '@aave/graphql';\nimport type { ResultAsync, TxHash } from '@aave/types';\n\n/**\n * @internal\n */\nexport type TransactionResult = {\n txHash: TxHash;\n operations: OperationType[] | null;\n};\n\n/**\n * @internal\n */\nexport function isHasProcessedKnownTransactionRequest(\n result: TransactionResult,\n): result is HasProcessedKnownTransactionRequest {\n return result.operations !== null && result.operations.length > 0;\n}\n\nexport type SendWithError =\n | CancelError\n | SigningError\n | TransactionError\n | ValidationError<InsufficientBalanceError>\n | UnexpectedError;\n\nexport type ExecutionPlanHandler<T extends ExecutionPlan = ExecutionPlan> = (\n result: T,\n) => ResultAsync<TransactionResult, SendWithError>;\n\nexport type ERC20PermitHandler = (\n result: PermitTypedDataResponse,\n) => ResultAsync<ERC20PermitSignature, SigningError>;\n\nexport type SwapSignatureHandler = (\n result: CancelSwapTypedData | SwapByIntentTypedData,\n) => ResultAsync<ERC20PermitSignature, SigningError>;\n","import {\n delay,\n GqlClient,\n type StandardData,\n TimeoutError,\n UnexpectedError,\n} from '@aave/core';\nimport type { HasProcessedKnownTransactionRequest } from '@aave/graphql';\nimport {\n type AnyVariables,\n invariant,\n ResultAsync,\n type TxHash,\n} from '@aave/types';\nimport type { TypedDocumentNode } from '@urql/core';\nimport { hasProcessedKnownTransaction } from './actions';\nimport { type ClientConfig, configureContext } from './config';\nimport {\n isHasProcessedKnownTransactionRequest,\n type TransactionResult,\n} from './types';\n\nexport class AaveClient extends GqlClient {\n /**\n * Create a new instance of the {@link AaveClient}.\n *\n * ```ts\n * const client = AaveClient.create({\n * environment: production,\n * });\n * ```\n *\n * @param options - The options to configure the client.\n * @returns The new instance of the client.\n */\n static create(options?: ClientConfig): AaveClient {\n return new AaveClient(configureContext(options ?? {}));\n }\n\n /**\n * Given the transaction hash of an Aave protocol transaction, wait for the transaction to be\n * processed by the Aave v4 API.\n *\n * Returns a {@link TimeoutError} if the transaction is not processed within the expected timeout period.\n *\n * @param result - The transaction execution result to wait for.\n * @returns The transaction hash or a TimeoutError\n */\n readonly waitForTransaction = (\n result: TransactionResult,\n ): ResultAsync<TxHash, TimeoutError | UnexpectedError> => {\n invariant(\n isHasProcessedKnownTransactionRequest(result),\n `Received a transaction result for an untracked operation. Make sure you're following the instructions in the docs.`,\n );\n\n return ResultAsync.fromPromise(\n this.pollTransactionStatus(result),\n (err) => {\n if (err instanceof TimeoutError || err instanceof UnexpectedError) {\n return err;\n }\n return UnexpectedError.from(err);\n },\n );\n };\n\n /**\n * @internal\n */\n async refreshQueryWhere<TValue, TVariables extends AnyVariables>(\n document: TypedDocumentNode<StandardData<TValue>, TVariables>,\n predicate: (\n variables: TVariables,\n data: TValue,\n ) => boolean | Promise<boolean>,\n ): Promise<void> {\n await this.refreshWhere(async (op) => {\n if (op.query === document) {\n const result = await this.query(document, op.variables as TVariables, {\n requestPolicy: 'cache-only',\n });\n\n if (result.isErr()) {\n return false;\n }\n\n return predicate(op.variables as TVariables, result.value as TValue);\n }\n return false;\n });\n }\n\n protected async pollTransactionStatus(\n request: HasProcessedKnownTransactionRequest,\n ): Promise<TxHash> {\n const startedAt = Date.now();\n\n while (Date.now() - startedAt < this.context.environment.indexingTimeout) {\n const processed = await hasProcessedKnownTransaction(this, request).match(\n (ok) => ok,\n (err) => {\n throw err;\n },\n );\n\n if (processed) {\n return request.txHash;\n }\n\n await delay(this.context.environment.pollingInterval);\n }\n throw TimeoutError.from(\n `Timeout waiting for transaction ${request.txHash} to be processed.`,\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/options.ts","../src/actions/misc.ts","../src/cache.ts","../src/environments.ts","../src/config.ts","../src/types.ts","../src/AaveClient.ts","../src/adapters.ts"],"names":["DEFAULT_QUERY_OPTIONS","Currency","TimeWindow","hasProcessedKnownTransaction","client","request","HasProcessedKnownTransactionQuery","transformToBigInt","parent","_args","_cache","info","transformToBigDecimal","BigDecimal","transformToNullableBigDecimal","value","transformToDate","transformToNullableDate","exchange","cacheExchange","introspectedSchema","_","isHubInputVariant","encodeHubId","isReserveInputVariant","encodeReserveId","chainId","address","decodeSpokeId","encodeUserPositionId","_parent","args","cache","isTxHashInputVariant","txHash","matches","f","set","pageRef","itemRefs","ref","spokeRef","chainRef","itemChainId","data","production","staging","local","configureContext","environment","headers","batch","debug","isHasProcessedKnownTransactionRequest","result","transactionReceipt","AaveClient","_AaveClient","GqlClient","options","invariant","ResultAsync","err","TimeoutError","UnexpectedError","startedAt","ok","delay","hasApprovals","plan","supportsPermit","isOneEntryArray"],"mappings":"wTA+CaA,CAAAA,CAAwB,CACnC,SAAUC,gBAAAA,CAAS,GAAA,CACnB,WAAYC,kBAAAA,CAAW,OAAA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AS,CAEhC,CASO,SAASC,EAAAA,CAAkBD,EAG9B,CACF,OACED,EAAaC,CAAI,CAAA,EACjBE,sBAAgBF,CAAAA,CAAK,SAAS,GAC9B,CAAC,CAACA,EAAK,SAAA,CAAU,CAAC,EAAE,WAExB","file":"index.cjs","sourcesContent":["import { Currency, TimeWindow } from '@aave/graphql';\nimport type { RequestPolicy } from '@urql/core';\n\nexport type CurrencyQueryOptions = {\n /**\n * The currency for fiat amounts.\n *\n * @defaultValue {@link Currency.Usd}\n */\n currency?: Currency;\n};\n\nexport type TimeWindowQueryOptions = {\n /**\n * The time window for historical data changes.\n *\n * @defaultValue {@link TimeWindow.LastDay}\n */\n timeWindow?: TimeWindow;\n};\n\n/**\n * @internal\n */\nexport type RequestPolicyOptions = {\n /**\n * The request policy to use.\n *\n * @internal This is used for testing purposes and could be changed without notice.\n * @defaultValue `cache-and-network`\n */\n requestPolicy?: RequestPolicy;\n};\n\n/**\n * @internal\n */\nexport type BatchOptions = {\n /**\n * Whether to batch the query or not.\n *\n * @internal This is used to turn off batching for a single query.\n * @defaultValue `true`\n */\n batch?: boolean;\n};\n\nexport const DEFAULT_QUERY_OPTIONS = {\n currency: Currency.Usd,\n timeWindow: TimeWindow.LastDay,\n requestPolicy: 'cache-and-network',\n batch: true,\n} as const;\n","import type { UnexpectedError } from '@aave/core';\nimport {\n type Chain,\n ChainQuery,\n type ChainRequest,\n ChainsQuery,\n type ChainsRequest,\n type ExchangeAmount,\n ExchangeRateQuery,\n type ExchangeRateRequest,\n HasProcessedKnownTransactionQuery,\n type HasProcessedKnownTransactionRequest,\n} from '@aave/graphql';\nimport type { ResultAsync } from '@aave/types';\nimport type { AaveClient } from '../AaveClient';\nimport {\n type BatchOptions,\n DEFAULT_QUERY_OPTIONS,\n type RequestPolicyOptions,\n} from '../options';\n\n/**\n * Fetches a specific chain by chain ID.\n *\n * ```ts\n * const result = await chain(client, {\n * chainId: chainId(1),\n * });\n * ```\n *\n * @param client - Aave client.\n * @param request - The chain request parameters.\n * @param options - The query options.\n * @returns The chain data, or null if not found.\n */\nexport function chain(\n client: AaveClient,\n request: ChainRequest,\n {\n batch = DEFAULT_QUERY_OPTIONS.batch,\n requestPolicy = DEFAULT_QUERY_OPTIONS.requestPolicy,\n }: BatchOptions & RequestPolicyOptions = DEFAULT_QUERY_OPTIONS,\n): ResultAsync<Chain | null, UnexpectedError> {\n return client.query(ChainQuery, { request }, { batch, requestPolicy });\n}\n\n/**\n * Fetches the list of supported chains.\n *\n * ```ts\n * const chains = await chains(client, {\n * query: { filter: ChainsFilter.ALL }\n * });\n * ```\n *\n * ```ts\n * const chains = await chains(client, {\n * query: { chainIds: [chainId(1), chainId(137)] }\n * });\n * ```\n *\n * @param client - Aave client.\n * @param request - The chains request parameters.\n * @returns Array of supported chains.\n */\nexport function chains(\n client: AaveClient,\n request: ChainsRequest,\n): ResultAsync<Chain[], UnexpectedError> {\n return client.query(ChainsQuery, { request });\n}\n\n/**\n * Check if a transaction has been processed by the Aave API.\n *\n * @param client - Aave client.\n * @param request - The request containing transaction hash and operations to check.\n * @returns True if the transaction has been processed, false otherwise.\n */\nexport function hasProcessedKnownTransaction(\n client: AaveClient,\n request: HasProcessedKnownTransactionRequest,\n): ResultAsync<boolean, UnexpectedError> {\n return client.query(\n HasProcessedKnownTransactionQuery,\n { request },\n {\n requestPolicy: 'network-only', // alwats hit the network\n batch: false, // never batch, always run ASAP\n },\n );\n}\n\n/**\n * Fetches the exchange rate between tokens and fiat currencies.\n *\n * ```ts\n * const result = await exchangeRate(client, {\n * from: { erc20: { chainId: chainId(1), address: evmAddress('0xA0b86a33E6...') } },\n * to: Currency.Usd,\n * });\n * ```\n *\n * @param client - Aave client.\n * @param request - The exchange rate request parameters.\n * @param options - The query options.\n * @returns The exchange rate information as a fiat amount.\n */\nexport function exchangeRate(\n client: AaveClient,\n request: ExchangeRateRequest,\n {\n requestPolicy = DEFAULT_QUERY_OPTIONS.requestPolicy,\n }: RequestPolicyOptions = DEFAULT_QUERY_OPTIONS,\n): ResultAsync<ExchangeAmount, UnexpectedError> {\n return client.query(ExchangeRateQuery, { request }, { requestPolicy });\n}\n","import {\n type ActivitiesQuery,\n type Asset,\n type BoostedRateId,\n type BorrowActivity,\n type BorrowPoints,\n type BorrowSwapActivity,\n type Chain,\n decodeSpokeId,\n type Erc20Token,\n encodeHubId,\n encodeReserveId,\n encodeUserPositionId,\n type Hub,\n type HubAsset,\n type HubQuery,\n isHubInputVariant,\n isReserveInputVariant,\n isTxHashInputVariant,\n type LiquidatedActivity,\n type MerklBorrowReward,\n type MerklGenericCriteria,\n type MerklSupplyReward,\n type NativeToken,\n type PointsGenericCriteria,\n type PointsProgram,\n type RepayActivity,\n type RepayWithSupplyActivity,\n type Reserve,\n type ReserveInfo,\n type ReserveQuery,\n type Spoke,\n type StableVault,\n type StableVaultUserPosition,\n type SupplyActivity,\n type SupplyPoints,\n type SupplySwapActivity,\n type TokenInfo,\n type TokenMovementRecord,\n type TokenSwapActivity,\n type UpdatedDynamicConfigActivity,\n type UpdatedRiskPremiumActivity,\n type UserMerklClaimableReward,\n type UserPosition,\n type UserPositionQuery,\n type UsingAsCollateralActivity,\n type VariablesOf,\n type WithdrawActivity,\n type WithdrawSwapActivity,\n} from '@aave/graphql';\nimport introspectedSchema from '@aave/graphql/schema';\nimport { BigDecimal, type TxHash } from '@aave/types';\nimport {\n cacheExchange,\n type Resolver,\n type Scalar,\n} from '@urql/exchange-graphcache';\n\nconst transformToBigInt: Resolver = (parent, _args, _cache, info) => {\n return BigInt(parent[info.fieldName] as string) as unknown as Scalar;\n};\n\nconst transformToBigDecimal: Resolver = (parent, _args, _cache, info) => {\n return BigDecimal.new(parent[info.fieldName] as string);\n};\n\nconst transformToNullableBigDecimal: Resolver = (\n parent,\n _args,\n _cache,\n info,\n) => {\n const value = parent[info.fieldName];\n if (value === null || value === undefined) {\n return null;\n }\n return transformToBigDecimal(parent, _args, _cache, info);\n};\n\nconst transformToDate: Resolver = (parent, _args, _cache, info) => {\n return new Date(parent[info.fieldName] as string);\n};\n\nconst transformToNullableDate: Resolver = (parent, _args, _cache, info) => {\n const value = parent[info.fieldName];\n if (value === null || value === undefined) {\n return null;\n }\n return transformToDate(parent, _args, _cache, info);\n};\n\nexport const exchange = cacheExchange({\n schema: introspectedSchema,\n resolvers: {\n PercentNumber: {\n onChainValue: transformToBigInt,\n value: transformToBigDecimal,\n normalized: transformToBigDecimal,\n },\n DecimalNumber: {\n onChainValue: transformToBigInt,\n value: transformToBigDecimal,\n },\n ExchangeAmount: {\n value: transformToBigDecimal,\n },\n AssetPriceSample: {\n price: transformToBigDecimal,\n date: transformToDate,\n },\n PermitTypedData: {\n signedAmount: transformToBigDecimal,\n },\n HealthFactorError: {\n current: transformToNullableBigDecimal,\n after: transformToNullableBigDecimal,\n },\n HealthFactorVariation: {\n current: transformToNullableBigDecimal,\n after: transformToNullableBigDecimal,\n },\n HealthFactorWithChange: {\n current: transformToNullableBigDecimal,\n },\n UserSummary: {\n lowestHealthFactor: transformToNullableBigDecimal,\n },\n UserSummaryHistoryItem: {\n healthFactor: transformToNullableBigDecimal,\n date: transformToDate,\n },\n TransactionRequest: {\n value: transformToBigInt,\n },\n ApySample: {\n date: transformToDate,\n },\n AssetBorrowSample: {\n date: transformToDate,\n },\n AssetSupplySample: {\n date: transformToDate,\n },\n HubSummarySample: {\n date: transformToDate,\n },\n BorrowPointsReward: {\n startDate: transformToDate,\n endDate: transformToNullableDate,\n },\n PreviewBorrowPointsReward: {\n startDate: transformToDate,\n endDate: transformToNullableDate,\n },\n PreviewMerklBorrowReward: {\n startDate: transformToDate,\n endDate: transformToDate,\n },\n PreviewMerklSupplyReward: {\n startDate: transformToDate,\n endDate: transformToDate,\n },\n PreviewSupplyPointsReward: {\n startDate: transformToDate,\n endDate: transformToNullableDate,\n },\n SupplyPointsReward: {\n startDate: transformToDate,\n endDate: transformToNullableDate,\n },\n ProtocolHistorySample: {\n date: transformToDate,\n },\n BorrowActivity: {\n timestamp: transformToDate,\n },\n LiquidatedActivity: {\n timestamp: transformToDate,\n },\n MerklBorrowReward: {\n startDate: transformToDate,\n endDate: transformToDate,\n },\n MerklSupplyReward: {\n startDate: transformToDate,\n endDate: transformToDate,\n },\n RepayActivity: {\n timestamp: transformToDate,\n },\n SupplyActivity: {\n timestamp: transformToDate,\n },\n WithdrawActivity: {\n timestamp: transformToDate,\n },\n UsingAsCollateralActivity: {\n timestamp: transformToDate,\n },\n UpdatedDynamicConfigActivity: {\n timestamp: transformToDate,\n },\n UpdatedRiskPremiumActivity: {\n timestamp: transformToDate,\n },\n TokenSwapActivity: {\n timestamp: transformToDate,\n },\n SupplySwapActivity: {\n timestamp: transformToDate,\n },\n BorrowSwapActivity: {\n timestamp: transformToDate,\n },\n RepayWithSupplyActivity: {\n timestamp: transformToDate,\n },\n WithdrawSwapActivity: {\n timestamp: transformToDate,\n },\n UserMerklClaimableReward: {\n startDate: transformToDate,\n endDate: transformToDate,\n claimUntil: transformToDate,\n },\n UserPosition: {\n createdAt: transformToDate,\n },\n UserBorrowItem: {\n createdAt: transformToNullableDate,\n },\n UserSupplyItem: {\n createdAt: transformToNullableDate,\n },\n SpokeUserPositionManager: {\n approvedOn: transformToDate,\n },\n SwapCancelled: {\n createdAt: transformToDate,\n cancelledAt: transformToNullableDate,\n },\n SwapCancelledResult: {\n createdAt: transformToDate,\n cancelledAt: transformToNullableDate,\n },\n SwapExpired: {\n createdAt: transformToDate,\n expiredAt: transformToDate,\n },\n SwapFulfilled: {\n createdAt: transformToDate,\n fulfilledAt: transformToDate,\n },\n SwapOpen: {\n createdAt: transformToDate,\n deadline: transformToDate,\n },\n SwapPendingSignature: {\n createdAt: transformToDate,\n deadline: transformToDate,\n },\n SwapReceipt: {\n createdAt: transformToDate,\n },\n StableVaultSummary: {\n shares: transformToBigInt,\n totalDeposits: transformToBigDecimal,\n userCount: transformToBigInt,\n },\n StableVaultWithdrawClaim: {\n executableAfter: transformToDate,\n },\n TokenMovementRecord: {\n timestamp: transformToDate,\n },\n StableVaultPendingAvailability: {\n executableAfter: transformToDate,\n },\n Query: {\n hub: (_, { request }: VariablesOf<typeof HubQuery>) => {\n if (isHubInputVariant(request.query)) {\n return {\n __typename: 'Hub',\n id: encodeHubId(request.query.hubInput),\n };\n }\n return {\n __typename: 'Hub',\n id: request.query.hubId,\n };\n },\n\n reserve: (_, { request }: VariablesOf<typeof ReserveQuery>) => {\n if (isReserveInputVariant(request.query)) {\n return {\n __typename: 'Reserve',\n id: encodeReserveId(request.query.reserveInput),\n };\n }\n return {\n __typename: 'Reserve',\n id: request.query.reserveId,\n };\n },\n\n userPosition: (_, { request }: VariablesOf<typeof UserPositionQuery>) => {\n if ('userSpoke' in request && request.userSpoke) {\n const { chainId, address } = decodeSpokeId(request.userSpoke.spoke);\n return {\n __typename: 'UserPosition',\n id: encodeUserPositionId({\n chainId,\n spoke: address,\n user: request.userSpoke.user,\n }),\n };\n }\n if ('id' in request && request.id) {\n return {\n __typename: 'UserPosition',\n id: request.id,\n };\n }\n return undefined;\n },\n\n activities: (\n _parent,\n args: VariablesOf<typeof ActivitiesQuery>,\n cache,\n ) => {\n // Bail out if not a txHash filter lookup\n if (!isTxHashInputVariant(args.request.query)) {\n return cache.resolve('Query', 'activities', args);\n }\n\n const { txHash, chainId } = args.request.query.txHash;\n\n // Collect all cached activities matching txHash\n const matches = cache\n .inspectFields('Query')\n .filter((f) => f.fieldName === 'activities')\n .reduce((set, f) => {\n const pageRef = cache.resolve('Query', f.fieldKey) as string | null;\n if (!pageRef) return set;\n\n const itemRefs = cache.resolve(pageRef, 'items') as string[] | null;\n if (!itemRefs) return set;\n\n for (const ref of itemRefs) {\n set.add(ref);\n }\n return set;\n }, new Set<string>())\n .values()\n .toArray()\n .filter((ref) => {\n const itemTxHash = cache.resolve(ref, 'txHash') as TxHash;\n if (itemTxHash !== txHash) return false;\n\n // Verify chainId via spoke.chain.chainId if present\n const spokeRef = cache.resolve(ref, 'spoke') as string | null;\n if (spokeRef) {\n const chainRef = cache.resolve(spokeRef, 'chain') as\n | string\n | null;\n const itemChainId = chainRef\n ? (cache.resolve(chainRef, 'chainId') as number | undefined)\n : undefined;\n if (typeof itemChainId === 'number') {\n return itemChainId === chainId;\n }\n }\n return true;\n });\n\n if (matches.length === 0) return undefined;\n\n return {\n __typename: 'PaginatedActivitiesResult',\n items: matches,\n pageInfo: {\n __typename: 'PaginatedResultInfo',\n prev: null,\n next: null,\n },\n };\n },\n },\n },\n keys: {\n // Entities with id field as key\n Asset: (data: Asset) => data.id,\n BorrowActivity: (data: BorrowActivity) => data.id,\n BorrowPointsReward: (data: BorrowPoints) => data.id,\n BorrowSwapActivity: (data: BorrowSwapActivity) => data.id,\n // URQL SystemFields & DataFields doesn't play ball with the bigint scalar (BoostedRate.userCounts field),\n // hence the type assertion to BoostedRateId which is a string alias of the id\n BoostedRate: (data) => data.id as BoostedRateId,\n Hub: (data: Hub) => data.id,\n HubAsset: (data: HubAsset) => data.id,\n LiquidatedActivity: (data: LiquidatedActivity) => data.id,\n MerklBorrowReward: (data: MerklBorrowReward) => data.id,\n MerklGenericCriteria: (data: MerklGenericCriteria) => data.id,\n MerklSupplyReward: (data: MerklSupplyReward) => data.id,\n PointsGenericCriteria: (data: PointsGenericCriteria) => data.id,\n PointsProgram: (data: PointsProgram) => data.id,\n RepayActivity: (data: RepayActivity) => data.id,\n RepayWithSupplyActivity: (data: RepayWithSupplyActivity) => data.id,\n Reserve: (data: Reserve) => data.id,\n ReserveInfo: (data: ReserveInfo) => data.id,\n Spoke: (data: Spoke) => data.id,\n StableVault: (data: StableVault) => data.id,\n StableVaultUserPosition: (data: StableVaultUserPosition) => data.id,\n SupplyActivity: (data: SupplyActivity) => data.id,\n SupplyPointsReward: (data: SupplyPoints) => data.id,\n SupplySwapActivity: (data: SupplySwapActivity) => data.id,\n TokenInfo: (data: TokenInfo) => data.id,\n TokenMovementRecord: (data: TokenMovementRecord) => data.id,\n TokenSwapActivity: (data: TokenSwapActivity) => data.id,\n UpdatedDynamicConfigActivity: (data: UpdatedDynamicConfigActivity) =>\n data.id,\n UpdatedRiskPremiumActivity: (data: UpdatedRiskPremiumActivity) => data.id,\n UserMerklClaimableReward: (data: UserMerklClaimableReward) => data.id,\n UserPosition: (data: UserPosition) => data.id,\n UsingAsCollateralActivity: (data: UsingAsCollateralActivity) => data.id,\n WithdrawActivity: (data: WithdrawActivity) => data.id,\n WithdrawSwapActivity: (data: WithdrawSwapActivity) => data.id,\n\n // Entities with address field as key\n Erc20Token: (data: Erc20Token) => data.address,\n\n // Entities with other fields as key\n Chain: (data: Chain) => data.chainId.toString(),\n NativeToken: (data: NativeToken) => data.chain.chainId.toString(),\n\n // Value objects and result types\n ApySample: () => null,\n AssetAmountWithChange: () => null,\n AssetBorrowSample: () => null,\n AssetPriceSample: () => null,\n AssetSampleBreakdown: () => null,\n AssetSummary: () => null,\n AssetSupplySample: () => null,\n BorrowSwap: () => null,\n BorrowSwapQuoteResult: () => null,\n CollateralFactorVariation: () => null,\n DecimalNumber: () => null,\n DecimalNumberWithChange: () => null,\n DomainData: () => null,\n Erc20Amount: () => null,\n Erc20Approval: () => null,\n Erc20ApprovalRequired: () => null,\n ExchangeAmount: () => null,\n ExchangeAmountVariation: () => null,\n ExchangeAmountWithChange: () => null,\n ForkTopUpResponse: () => null,\n HealthFactorError: () => null,\n HealthFactorVariation: () => null,\n HealthFactorWithChange: () => null,\n HubAssetInterestRateModelPoint: () => null,\n HubAssetInterestRateModelResult: () => null,\n HubAssetSettings: () => null,\n HubAssetSummary: () => null,\n HubAssetUserState: () => null,\n HubSummary: () => null,\n HubSummarySample: () => null,\n InsufficientBalanceError: () => null,\n InsufficientLiquidityError: () => null,\n LiquidationFeeVariation: () => null,\n MaxLiquidationBonusVariation: () => null,\n NativeAmount: () => null,\n PaginatedActivitiesResult: () => null,\n PaginatedResultInfo: () => null,\n PaginatedSpokePositionManagerResult: () => null,\n PaginatedSpokeUserPositionManagerResult: () => null,\n PaginatedStableVaultMovementsResult: () => null,\n PaginatedStableVaultRateUsersResult: () => null,\n PaginatedUserSwapsResult: () => null,\n PercentNumber: () => null,\n PercentNumberChangeSnapshot: () => null,\n PercentNumberVariation: () => null,\n PercentNumberWithChange: () => null,\n PermitTypedData: () => null,\n PositionAmount: () => null,\n PositionSwapAdapterContractApproval: () => null,\n PositionSwapByIntentApprovalsRequired: () => null,\n PositionSwapPositionManagerApproval: () => null,\n PreContractActionRequired: () => null,\n PrepareSwapCancelResult: () => null,\n PrepareSwapOrder: () => null,\n PreviewBorrowPointsReward: () => null,\n PreviewMerklBorrowReward: () => null,\n PreviewMerklSupplyReward: () => null,\n PreviewReserveRates: () => null,\n PreviewRewardOutcome: () => null,\n PreviewSupplyPointsReward: () => null,\n PreviewUserPosition: () => null,\n ProtocolHistorySample: () => null,\n RepayWithSupply: () => null,\n RepayWithSupplyQuoteResult: () => null,\n ReserveSettings: () => null,\n ReserveStatus: () => null,\n ReserveSummary: () => null,\n ReserveUserState: () => null,\n SpokePositionManager: () => null,\n SpokeUserPositionManager: () => null,\n StableVaultPendingAvailability: () => null,\n StableVaultRates: () => null,\n StableVaultSummary: () => null,\n StableVaultWithdrawClaim: () => null,\n SupplySwap: () => null,\n SupplySwapQuoteResult: () => null,\n SwapByIntent: () => null,\n SwapByIntentWithApprovalRequired: () => null,\n SwapByTransaction: () => null,\n SwapCancelled: () => null,\n SwapCancelledResult: () => null,\n SwapExpired: () => null,\n SwapFulfilled: () => null,\n SwapOpen: () => null,\n SwapPendingSignature: () => null,\n SwapQuote: () => null,\n SwapQuoteCosts: () => null,\n SwapReceipt: () => null,\n SwapTransactionRequest: () => null,\n SwapTypedData: () => null,\n TokenMovementAllocate: () => null,\n TokenMovementBridgeIn: () => null,\n TokenMovementBridgeOut: () => null,\n TokenMovementDeallocate: () => null,\n TokenMovementRebalance: () => null,\n TokenMovementSwap: () => null,\n TokenSwap: () => null,\n TokenSwapQuoteResult: () => null,\n TransactionRequest: () => null,\n UserBalance: () => null,\n UserBorrowItem: () => null,\n UserPositionRiskPremium: () => null,\n UserRiskPremiumBreakdownItem: () => null,\n UserSummary: () => null,\n UserSummaryHistoryItem: () => null,\n UserSupplyItem: () => null,\n WithdrawSwap: () => null,\n WithdrawSwapQuoteResult: () => null,\n },\n});\n","import type { EnvironmentConfig } from '@aave/core';\n\n/**\n * The production environment configuration.\n */\nexport const production: EnvironmentConfig = {\n name: 'production',\n backend: 'https://api.aave.com/graphql',\n indexingTimeout: 60_000,\n pollingInterval: 100,\n exchangeRateInterval: 10_000,\n swapQuoteInterval: 30_000,\n swapStatusInterval: 5_000,\n};\n\n/**\n * @internal\n */\nexport const staging: EnvironmentConfig = {\n name: 'staging',\n backend: 'https://api.staging.aave.com/graphql',\n indexingTimeout: 60_000,\n pollingInterval: 500,\n exchangeRateInterval: 10_000,\n swapQuoteInterval: 30_000,\n swapStatusInterval: 5_000,\n};\n\n/**\n * @internal\n */\nexport const local: EnvironmentConfig = {\n name: 'local',\n backend: 'http://localhost:3007/graphql',\n indexingTimeout: 60_000,\n pollingInterval: 1000,\n exchangeRateInterval: 10_000,\n swapQuoteInterval: 30_000,\n swapStatusInterval: 5_000,\n};\n","import type { Context } from '@aave/core';\nimport type { EnvironmentConfig } from '../../core/src/types';\nimport { exchange } from './cache';\nimport { production } from './environments';\n\n/**\n * The client configuration.\n */\nexport type ClientConfig = {\n /**\n * @internal\n * @defaultValue `production`\n */\n environment?: EnvironmentConfig;\n /**\n * @internal\n */\n headers?: Record<string, string>;\n /**\n * Whether to enable caching.\n *\n * @defaultValue `true`\n */\n cache?: boolean;\n /**\n * Whether to enable query batching.\n *\n * @defaultValue `true`\n */\n batch?: boolean;\n /**\n * Whether to enable debug mode.\n *\n * @defaultValue `false`\n */\n debug?: boolean;\n};\n\n/**\n * @internal\n */\nexport function configureContext({\n environment = production,\n headers,\n cache = true,\n batch = true,\n debug = false,\n}: ClientConfig): Context {\n return {\n displayName: 'AaveClient',\n environment,\n headers,\n cache: cache ? exchange : null,\n batch,\n debug,\n };\n}\n","import type {\n CancelError,\n SigningError,\n TransactionError,\n UnexpectedError,\n ValidationError,\n} from '@aave/core';\nimport type {\n ExecutionPlan,\n HasProcessedKnownTransactionRequest,\n InsufficientBalanceError,\n OperationType,\n PermitTypedData,\n SwapTypedData,\n} from '@aave/graphql';\nimport type { ResultAsync, Signature, TxHash } from '@aave/types';\n\n/**\n * @internal\n */\nexport type TransactionResult = {\n txHash: TxHash;\n operations: OperationType[] | null;\n};\n\n/**\n * @internal\n */\nexport function isHasProcessedKnownTransactionRequest(\n result: TransactionResult,\n): result is HasProcessedKnownTransactionRequest {\n return result.operations !== null && result.operations.length > 0;\n}\n\nexport type TransactionReceipt = {\n __typename: 'TransactionReceipt';\n txHash: TxHash;\n};\n\n/**\n * @internal\n */\nexport function transactionReceipt(txHash: TxHash): TransactionReceipt {\n return { __typename: 'TransactionReceipt', txHash };\n}\n\nexport type SendWithError =\n | CancelError\n | SigningError\n | TransactionError\n | ValidationError<InsufficientBalanceError>\n | UnexpectedError;\n\nexport type ExecutionPlanHandler<T extends ExecutionPlan = ExecutionPlan> = (\n result: T,\n) => ResultAsync<TransactionResult, SendWithError>;\n\nexport type SignTypedDataError = CancelError | SigningError;\n\n/**\n * Union type for all EIP-712 typed data structures used in the SDK.\n */\nexport type TypedData = PermitTypedData | SwapTypedData;\n\nexport type TypedDataHandler = (\n data: TypedData,\n) => ResultAsync<Signature, SignTypedDataError>;\n","import { delay, GqlClient, TimeoutError, UnexpectedError } from '@aave/core';\nimport type { HasProcessedKnownTransactionRequest } from '@aave/graphql';\nimport { invariant, ResultAsync } from '@aave/types';\nimport { hasProcessedKnownTransaction } from './actions';\nimport { type ClientConfig, configureContext } from './config';\nimport {\n isHasProcessedKnownTransactionRequest,\n type TransactionReceipt,\n type TransactionResult,\n transactionReceipt,\n} from './types';\n\nexport class AaveClient extends GqlClient {\n /**\n * Create a new instance of the {@link AaveClient}.\n *\n * ```ts\n * const client = AaveClient.create({\n * environment: production,\n * });\n * ```\n *\n * @param options - The options to configure the client.\n * @returns The new instance of the client.\n */\n static create(options?: ClientConfig): AaveClient {\n return new AaveClient(configureContext(options ?? {}));\n }\n\n /**\n * Given the transaction hash of an Aave protocol transaction, wait for the transaction to be\n * processed by the Aave v4 API.\n *\n * Returns a {@link TimeoutError} if the transaction is not processed within the expected timeout period.\n *\n * @param result - The transaction execution result to wait for.\n * @returns The {@link TransactionReceipt} or a error\n */\n readonly waitForTransaction = (\n result: TransactionResult,\n ): ResultAsync<TransactionReceipt, TimeoutError | UnexpectedError> => {\n invariant(\n isHasProcessedKnownTransactionRequest(result),\n 'AaveClient.waitForTransaction called with an non-tracked operation. See the documentation for correct tracking setup.',\n );\n\n return ResultAsync.fromPromise(\n this.pollTransactionStatus(result),\n (err) => {\n if (err instanceof TimeoutError || err instanceof UnexpectedError) {\n return err;\n }\n return UnexpectedError.from(err);\n },\n );\n };\n\n protected async pollTransactionStatus(\n request: HasProcessedKnownTransactionRequest,\n ): Promise<TransactionReceipt> {\n const startedAt = Date.now();\n\n while (Date.now() - startedAt < this.context.environment.indexingTimeout) {\n const processed = await hasProcessedKnownTransaction(this, request).match(\n (ok) => ok,\n (err) => {\n throw err;\n },\n );\n\n if (processed) {\n return transactionReceipt(request.txHash);\n }\n\n await delay(this.context.environment.pollingInterval);\n }\n throw TimeoutError.from(\n `Timeout waiting for transaction ${request.txHash} to be processed.`,\n );\n }\n}\n","import type { Erc20Approval, PermitTypedData } from '@aave/graphql';\nimport { isOneEntryArray } from '@aave/types';\n\ntype WithApprovals = { approvals: Erc20Approval[] };\n\nfunction hasApprovals(plan: unknown): plan is WithApprovals {\n return (\n typeof plan === 'object' &&\n plan !== null &&\n 'approvals' in plan &&\n Array.isArray(plan.approvals)\n );\n}\n\n/**\n * Checks if a plan supports permit (single approval with bySignature).\n * Works with union types - picks any member that has an `approvals` array\n * with a single entry containing `bySignature`.\n *\n * @internal\n */\nexport function supportsPermit<T>(plan: T): plan is T &\n Extract<T, WithApprovals> & {\n approvals: [Erc20Approval & { bySignature: PermitTypedData }];\n } {\n return (\n hasApprovals(plan) &&\n isOneEntryArray(plan.approvals) &&\n !!plan.approvals[0].bySignature\n );\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,12 +1,29 @@
1
1
  import { EnvironmentConfig } from '@aave/core';
2
2
  export * from '@aave/core';
3
+ import { Erc20Approval, PermitTypedData } from '@aave/graphql';
3
4
  export * from '@aave/graphql';
4
5
  export * from '@aave/types';
5
- export { A as AaveClient, C as ClientConfig } from './AaveClient-L3v8kWvn.cjs';
6
+ export { A as AaveClient, C as ClientConfig } from './AaveClient-wwfQOLJS.cjs';
6
7
  export { B as BatchOptions, C as CurrencyQueryOptions, D as DEFAULT_QUERY_OPTIONS, R as RequestPolicyOptions, T as TimeWindowQueryOptions } from './options-BX6n3sbh.cjs';
7
- export { a as ERC20PermitHandler, E as ExecutionPlanHandler, b as SendWithError, S as SwapSignatureHandler, T as TransactionResult, i as isHasProcessedKnownTransactionRequest } from './types-Bu63z0x6.cjs';
8
+ export { E as ExecutionPlanHandler, c as SendWithError, S as SignTypedDataError, d as TransactionReceipt, b as TransactionResult, a as TypedData, T as TypedDataHandler, i as isHasProcessedKnownTransactionRequest, t as transactionReceipt } from './types-XProSTZ7.cjs';
8
9
  import '@urql/core';
9
10
 
11
+ type WithApprovals = {
12
+ approvals: Erc20Approval[];
13
+ };
14
+ /**
15
+ * Checks if a plan supports permit (single approval with bySignature).
16
+ * Works with union types - picks any member that has an `approvals` array
17
+ * with a single entry containing `bySignature`.
18
+ *
19
+ * @internal
20
+ */
21
+ declare function supportsPermit<T>(plan: T): plan is T & Extract<T, WithApprovals> & {
22
+ approvals: [Erc20Approval & {
23
+ bySignature: PermitTypedData;
24
+ }];
25
+ };
26
+
10
27
  /**
11
28
  * The production environment configuration.
12
29
  */
@@ -20,4 +37,4 @@ declare const staging: EnvironmentConfig;
20
37
  */
21
38
  declare const local: EnvironmentConfig;
22
39
 
23
- export { local, production, staging };
40
+ export { local, production, staging, supportsPermit };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,29 @@
1
1
  import { EnvironmentConfig } from '@aave/core';
2
2
  export * from '@aave/core';
3
+ import { Erc20Approval, PermitTypedData } from '@aave/graphql';
3
4
  export * from '@aave/graphql';
4
5
  export * from '@aave/types';
5
- export { A as AaveClient, C as ClientConfig } from './AaveClient-CgHY2iS9.js';
6
+ export { A as AaveClient, C as ClientConfig } from './AaveClient-C7hQU3qX.js';
6
7
  export { B as BatchOptions, C as CurrencyQueryOptions, D as DEFAULT_QUERY_OPTIONS, R as RequestPolicyOptions, T as TimeWindowQueryOptions } from './options-BX6n3sbh.js';
7
- export { a as ERC20PermitHandler, E as ExecutionPlanHandler, b as SendWithError, S as SwapSignatureHandler, T as TransactionResult, i as isHasProcessedKnownTransactionRequest } from './types-Bu63z0x6.js';
8
+ export { E as ExecutionPlanHandler, c as SendWithError, S as SignTypedDataError, d as TransactionReceipt, b as TransactionResult, a as TypedData, T as TypedDataHandler, i as isHasProcessedKnownTransactionRequest, t as transactionReceipt } from './types-XProSTZ7.js';
8
9
  import '@urql/core';
9
10
 
11
+ type WithApprovals = {
12
+ approvals: Erc20Approval[];
13
+ };
14
+ /**
15
+ * Checks if a plan supports permit (single approval with bySignature).
16
+ * Works with union types - picks any member that has an `approvals` array
17
+ * with a single entry containing `bySignature`.
18
+ *
19
+ * @internal
20
+ */
21
+ declare function supportsPermit<T>(plan: T): plan is T & Extract<T, WithApprovals> & {
22
+ approvals: [Erc20Approval & {
23
+ bySignature: PermitTypedData;
24
+ }];
25
+ };
26
+
10
27
  /**
11
28
  * The production environment configuration.
12
29
  */
@@ -20,4 +37,4 @@ declare const staging: EnvironmentConfig;
20
37
  */
21
38
  declare const local: EnvironmentConfig;
22
39
 
23
- export { local, production, staging };
40
+ export { local, production, staging, supportsPermit };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {g as g$1}from'./chunk-3VL3Y3IZ.js';export{a as DEFAULT_QUERY_OPTIONS}from'./chunk-3VL3Y3IZ.js';import {GqlClient,UnexpectedError,TimeoutError,delay}from'@aave/core';export*from'@aave/core';import {encodeHubId,isTxHashInputVariant,isHubInputVariant}from'@aave/graphql';export*from'@aave/graphql';import {BigDecimal,ResultAsync,invariant}from'@aave/types';export*from'@aave/types';import P from'@aave/graphql/schema';import {cacheExchange}from'@urql/exchange-graphcache';var m=(e,t,n,a)=>BigInt(e[a.fieldName]),l=(e,t,n,a)=>BigDecimal.new(e[a.fieldName]),s=(e,t,n,a)=>{let i=e[a.fieldName];return i==null?null:l(e,t,n,a)},r=(e,t,n,a)=>new Date(e[a.fieldName]),E=(e,t,n,a)=>{let i=e[a.fieldName];return i==null?null:r(e,t,n,a)},v=cacheExchange({schema:P,resolvers:{PercentNumber:{onChainValue:m,value:l,normalized:l},DecimalNumber:{onChainValue:m,value:l},ExchangeAmount:{value:l},AssetPriceSample:{price:l,date:r},Reserve:{borrowCap:l,supplyCap:l},HealthFactorError:{current:s,after:s},HealthFactorVariation:{current:s,after:s},HealthFactorWithChange:{current:s},UserSummary:{lowestHealthFactor:s},UserSummaryHistoryItem:{healthFactor:s,date:r},TransactionRequest:{value:m},ApySample:{date:r},AssetBorrowSample:{date:r},AssetSupplySample:{date:r},ProtocolHistorySample:{date:r},BorrowActivity:{timestamp:r},LiquidatedActivity:{timestamp:r},RepayActivity:{timestamp:r},SupplyActivity:{timestamp:r},WithdrawActivity:{timestamp:r},UsingAsCollateralActivity:{timestamp:r},UpdatedDynamicConfigActivity:{timestamp:r},UpdatedRiskPremiumActivity:{timestamp:r},SpokeUserPositionManager:{approvedOn:r},SwapCancelled:{createdAt:r,cancelledAt:E},SwapExpired:{createdAt:r,expiredAt:r},SwapFulfilled:{createdAt:r,fulfilledAt:r},SwapOpen:{createdAt:r,deadline:r},SwapPendingSignature:{createdAt:r,deadline:r},SwapReceipt:{createdAt:r},Query:{hub:(e,{request:t})=>isHubInputVariant(t.query)?{__typename:"Hub",id:encodeHubId(t.query.hubInput)}:{__typename:"Hub",id:t.query.hubId},activities:(e,t,n)=>{if(!isTxHashInputVariant(t.request.query))return n.resolve("Query","activities",t);let{txHash:a,chainId:i}=t.request.query.txHash,d=n.inspectFields("Query").filter(o=>o.fieldName==="activities").reduce((o,y)=>{let u=n.resolve("Query",y.fieldKey);if(!u)return o;let p=n.resolve(u,"items");if(!p)return o;for(let c of p)o.add(c);return o},new Set).values().toArray().filter(o=>{if(n.resolve(o,"txHash")!==a)return false;let u=n.resolve(o,"spoke");if(u){let p=n.resolve(u,"chain"),c=p?n.resolve(p,"chainId"):void 0;if(typeof c=="number")return c===i}return true});if(d.length!==0)return {__typename:"PaginatedActivitiesResult",items:d,pageInfo:{__typename:"PaginatedResultInfo",prev:null,next:null}}}}},keys:{Hub:e=>e.id,HubAsset:e=>e.id,Reserve:e=>e.id,ReserveInfo:e=>e.id,Spoke:e=>e.id,BorrowActivity:e=>e.id,LiquidatedActivity:e=>e.id,SupplyActivity:e=>e.id,SwapByIntent:e=>e.quote.quoteId,SwapByIntentWithApprovalRequired:e=>e.quote.quoteId,SwapByTransaction:e=>e.quote.quoteId,UserPosition:e=>e.id,UpdatedDynamicConfigActivity:e=>e.id,UpdatedRiskPremiumActivity:e=>e.id,UsingAsCollateralActivity:e=>e.id,WithdrawActivity:e=>e.id,RepayActivity:e=>e.id,TokenInfo:e=>e.id,Erc20Token:e=>e.address,Chain:e=>e.chainId.toString(),NativeToken:e=>e.chain.chainId.toString(),PaginatedActivitiesResult:()=>null,PaginatedResultInfo:()=>null,PaginatedSpokePositionManagerResult:()=>null,PaginatedSpokeUserPositionManagerResult:()=>null,PaginatedUserSwapsResult:()=>null,SpokePositionManger:()=>null,SpokeUserPositionManager:()=>null,SwapReceipt:()=>null,SwapTransactionRequest:()=>null,ApySample:()=>null,Asset:()=>null,AssetBorrowSample:()=>null,AssetPriceSample:()=>null,AssetSummary:()=>null,AssetSupplySample:()=>null,CancelSwapTypedData:()=>null,CancelSwapTypeDefinition:()=>null,DecimalNumber:()=>null,DecimalNumberWithChange:()=>null,DomainData:()=>null,Erc20Amount:()=>null,Erc20ApprovalRequired:()=>null,ExchangeAmount:()=>null,ExchangeAmountValueVariation:()=>null,ExchangeAmountWithChange:()=>null,ForkTopUpResponse:()=>null,HealthFactorError:()=>null,HealthFactorVariation:()=>null,HealthFactorWithChange:()=>null,HubAssetSettings:()=>null,HubAssetSummary:()=>null,HubAssetUserState:()=>null,HubSummary:()=>null,InsufficientBalanceError:()=>null,NativeAmount:()=>null,PercentNumber:()=>null,PercentNumberVariation:()=>null,PercentNumberWithChange:()=>null,PermitMessageData:()=>null,PermitTypedDataResponse:()=>null,PreContractActionRequired:()=>null,PrepareSwapCancelResult:()=>null,PreviewUserPosition:()=>null,ProtocolHistorySample:()=>null,ReserveSettings:()=>null,ReserveStatus:()=>null,ReserveSummary:()=>null,ReserveUserState:()=>null,SwapApprovalRequired:()=>null,SwapByIntentTypedData:()=>null,SwapByIntentTypeDefinition:()=>null,SwapCancelled:()=>null,SwapExpired:()=>null,SwapFulfilled:()=>null,SwapOpen:()=>null,SwapPendingSignature:()=>null,SwapQuote:()=>null,SwapQuoteCosts:()=>null,TransactionRequest:()=>null,TypeDefinition:()=>null,TypeField:()=>null,UserBalance:()=>null,UserBorrowItem:()=>null,UserSummary:()=>null,UserSummaryHistoryItem:()=>null,UserSupplyItem:()=>null}});var g={name:"production",backend:"https://api.v4.aave.com/graphql",indexingTimeout:6e4,pollingInterval:100,exchangeRateInterval:1e4},F={name:"staging",backend:"https://api.v4.staging.aave.com/graphql",indexingTimeout:6e4,pollingInterval:500,exchangeRateInterval:1e4},Q={name:"local",backend:"http://localhost:3007/graphql",indexingTimeout:6e4,pollingInterval:1e3,exchangeRateInterval:1e4};function h({environment:e=g,headers:t,cache:n=true,debug:a=false,fragments:i=[]}){return {displayName:"AaveClient",environment:e,headers:t,cache:n?v:null,debug:a,fragments:i}}function S(e){return e.operations!==null&&e.operations.length>0}var R=class e extends GqlClient{static create(t){return new e(h(t??{}))}waitForTransaction=t=>(invariant(S(t),"Received a transaction result for an untracked operation. Make sure you're following the instructions in the docs."),ResultAsync.fromPromise(this.pollTransactionStatus(t),n=>n instanceof TimeoutError||n instanceof UnexpectedError?n:UnexpectedError.from(n)));async refreshQueryWhere(t,n){await this.refreshWhere(async a=>{if(a.query===t){let i=await this.query(t,a.variables,{requestPolicy:"cache-only"});return i.isErr()?false:n(a.variables,i.value)}return false});}async pollTransactionStatus(t){let n=Date.now();for(;Date.now()-n<this.context.environment.indexingTimeout;){if(await g$1(this,t).match(i=>i,i=>{throw i}))return t.txHash;await delay(this.context.environment.pollingInterval);}throw TimeoutError.from(`Timeout waiting for transaction ${t.txHash} to be processed.`)}};
2
- export{R as AaveClient,Q as local,g as production,F as staging};//# sourceMappingURL=index.js.map
1
+ export{a as supportsPermit}from'./chunk-N4LXBTGY.js';import {i}from'./chunk-HH6OAH2K.js';export{a as DEFAULT_QUERY_OPTIONS}from'./chunk-HH6OAH2K.js';import {GqlClient,TimeoutError,UnexpectedError,delay}from'@aave/core';export*from'@aave/core';import {isTxHashInputVariant,decodeSpokeId,encodeUserPositionId,isReserveInputVariant,encodeReserveId,isHubInputVariant,encodeHubId}from'@aave/graphql';export*from'@aave/graphql';import {BigDecimal,invariant,ResultAsync}from'@aave/types';export*from'@aave/types';import D from'@aave/graphql/schema';import {cacheExchange}from'@urql/exchange-graphcache';var d=(e,r,a,n)=>BigInt(e[n.fieldName]),s=(e,r,a,n)=>BigDecimal.new(e[n.fieldName]),p=(e,r,a,n)=>{let i=e[n.fieldName];return i==null?null:s(e,r,a,n)},t=(e,r,a,n)=>new Date(e[n.fieldName]),l=(e,r,a,n)=>{let i=e[n.fieldName];return i==null?null:t(e,r,a,n)},R=cacheExchange({schema:D,resolvers:{PercentNumber:{onChainValue:d,value:s,normalized:s},DecimalNumber:{onChainValue:d,value:s},ExchangeAmount:{value:s},AssetPriceSample:{price:s,date:t},PermitTypedData:{signedAmount:s},HealthFactorError:{current:p,after:p},HealthFactorVariation:{current:p,after:p},HealthFactorWithChange:{current:p},UserSummary:{lowestHealthFactor:p},UserSummaryHistoryItem:{healthFactor:p,date:t},TransactionRequest:{value:d},ApySample:{date:t},AssetBorrowSample:{date:t},AssetSupplySample:{date:t},HubSummarySample:{date:t},BorrowPointsReward:{startDate:t,endDate:l},PreviewBorrowPointsReward:{startDate:t,endDate:l},PreviewMerklBorrowReward:{startDate:t,endDate:t},PreviewMerklSupplyReward:{startDate:t,endDate:t},PreviewSupplyPointsReward:{startDate:t,endDate:l},SupplyPointsReward:{startDate:t,endDate:l},ProtocolHistorySample:{date:t},BorrowActivity:{timestamp:t},LiquidatedActivity:{timestamp:t},MerklBorrowReward:{startDate:t,endDate:t},MerklSupplyReward:{startDate:t,endDate:t},RepayActivity:{timestamp:t},SupplyActivity:{timestamp:t},WithdrawActivity:{timestamp:t},UsingAsCollateralActivity:{timestamp:t},UpdatedDynamicConfigActivity:{timestamp:t},UpdatedRiskPremiumActivity:{timestamp:t},TokenSwapActivity:{timestamp:t},SupplySwapActivity:{timestamp:t},BorrowSwapActivity:{timestamp:t},RepayWithSupplyActivity:{timestamp:t},WithdrawSwapActivity:{timestamp:t},UserMerklClaimableReward:{startDate:t,endDate:t,claimUntil:t},UserPosition:{createdAt:t},UserBorrowItem:{createdAt:l},UserSupplyItem:{createdAt:l},SpokeUserPositionManager:{approvedOn:t},SwapCancelled:{createdAt:t,cancelledAt:l},SwapCancelledResult:{createdAt:t,cancelledAt:l},SwapExpired:{createdAt:t,expiredAt:t},SwapFulfilled:{createdAt:t,fulfilledAt:t},SwapOpen:{createdAt:t,deadline:t},SwapPendingSignature:{createdAt:t,deadline:t},SwapReceipt:{createdAt:t},StableVaultSummary:{shares:d,totalDeposits:s,userCount:d},StableVaultWithdrawClaim:{executableAfter:t},TokenMovementRecord:{timestamp:t},StableVaultPendingAvailability:{executableAfter:t},Query:{hub:(e,{request:r})=>isHubInputVariant(r.query)?{__typename:"Hub",id:encodeHubId(r.query.hubInput)}:{__typename:"Hub",id:r.query.hubId},reserve:(e,{request:r})=>isReserveInputVariant(r.query)?{__typename:"Reserve",id:encodeReserveId(r.query.reserveInput)}:{__typename:"Reserve",id:r.query.reserveId},userPosition:(e,{request:r})=>{if("userSpoke"in r&&r.userSpoke){let{chainId:a,address:n}=decodeSpokeId(r.userSpoke.spoke);return {__typename:"UserPosition",id:encodeUserPositionId({chainId:a,spoke:n,user:r.userSpoke.user})}}if("id"in r&&r.id)return {__typename:"UserPosition",id:r.id}},activities:(e,r,a)=>{if(!isTxHashInputVariant(r.request.query))return a.resolve("Query","activities",r);let{txHash:n,chainId:i}=r.request.query.txHash,v=a.inspectFields("Query").filter(o=>o.fieldName==="activities").reduce((o,S)=>{let u=a.resolve("Query",S.fieldKey);if(!u)return o;let c=a.resolve(u,"items");if(!c)return o;for(let y of c)o.add(y);return o},new Set).values().toArray().filter(o=>{if(a.resolve(o,"txHash")!==n)return false;let u=a.resolve(o,"spoke");if(u){let c=a.resolve(u,"chain"),y=c?a.resolve(c,"chainId"):void 0;if(typeof y=="number")return y===i}return true});if(v.length!==0)return {__typename:"PaginatedActivitiesResult",items:v,pageInfo:{__typename:"PaginatedResultInfo",prev:null,next:null}}}}},keys:{Asset:e=>e.id,BorrowActivity:e=>e.id,BorrowPointsReward:e=>e.id,BorrowSwapActivity:e=>e.id,BoostedRate:e=>e.id,Hub:e=>e.id,HubAsset:e=>e.id,LiquidatedActivity:e=>e.id,MerklBorrowReward:e=>e.id,MerklGenericCriteria:e=>e.id,MerklSupplyReward:e=>e.id,PointsGenericCriteria:e=>e.id,PointsProgram:e=>e.id,RepayActivity:e=>e.id,RepayWithSupplyActivity:e=>e.id,Reserve:e=>e.id,ReserveInfo:e=>e.id,Spoke:e=>e.id,StableVault:e=>e.id,StableVaultUserPosition:e=>e.id,SupplyActivity:e=>e.id,SupplyPointsReward:e=>e.id,SupplySwapActivity:e=>e.id,TokenInfo:e=>e.id,TokenMovementRecord:e=>e.id,TokenSwapActivity:e=>e.id,UpdatedDynamicConfigActivity:e=>e.id,UpdatedRiskPremiumActivity:e=>e.id,UserMerklClaimableReward:e=>e.id,UserPosition:e=>e.id,UsingAsCollateralActivity:e=>e.id,WithdrawActivity:e=>e.id,WithdrawSwapActivity:e=>e.id,Erc20Token:e=>e.address,Chain:e=>e.chainId.toString(),NativeToken:e=>e.chain.chainId.toString(),ApySample:()=>null,AssetAmountWithChange:()=>null,AssetBorrowSample:()=>null,AssetPriceSample:()=>null,AssetSampleBreakdown:()=>null,AssetSummary:()=>null,AssetSupplySample:()=>null,BorrowSwap:()=>null,BorrowSwapQuoteResult:()=>null,CollateralFactorVariation:()=>null,DecimalNumber:()=>null,DecimalNumberWithChange:()=>null,DomainData:()=>null,Erc20Amount:()=>null,Erc20Approval:()=>null,Erc20ApprovalRequired:()=>null,ExchangeAmount:()=>null,ExchangeAmountVariation:()=>null,ExchangeAmountWithChange:()=>null,ForkTopUpResponse:()=>null,HealthFactorError:()=>null,HealthFactorVariation:()=>null,HealthFactorWithChange:()=>null,HubAssetInterestRateModelPoint:()=>null,HubAssetInterestRateModelResult:()=>null,HubAssetSettings:()=>null,HubAssetSummary:()=>null,HubAssetUserState:()=>null,HubSummary:()=>null,HubSummarySample:()=>null,InsufficientBalanceError:()=>null,InsufficientLiquidityError:()=>null,LiquidationFeeVariation:()=>null,MaxLiquidationBonusVariation:()=>null,NativeAmount:()=>null,PaginatedActivitiesResult:()=>null,PaginatedResultInfo:()=>null,PaginatedSpokePositionManagerResult:()=>null,PaginatedSpokeUserPositionManagerResult:()=>null,PaginatedStableVaultMovementsResult:()=>null,PaginatedStableVaultRateUsersResult:()=>null,PaginatedUserSwapsResult:()=>null,PercentNumber:()=>null,PercentNumberChangeSnapshot:()=>null,PercentNumberVariation:()=>null,PercentNumberWithChange:()=>null,PermitTypedData:()=>null,PositionAmount:()=>null,PositionSwapAdapterContractApproval:()=>null,PositionSwapByIntentApprovalsRequired:()=>null,PositionSwapPositionManagerApproval:()=>null,PreContractActionRequired:()=>null,PrepareSwapCancelResult:()=>null,PrepareSwapOrder:()=>null,PreviewBorrowPointsReward:()=>null,PreviewMerklBorrowReward:()=>null,PreviewMerklSupplyReward:()=>null,PreviewReserveRates:()=>null,PreviewRewardOutcome:()=>null,PreviewSupplyPointsReward:()=>null,PreviewUserPosition:()=>null,ProtocolHistorySample:()=>null,RepayWithSupply:()=>null,RepayWithSupplyQuoteResult:()=>null,ReserveSettings:()=>null,ReserveStatus:()=>null,ReserveSummary:()=>null,ReserveUserState:()=>null,SpokePositionManager:()=>null,SpokeUserPositionManager:()=>null,StableVaultPendingAvailability:()=>null,StableVaultRates:()=>null,StableVaultSummary:()=>null,StableVaultWithdrawClaim:()=>null,SupplySwap:()=>null,SupplySwapQuoteResult:()=>null,SwapByIntent:()=>null,SwapByIntentWithApprovalRequired:()=>null,SwapByTransaction:()=>null,SwapCancelled:()=>null,SwapCancelledResult:()=>null,SwapExpired:()=>null,SwapFulfilled:()=>null,SwapOpen:()=>null,SwapPendingSignature:()=>null,SwapQuote:()=>null,SwapQuoteCosts:()=>null,SwapReceipt:()=>null,SwapTransactionRequest:()=>null,SwapTypedData:()=>null,TokenMovementAllocate:()=>null,TokenMovementBridgeIn:()=>null,TokenMovementBridgeOut:()=>null,TokenMovementDeallocate:()=>null,TokenMovementRebalance:()=>null,TokenMovementSwap:()=>null,TokenSwap:()=>null,TokenSwapQuoteResult:()=>null,TransactionRequest:()=>null,UserBalance:()=>null,UserBorrowItem:()=>null,UserPositionRiskPremium:()=>null,UserRiskPremiumBreakdownItem:()=>null,UserSummary:()=>null,UserSummaryHistoryItem:()=>null,UserSupplyItem:()=>null,WithdrawSwap:()=>null,WithdrawSwapQuoteResult:()=>null}});var f={name:"production",backend:"https://api.aave.com/graphql",indexingTimeout:6e4,pollingInterval:100,exchangeRateInterval:1e4,swapQuoteInterval:3e4,swapStatusInterval:5e3},L={name:"staging",backend:"https://api.staging.aave.com/graphql",indexingTimeout:6e4,pollingInterval:500,exchangeRateInterval:1e4,swapQuoteInterval:3e4,swapStatusInterval:5e3},z={name:"local",backend:"http://localhost:3007/graphql",indexingTimeout:6e4,pollingInterval:1e3,exchangeRateInterval:1e4,swapQuoteInterval:3e4,swapStatusInterval:5e3};function A({environment:e=f,headers:r,cache:a=true,batch:n=true,debug:i=false}){return {displayName:"AaveClient",environment:e,headers:r,cache:a?R:null,batch:n,debug:i}}function g(e){return e.operations!==null&&e.operations.length>0}function m(e){return {__typename:"TransactionReceipt",txHash:e}}var T=class e extends GqlClient{static create(r){return new e(A(r??{}))}waitForTransaction=r=>(invariant(g(r),"AaveClient.waitForTransaction called with an non-tracked operation. See the documentation for correct tracking setup."),ResultAsync.fromPromise(this.pollTransactionStatus(r),a=>a instanceof TimeoutError||a instanceof UnexpectedError?a:UnexpectedError.from(a)));async pollTransactionStatus(r){let a=Date.now();for(;Date.now()-a<this.context.environment.indexingTimeout;){if(await i(this,r).match(i=>i,i=>{throw i}))return m(r.txHash);await delay(this.context.environment.pollingInterval);}throw TimeoutError.from(`Timeout waiting for transaction ${r.txHash} to be processed.`)}};
2
+ export{T as AaveClient,z as local,f as production,L as staging,m as transactionReceipt};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map