@huma-finance/sdk 0.0.39 → 0.0.41

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 (135) hide show
  1. package/API.md +45 -9
  2. package/dist/cjs/graphql/generatedTypes.d.ts +40 -0
  3. package/dist/cjs/graphql/generatedTypes.js +9 -0
  4. package/dist/cjs/graphql/generatedTypes.js.map +1 -0
  5. package/dist/cjs/graphql/index.d.ts +1 -0
  6. package/dist/cjs/graphql/index.js +5 -0
  7. package/dist/cjs/graphql/index.js.map +1 -0
  8. package/dist/cjs/helpers/ERC20TransferableReceivableContractHelper.d.ts +10 -0
  9. package/dist/cjs/helpers/ERC20TransferableReceivableContractHelper.js +22 -0
  10. package/dist/cjs/helpers/ERC20TransferableReceivableContractHelper.js.map +1 -0
  11. package/dist/cjs/helpers/PoolContractHelper.d.ts +119 -0
  12. package/dist/cjs/helpers/PoolContractHelper.js +144 -0
  13. package/dist/cjs/helpers/PoolContractHelper.js.map +1 -0
  14. package/dist/cjs/helpers/RealWorldReceivableContractHelper.d.ts +10 -0
  15. package/dist/cjs/helpers/RealWorldReceivableContractHelper.js +22 -0
  16. package/dist/cjs/helpers/RealWorldReceivableContractHelper.js.map +1 -0
  17. package/dist/cjs/helpers/index.d.ts +3 -0
  18. package/dist/cjs/helpers/index.js +7 -0
  19. package/dist/cjs/helpers/index.js.map +1 -0
  20. package/dist/cjs/hooks/index.d.ts +4 -0
  21. package/dist/cjs/hooks/index.js +8 -0
  22. package/dist/cjs/hooks/index.js.map +1 -0
  23. package/dist/cjs/hooks/useContract.d.ts +13 -0
  24. package/dist/cjs/hooks/useContract.js +31 -0
  25. package/dist/cjs/hooks/useContract.js.map +1 -0
  26. package/dist/cjs/hooks/useERC20TransferableReceivableContract.d.ts +12 -0
  27. package/dist/cjs/hooks/useERC20TransferableReceivableContract.js +21 -0
  28. package/dist/cjs/hooks/useERC20TransferableReceivableContract.js.map +1 -0
  29. package/dist/cjs/hooks/usePoolContract.d.ts +60 -0
  30. package/dist/cjs/hooks/usePoolContract.js +54 -0
  31. package/dist/cjs/hooks/usePoolContract.js.map +1 -0
  32. package/dist/cjs/hooks/useRealWorldReceivableContract.d.ts +10 -0
  33. package/dist/cjs/hooks/useRealWorldReceivableContract.js +20 -0
  34. package/dist/cjs/hooks/useRealWorldReceivableContract.js.map +1 -0
  35. package/dist/cjs/index.d.ts +4 -0
  36. package/dist/cjs/index.js +8 -0
  37. package/dist/cjs/index.js.map +1 -0
  38. package/dist/cjs/services/ARWeaveService.d.ts +117 -0
  39. package/dist/cjs/services/ARWeaveService.js +204 -0
  40. package/dist/cjs/services/ARWeaveService.js.map +1 -0
  41. package/dist/cjs/services/EAService.d.ts +20 -0
  42. package/dist/cjs/services/EAService.js +34 -0
  43. package/dist/cjs/services/EAService.js.map +1 -0
  44. package/dist/cjs/services/ReceivableService.d.ts +142 -0
  45. package/dist/cjs/services/ReceivableService.js +330 -0
  46. package/dist/cjs/services/ReceivableService.js.map +1 -0
  47. package/dist/cjs/services/SubgraphService.d.ts +53 -0
  48. package/dist/cjs/services/SubgraphService.js +94 -0
  49. package/dist/cjs/services/SubgraphService.js.map +1 -0
  50. package/dist/cjs/services/index.d.ts +4 -0
  51. package/dist/cjs/services/index.js +8 -0
  52. package/dist/cjs/services/index.js.map +1 -0
  53. package/dist/cjs/utils/chain.d.ts +15 -0
  54. package/dist/cjs/utils/chain.js +38 -0
  55. package/dist/cjs/utils/chain.js.map +1 -0
  56. package/dist/cjs/utils/index.d.ts +4 -0
  57. package/dist/cjs/utils/index.js +8 -0
  58. package/dist/cjs/utils/index.js.map +1 -0
  59. package/dist/cjs/utils/maticGasStation.d.ts +3 -0
  60. package/dist/cjs/utils/maticGasStation.js +39 -0
  61. package/dist/cjs/utils/maticGasStation.js.map +1 -0
  62. package/dist/cjs/utils/poolInfo.d.ts +8 -0
  63. package/dist/cjs/utils/poolInfo.js +13 -0
  64. package/dist/cjs/utils/poolInfo.js.map +1 -0
  65. package/dist/cjs/utils/web3.d.ts +5 -0
  66. package/dist/cjs/utils/web3.js +34 -0
  67. package/dist/cjs/utils/web3.js.map +1 -0
  68. package/dist/graphql/generatedTypes.d.ts +40 -0
  69. package/dist/graphql/generatedTypes.js +5 -0
  70. package/dist/graphql/generatedTypes.js.map +1 -0
  71. package/dist/graphql/index.d.ts +1 -0
  72. package/dist/graphql/index.js +2 -0
  73. package/dist/graphql/index.js.map +1 -0
  74. package/dist/helpers/ERC20TransferableReceivableContractHelper.d.ts +10 -0
  75. package/dist/helpers/ERC20TransferableReceivableContractHelper.js +18 -0
  76. package/dist/helpers/ERC20TransferableReceivableContractHelper.js.map +1 -0
  77. package/dist/helpers/PoolContractHelper.d.ts +119 -0
  78. package/dist/helpers/PoolContractHelper.js +135 -0
  79. package/dist/helpers/PoolContractHelper.js.map +1 -0
  80. package/dist/helpers/RealWorldReceivableContractHelper.d.ts +10 -0
  81. package/dist/helpers/RealWorldReceivableContractHelper.js +18 -0
  82. package/dist/helpers/RealWorldReceivableContractHelper.js.map +1 -0
  83. package/dist/helpers/index.d.ts +3 -0
  84. package/dist/helpers/index.js +4 -0
  85. package/dist/helpers/index.js.map +1 -0
  86. package/dist/hooks/index.d.ts +4 -0
  87. package/dist/hooks/index.js +5 -0
  88. package/dist/hooks/index.js.map +1 -0
  89. package/dist/hooks/useContract.d.ts +13 -0
  90. package/dist/hooks/useContract.js +27 -0
  91. package/dist/hooks/useContract.js.map +1 -0
  92. package/dist/hooks/useERC20TransferableReceivableContract.d.ts +12 -0
  93. package/dist/hooks/useERC20TransferableReceivableContract.js +17 -0
  94. package/dist/hooks/useERC20TransferableReceivableContract.js.map +1 -0
  95. package/dist/hooks/usePoolContract.d.ts +60 -0
  96. package/dist/hooks/usePoolContract.js +49 -0
  97. package/dist/hooks/usePoolContract.js.map +1 -0
  98. package/dist/hooks/useRealWorldReceivableContract.d.ts +10 -0
  99. package/dist/hooks/useRealWorldReceivableContract.js +16 -0
  100. package/dist/hooks/useRealWorldReceivableContract.js.map +1 -0
  101. package/dist/index.d.ts +4 -0
  102. package/dist/index.js +5 -0
  103. package/dist/index.js.map +1 -0
  104. package/dist/services/ARWeaveService.d.ts +117 -0
  105. package/dist/services/ARWeaveService.js +199 -0
  106. package/dist/services/ARWeaveService.js.map +1 -0
  107. package/dist/services/EAService.d.ts +20 -0
  108. package/dist/services/EAService.js +31 -0
  109. package/dist/services/EAService.js.map +1 -0
  110. package/dist/services/ReceivableService.d.ts +142 -0
  111. package/dist/services/ReceivableService.js +327 -0
  112. package/dist/services/ReceivableService.js.map +1 -0
  113. package/dist/services/SubgraphService.d.ts +53 -0
  114. package/dist/services/SubgraphService.js +91 -0
  115. package/dist/services/SubgraphService.js.map +1 -0
  116. package/dist/services/index.d.ts +4 -0
  117. package/dist/services/index.js +5 -0
  118. package/dist/services/index.js.map +1 -0
  119. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  120. package/dist/utils/chain.d.ts +15 -0
  121. package/dist/utils/chain.js +32 -0
  122. package/dist/utils/chain.js.map +1 -0
  123. package/dist/utils/index.d.ts +4 -0
  124. package/dist/utils/index.js +5 -0
  125. package/dist/utils/index.js.map +1 -0
  126. package/dist/utils/maticGasStation.d.ts +3 -0
  127. package/dist/utils/maticGasStation.js +34 -0
  128. package/dist/utils/maticGasStation.js.map +1 -0
  129. package/dist/utils/poolInfo.d.ts +8 -0
  130. package/dist/utils/poolInfo.js +9 -0
  131. package/dist/utils/poolInfo.js.map +1 -0
  132. package/dist/utils/web3.d.ts +5 -0
  133. package/dist/utils/web3.js +28 -0
  134. package/dist/utils/web3.js.map +1 -0
  135. package/package.json +3 -3
@@ -0,0 +1,142 @@
1
+ import { TransactionResponse, Web3Provider } from '@ethersproject/providers';
2
+ import { BigNumberish, ethers, Overrides } from 'ethers';
3
+ import { POOL_NAME, POOL_TYPE, RealWorldReceivableInfo } from '@huma-finance/shared';
4
+ /**
5
+ * Fetches the tokenId of a RealWorldReceivable, or null if it doesn't exist, given a metadata URI
6
+ *
7
+ * @async
8
+ * @function
9
+ * @memberof ReceivableService
10
+ * @param {ethers.Signer} signer - The signer used to lookup metadata uploads for
11
+ * @param {string} arweaveId - The internal ARWeave identifier to lookup a token by
12
+ * @returns {Promise<string | null | undefined>} - Either the token Id or null if no token was found.
13
+ */
14
+ declare function getTokenIdByURI(signer: ethers.Signer, uri: string | null): Promise<string | null | undefined>;
15
+ /**
16
+ * Declares a payment on a RealWorldReceivable given a reference Id of the receivable, which was used as an index for ARWeave data.
17
+ *
18
+ * @async
19
+ * @function
20
+ * @memberof ReceivableService
21
+ * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
22
+ * @param {string} referenceId - An internal identifier value added as a tag on ARWeave
23
+ * @param {number} paymentAmount - The amount to declare paid to the receivable.
24
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
25
+ * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
26
+ */
27
+ declare function declareReceivablePaymentByReferenceId(signer: ethers.Signer, referenceId: string, paymentAmount: number, gasOpts?: Overrides): Promise<TransactionResponse>;
28
+ /**
29
+ * Declares a payment on a RealWorldReceivable given a tokenId of the receivable.
30
+ *
31
+ * @async
32
+ * @function
33
+ * @memberof ReceivableService
34
+ * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
35
+ * @param {BigNumberish} receivableTokenId - The Id of the receivable token to pay.
36
+ * @param {number} paymentAmount - The amount to pay the receivable.
37
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
38
+ * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
39
+ * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network.
40
+ */
41
+ declare function declareReceivablePaymentByTokenId(signer: ethers.Signer, receivableTokenId: BigNumberish, paymentAmount: number, gasOpts?: Overrides): Promise<TransactionResponse>;
42
+ /**
43
+ * Creates a new RealWorldReceivable token on the given chain of the signer
44
+ *
45
+ * @async
46
+ * @function
47
+ * @memberof ReceivableService
48
+ * @param {ethers.Signer} signer - The signer used to send the transaction.
49
+ * @param {POOL_NAME} poolName - The name of the credit pool to mint the receivable token from. Used to lookup the pool address.
50
+ * @param {POOL_TYPE} poolType - The type of the credit pool to mint the receivable token from. Used to lookup the pool address.
51
+ * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
52
+ * @param {number} receivableAmount - The amount of the receivable token to mint.
53
+ * @param {number} maturityDate - The maturity date of the receivable token, in UNIX timestamp format.
54
+ * @param {string} uri - The URI of the receivable token metadata.
55
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
56
+ * @returns {Promise<TransactionResponse | null>} - A Promise of the transaction response.
57
+ * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network, or if a token already exists with the same metadata URI.
58
+ */
59
+ declare function createReceivable(signer: ethers.Signer, poolName: POOL_NAME, poolType: POOL_TYPE, currencyCode: number, receivableAmount: number, maturityDate: number, uri: string, gasOpts?: Overrides): Promise<TransactionResponse>;
60
+ /**
61
+ * Uploads metadata onto ARWeave (or fetches the existing metadata with the same reference Id) and returns the ARWeave URL
62
+ *
63
+ * @async
64
+ * @function
65
+ * @memberof ReceivableService
66
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
67
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
68
+ * from server calls.
69
+ * @param {string | null} privateKey - Private key of the wallet used to upload metadata to ARWeave. Only required if calling this function from a server.
70
+ * @param {number} chainId - The chain ID to mint the receivable token on and pay ARWeave funds from.
71
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
72
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
73
+ * @param {Record<string, any>} metadata - The metadata in JSON format. This will be uploaded onto ARWeave
74
+ * @param {string} referenceId - An internal identifier value added as a tag on ARWeave, for easily querying the metadata later.
75
+ * @param {Array<{ name: string, value: string }>} extraTags - Any extraTags you'd like to tag your metadata with. Note that metadata on
76
+ * ARWeave is indexed by these tags, so make sure to include any tags that you'd like to be able to query by.
77
+ * @param {boolean} [lazyFund=true] - Whether to lazy fund the ARWeave uploads. If true, the ARWeave uploads will be paid for by the
78
+ * metadata uploader immediately before uploading. If false, the ARWeave node must be pre-funded before calling this function.
79
+ * @returns {Promise<string>} - The ARWeave metadata URI.
80
+ */
81
+ declare function uploadOrFetchMetadataURI(signerOrProvider: Web3Provider | ethers.Signer, privateKey: string | null, chainId: number, poolName: POOL_NAME, poolType: POOL_TYPE, metadata: Record<string, unknown>, referenceId: string, extraTags: {
82
+ name: string;
83
+ value: string;
84
+ }[], lazyFund?: boolean): Promise<string>;
85
+ /**
86
+ * Creates a RealWorldReceivable token with metadata uploaded onto ARWeave
87
+ *
88
+ * @async
89
+ * @function
90
+ * @memberof ReceivableService
91
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
92
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
93
+ * from server calls.
94
+ * @param {string | null} privateKey - Private key of the wallet used to upload metadata to ARWeave. Only required if calling this function from a server.
95
+ * @param {number} chainId - The chain ID to mint the receivable token on and pay ARWeave funds from.
96
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
97
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
98
+ * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
99
+ * @param {number} receivableAmount - The receivable amount.
100
+ * @param {number} maturityDate - The maturity date of the receivable, in UNIX timestamp format.
101
+ * @param {Record<string, any>} metadata - The metadata in JSON format. This will be uploaded onto ARWeave
102
+ * @param {string} referenceId - An internal identifier value added as a tag on ARWeave, for easily querying the metadata later.
103
+ * @param {Array<{ name: string, value: string }>} extraTags - Any extraTags you'd like to tag your metadata with. Note that metadata on
104
+ * ARWeave is indexed by these tags, so make sure to include any tags that you'd like to be able to query by.
105
+ * @param {boolean} [lazyFund=true] - Whether to lazy fund the ARWeave uploads. If true, the ARWeave uploads will be paid for by the
106
+ * metadata uploader immediately before uploading. If false, the ARWeave node must be pre-funded before calling this function.
107
+ * @param {Overrides} [gasOpts] - Optional gas overrides for the transaction.
108
+ * @returns {Promise<TransactionResponse>} - The transaction receipt.
109
+ */
110
+ declare function createReceivableWithMetadata(signerOrProvider: Web3Provider | ethers.Signer, privateKey: string | null, chainId: number, poolName: POOL_NAME, poolType: POOL_TYPE, currencyCode: number, receivableAmount: number, maturityDate: number, metadata: Record<string, unknown>, referenceId: string, extraTags: {
111
+ name: string;
112
+ value: string;
113
+ }[], lazyFund?: boolean, gasOpts?: Overrides): Promise<TransactionResponse>;
114
+ /**
115
+ * Loads all RWRs belonging to the specified owner, including the RWR metadata
116
+ *
117
+ * @async
118
+ * @function
119
+ * @memberof ReceivableService
120
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
121
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
122
+ * from server calls.
123
+ * @param {string} owner - The receivable token owner to query from.
124
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
125
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
126
+ * @returns {Promise<RealWorldReceivableInfo[]>} - An array of receivables owned by the owner for the pool.
127
+ */
128
+ declare function loadReceivablesOfOwnerWithMetadata<T>(signerOrProvider: Web3Provider | ethers.Signer, owner: string, poolName: POOL_NAME, poolType: POOL_TYPE): Promise<RealWorldReceivableInfo<T>[]>;
129
+ /**
130
+ * An object that contains functions to interact with Huma's receivables.
131
+ * @namespace ReceivableService
132
+ */
133
+ export declare const ReceivableService: {
134
+ createReceivableWithMetadata: typeof createReceivableWithMetadata;
135
+ createReceivable: typeof createReceivable;
136
+ declareReceivablePaymentByTokenId: typeof declareReceivablePaymentByTokenId;
137
+ declareReceivablePaymentByReferenceId: typeof declareReceivablePaymentByReferenceId;
138
+ loadReceivablesOfOwnerWithMetadata: typeof loadReceivablesOfOwnerWithMetadata;
139
+ uploadOrFetchMetadataURI: typeof uploadOrFetchMetadataURI;
140
+ getTokenIdByURI: typeof getTokenIdByURI;
141
+ };
142
+ export {};
@@ -0,0 +1,330 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ReceivableService = void 0;
4
+ const providers_1 = require("@ethersproject/providers");
5
+ const ethers_1 = require("ethers");
6
+ const shared_1 = require("@huma-finance/shared");
7
+ const graphql_request_1 = require("graphql-request");
8
+ const ARWeaveService_1 = require("./ARWeaveService");
9
+ const helpers_1 = require("../helpers");
10
+ const utils_1 = require("../utils");
11
+ /**
12
+ * Fetches the tokenId of a RealWorldReceivable, or null if it doesn't exist, given a metadata URI
13
+ *
14
+ * @async
15
+ * @function
16
+ * @memberof ReceivableService
17
+ * @param {ethers.Signer} signer - The signer used to lookup metadata uploads for
18
+ * @param {string} arweaveId - The internal ARWeave identifier to lookup a token by
19
+ * @returns {Promise<string | null | undefined>} - Either the token Id or null if no token was found.
20
+ */
21
+ async function getTokenIdByURI(signer, uri) {
22
+ var _a, _b, _c, _d;
23
+ if (uri === null) {
24
+ return null;
25
+ }
26
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
27
+ const signerAddress = await signer.getAddress();
28
+ if (!chainId) {
29
+ throw new Error('No Chain Id found');
30
+ }
31
+ // Fetch receivables with the same ARWeave Id
32
+ const receivablesQuery = (0, graphql_request_1.gql) `
33
+ query ReceivablesByURIQuery($owner: String!, $uri: String!) {
34
+ receivables(where: { owner: $owner, uri: $uri }) {
35
+ ...ReceivableFields
36
+ }
37
+ }
38
+
39
+ fragment ReceivableFields on Receivable {
40
+ tokenId
41
+ }
42
+ `;
43
+ const receivableSubgraph = (_a = shared_1.PoolSubgraphMap[chainId]) === null || _a === void 0 ? void 0 : _a.receivablesSubgraph;
44
+ if (!receivableSubgraph) {
45
+ throw new Error('No receivable subgraph exists for this chain');
46
+ }
47
+ const receivablesData = await (0, graphql_request_1.request)(receivableSubgraph, receivablesQuery, {
48
+ owner: signerAddress,
49
+ uri,
50
+ });
51
+ if (!((_b = receivablesData === null || receivablesData === void 0 ? void 0 : receivablesData.receivables) === null || _b === void 0 ? void 0 : _b.length)) {
52
+ console.log('No receivables found with this URI.');
53
+ return null;
54
+ }
55
+ if (((_c = receivablesData === null || receivablesData === void 0 ? void 0 : receivablesData.receivables) === null || _c === void 0 ? void 0 : _c.length) > 1) {
56
+ throw new Error(`This owner has multiple receivables with the same URI, so we don't know which to use. Please burn
57
+ unnecessary receivables. If paying, you can pay the correct token manually using declareReceivablePaymentByTokenId`);
58
+ }
59
+ return (_d = receivablesData === null || receivablesData === void 0 ? void 0 : receivablesData.receivables[0]) === null || _d === void 0 ? void 0 : _d.tokenId;
60
+ }
61
+ /**
62
+ * Declares a payment on a RealWorldReceivable given a reference Id of the receivable, which was used as an index for ARWeave data.
63
+ *
64
+ * @async
65
+ * @function
66
+ * @memberof ReceivableService
67
+ * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
68
+ * @param {string} referenceId - An internal identifier value added as a tag on ARWeave
69
+ * @param {number} paymentAmount - The amount to declare paid to the receivable.
70
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
71
+ * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
72
+ */
73
+ async function declareReceivablePaymentByReferenceId(signer, referenceId, paymentAmount, gasOpts = {}) {
74
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
75
+ const signerAddress = await signer.getAddress();
76
+ if (!chainId) {
77
+ throw new Error('No Chain Id found');
78
+ }
79
+ // Get ARWeave Id
80
+ const dataId = await ARWeaveService_1.ARWeaveService.queryForMetadata(chainId, signerAddress, referenceId);
81
+ // Fetch receivables with the same ARWeave Id
82
+ const tokenId = await getTokenIdByURI(signer, dataId);
83
+ if (tokenId == null) {
84
+ throw new Error('Could not find tokenId for this ARWeave Id. Please check your logs for more details.');
85
+ }
86
+ const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
87
+ if (!contract) {
88
+ throw new Error('Could not find RealWorldReceivable contract');
89
+ }
90
+ gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
91
+ return contract.declarePayment(tokenId, paymentAmount, gasOpts);
92
+ }
93
+ /**
94
+ * Declares a payment on a RealWorldReceivable given a tokenId of the receivable.
95
+ *
96
+ * @async
97
+ * @function
98
+ * @memberof ReceivableService
99
+ * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
100
+ * @param {BigNumberish} receivableTokenId - The Id of the receivable token to pay.
101
+ * @param {number} paymentAmount - The amount to pay the receivable.
102
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
103
+ * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
104
+ * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network.
105
+ */
106
+ async function declareReceivablePaymentByTokenId(signer, receivableTokenId, paymentAmount, gasOpts = {}) {
107
+ var _a;
108
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
109
+ if (!chainId) {
110
+ throw new Error('No Chain Id found');
111
+ }
112
+ const realWorldReceivable = (_a = shared_1.SupplementaryContractsMap[chainId]) === null || _a === void 0 ? void 0 : _a[shared_1.SupplementaryContracts.RealWorldReceivable];
113
+ if (!realWorldReceivable) {
114
+ throw new Error('RealWorldReceivable is not available on this network');
115
+ }
116
+ const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
117
+ if (!contract) {
118
+ throw new Error('Could not find RealWorldReceivable contract');
119
+ }
120
+ gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
121
+ return contract.declarePayment(receivableTokenId, paymentAmount, gasOpts);
122
+ }
123
+ /**
124
+ * Creates a new RealWorldReceivable token on the given chain of the signer
125
+ *
126
+ * @async
127
+ * @function
128
+ * @memberof ReceivableService
129
+ * @param {ethers.Signer} signer - The signer used to send the transaction.
130
+ * @param {POOL_NAME} poolName - The name of the credit pool to mint the receivable token from. Used to lookup the pool address.
131
+ * @param {POOL_TYPE} poolType - The type of the credit pool to mint the receivable token from. Used to lookup the pool address.
132
+ * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
133
+ * @param {number} receivableAmount - The amount of the receivable token to mint.
134
+ * @param {number} maturityDate - The maturity date of the receivable token, in UNIX timestamp format.
135
+ * @param {string} uri - The URI of the receivable token metadata.
136
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
137
+ * @returns {Promise<TransactionResponse | null>} - A Promise of the transaction response.
138
+ * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network, or if a token already exists with the same metadata URI.
139
+ */
140
+ async function createReceivable(signer, poolName, poolType, currencyCode, receivableAmount, maturityDate, uri, gasOpts = {}) {
141
+ var _a, _b;
142
+ const tokenId = await getTokenIdByURI(signer, uri);
143
+ if (tokenId != null) {
144
+ throw new Error('A token already exists with this metadata, canceling mint');
145
+ }
146
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
147
+ if (!chainId) {
148
+ throw new Error('No Chain Id found');
149
+ }
150
+ const poolInfo = chainId
151
+ ? (_b = (_a = shared_1.PoolContractMap[chainId]) === null || _a === void 0 ? void 0 : _a[poolType]) === null || _b === void 0 ? void 0 : _b[poolName]
152
+ : undefined;
153
+ if (!poolInfo) {
154
+ throw new Error('RealWorldReceivable is not available on this network');
155
+ }
156
+ const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
157
+ if (!contract) {
158
+ throw new Error('Could not find RealWorldReceivable contract');
159
+ }
160
+ gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
161
+ return contract.createRealWorldReceivable(poolInfo.pool, currencyCode, receivableAmount, maturityDate, uri, gasOpts);
162
+ }
163
+ /**
164
+ * Uploads metadata onto ARWeave (or fetches the existing metadata with the same reference Id) and returns the ARWeave URL
165
+ *
166
+ * @async
167
+ * @function
168
+ * @memberof ReceivableService
169
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
170
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
171
+ * from server calls.
172
+ * @param {string | null} privateKey - Private key of the wallet used to upload metadata to ARWeave. Only required if calling this function from a server.
173
+ * @param {number} chainId - The chain ID to mint the receivable token on and pay ARWeave funds from.
174
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
175
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
176
+ * @param {Record<string, any>} metadata - The metadata in JSON format. This will be uploaded onto ARWeave
177
+ * @param {string} referenceId - An internal identifier value added as a tag on ARWeave, for easily querying the metadata later.
178
+ * @param {Array<{ name: string, value: string }>} extraTags - Any extraTags you'd like to tag your metadata with. Note that metadata on
179
+ * ARWeave is indexed by these tags, so make sure to include any tags that you'd like to be able to query by.
180
+ * @param {boolean} [lazyFund=true] - Whether to lazy fund the ARWeave uploads. If true, the ARWeave uploads will be paid for by the
181
+ * metadata uploader immediately before uploading. If false, the ARWeave node must be pre-funded before calling this function.
182
+ * @returns {Promise<string>} - The ARWeave metadata URI.
183
+ */
184
+ async function uploadOrFetchMetadataURI(signerOrProvider, privateKey, chainId, poolName, poolType, metadata, referenceId, extraTags, lazyFund = true) {
185
+ if (typeof metadata !== 'object' || Array.isArray(metadata)) {
186
+ throw new Error('Input must be a JSON object.');
187
+ }
188
+ // Check to see if metadata with referenceId has already been minted
189
+ const signer = signerOrProvider instanceof providers_1.Web3Provider
190
+ ? signerOrProvider.getSigner()
191
+ : signerOrProvider;
192
+ const signerAddress = await signer.getAddress();
193
+ const dataId = await ARWeaveService_1.ARWeaveService.queryForMetadata(chainId, signerAddress, referenceId);
194
+ const config = ARWeaveService_1.ARWeaveService.getBundlrNetworkConfig(chainId);
195
+ let arweaveId;
196
+ if (dataId != null) {
197
+ console.log(`Metadata already exists with this reference Id, returning existing data ==> ${ARWeaveService_1.ARWeaveService.getURIFromARWeaveId(dataId)}`);
198
+ arweaveId = dataId;
199
+ }
200
+ else {
201
+ const tags = [
202
+ { name: 'Content-Type', value: 'application/json' },
203
+ { name: 'appName', value: 'HumaFinance' },
204
+ { name: 'poolName', value: poolName },
205
+ { name: 'poolType', value: poolType },
206
+ { name: 'referenceId', value: referenceId },
207
+ ...extraTags,
208
+ ];
209
+ // Append referenceId to metadata (if it's not already there)
210
+ if (!Object.prototype.hasOwnProperty.call(metadata, 'referenceId')) {
211
+ metadata.referenceId = referenceId;
212
+ }
213
+ const response = await ARWeaveService_1.ARWeaveService.storeData(config, signerOrProvider instanceof providers_1.Web3Provider ? signerOrProvider : privateKey, metadata, tags, lazyFund);
214
+ arweaveId = response.id;
215
+ console.log(`Data uploaded ==> ${ARWeaveService_1.ARWeaveService.getURIFromARWeaveId(arweaveId)}`);
216
+ }
217
+ return ARWeaveService_1.ARWeaveService.getURIFromARWeaveId(arweaveId);
218
+ }
219
+ /**
220
+ * Creates a RealWorldReceivable token with metadata uploaded onto ARWeave
221
+ *
222
+ * @async
223
+ * @function
224
+ * @memberof ReceivableService
225
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
226
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
227
+ * from server calls.
228
+ * @param {string | null} privateKey - Private key of the wallet used to upload metadata to ARWeave. Only required if calling this function from a server.
229
+ * @param {number} chainId - The chain ID to mint the receivable token on and pay ARWeave funds from.
230
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
231
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
232
+ * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
233
+ * @param {number} receivableAmount - The receivable amount.
234
+ * @param {number} maturityDate - The maturity date of the receivable, in UNIX timestamp format.
235
+ * @param {Record<string, any>} metadata - The metadata in JSON format. This will be uploaded onto ARWeave
236
+ * @param {string} referenceId - An internal identifier value added as a tag on ARWeave, for easily querying the metadata later.
237
+ * @param {Array<{ name: string, value: string }>} extraTags - Any extraTags you'd like to tag your metadata with. Note that metadata on
238
+ * ARWeave is indexed by these tags, so make sure to include any tags that you'd like to be able to query by.
239
+ * @param {boolean} [lazyFund=true] - Whether to lazy fund the ARWeave uploads. If true, the ARWeave uploads will be paid for by the
240
+ * metadata uploader immediately before uploading. If false, the ARWeave node must be pre-funded before calling this function.
241
+ * @param {Overrides} [gasOpts] - Optional gas overrides for the transaction.
242
+ * @returns {Promise<TransactionResponse>} - The transaction receipt.
243
+ */
244
+ async function createReceivableWithMetadata(signerOrProvider, privateKey, chainId, poolName, poolType, currencyCode, receivableAmount, maturityDate, metadata, referenceId, extraTags, lazyFund = true, gasOpts) {
245
+ if (typeof metadata !== 'object' || Array.isArray(metadata)) {
246
+ throw new Error('Input must be a JSON object.');
247
+ }
248
+ // Check to see if metadata with referenceId has already been minted
249
+ const signer = signerOrProvider instanceof providers_1.Web3Provider
250
+ ? signerOrProvider.getSigner()
251
+ : signerOrProvider;
252
+ const metadataURI = await uploadOrFetchMetadataURI(signerOrProvider, privateKey, chainId, poolName, poolType, metadata, referenceId, extraTags, lazyFund);
253
+ return createReceivable(signer, poolName, poolType, currencyCode, receivableAmount, maturityDate, metadataURI, gasOpts);
254
+ }
255
+ /**
256
+ * Loads all RWRs belonging to the specified owner, including the RWR metadata
257
+ *
258
+ * @async
259
+ * @function
260
+ * @memberof ReceivableService
261
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
262
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
263
+ * from server calls.
264
+ * @param {string} owner - The receivable token owner to query from.
265
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
266
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
267
+ * @returns {Promise<RealWorldReceivableInfo[]>} - An array of receivables owned by the owner for the pool.
268
+ */
269
+ async function loadReceivablesOfOwnerWithMetadata(signerOrProvider, owner, poolName, poolType) {
270
+ var _a, _b;
271
+ if (!ethers_1.ethers.utils.isAddress(owner)) {
272
+ throw new Error('Invalid owner address');
273
+ }
274
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signerOrProvider);
275
+ if (!chainId) {
276
+ throw new Error('No Chain Id found');
277
+ }
278
+ const poolInfo = chainId
279
+ ? (_b = (_a = shared_1.PoolContractMap[chainId]) === null || _a === void 0 ? void 0 : _a[poolType]) === null || _b === void 0 ? void 0 : _b[poolName]
280
+ : undefined;
281
+ if (!poolInfo) {
282
+ throw new Error('RealWorldReceivable is not available on this network');
283
+ }
284
+ const rwrContract = (0, helpers_1.getRealWorldReceivableContract)(signerOrProvider, chainId);
285
+ if (!rwrContract) {
286
+ throw new Error('Could not find RealWorldReceivable contract');
287
+ }
288
+ // Load all receivables of owner
289
+ const balance = await rwrContract.balanceOf(owner);
290
+ // Create empty array with length of balance
291
+ const tokens = Array.from(Array(balance.toNumber()));
292
+ const fetchPromises = tokens.map(async (_, tokenIndex) => {
293
+ const tokenId = await rwrContract.tokenOfOwnerByIndex(owner, tokenIndex);
294
+ const rwrInfo = await rwrContract.rwrInfoMapping(tokenId);
295
+ // If a RWR uploaded by an owner is not for this specific pool, skip it
296
+ if (rwrInfo.poolAddress.toLowerCase() !== poolInfo.pool.toLowerCase()) {
297
+ return undefined;
298
+ }
299
+ const tokenURI = await rwrContract.tokenURI(tokenId);
300
+ const metadata = await ARWeaveService_1.ARWeaveService.fetchMetadataFromUrl(tokenURI);
301
+ return {
302
+ tokenId,
303
+ poolAddress: rwrInfo.poolAddress,
304
+ receivableAmount: rwrInfo.receivableAmount,
305
+ paidAmount: rwrInfo.paidAmount,
306
+ creationDate: rwrInfo.creationDate,
307
+ maturityDate: rwrInfo.maturityDate,
308
+ currencyCode: rwrInfo.currencyCode,
309
+ tokenURI,
310
+ metadata,
311
+ };
312
+ });
313
+ const tokenData = await Promise.all(fetchPromises);
314
+ // Filter undefined
315
+ return tokenData.filter((token) => token !== undefined);
316
+ }
317
+ /**
318
+ * An object that contains functions to interact with Huma's receivables.
319
+ * @namespace ReceivableService
320
+ */
321
+ exports.ReceivableService = {
322
+ createReceivableWithMetadata,
323
+ createReceivable,
324
+ declareReceivablePaymentByTokenId,
325
+ declareReceivablePaymentByReferenceId,
326
+ loadReceivablesOfOwnerWithMetadata,
327
+ uploadOrFetchMetadataURI,
328
+ getTokenIdByURI,
329
+ };
330
+ //# sourceMappingURL=ReceivableService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReceivableService.js","sourceRoot":"","sources":["../../../src/services/ReceivableService.ts"],"names":[],"mappings":";;;AAAA,wDAA4E;AAC5E,mCAAwD;AACxD,iDAQ6B;AAC7B,qDAA8C;AAE9C,qDAAiD;AACjD,wCAA2D;AAC3D,oCAA+E;AAG/E;;;;;;;;;GASG;AACH,KAAK,UAAU,eAAe,CAC5B,MAAqB,EACrB,GAAkB;;IAElB,IAAI,GAAG,KAAK,IAAI,EAAE;QAChB,OAAO,IAAI,CAAA;KACZ;IAED,MAAM,OAAO,GAAG,MAAM,IAAA,sCAA8B,EAAC,MAAM,CAAC,CAAA;IAC5D,MAAM,aAAa,GAAG,MAAM,MAAM,CAAC,UAAU,EAAE,CAAA;IAE/C,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAA;KACrC;IAED,6CAA6C;IAC7C,MAAM,gBAAgB,GAAG,IAAA,qBAAG,EAAA;;;;;;;;;;GAU3B,CAAA;IAED,MAAM,kBAAkB,GAAG,MAAA,wBAAe,CAAC,OAAO,CAAC,0CAAE,mBAAmB,CAAA;IACxE,IAAI,CAAC,kBAAkB,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAA;KAChE;IAED,MAAM,eAAe,GAAkC,MAAM,IAAA,yBAAO,EAClE,kBAAkB,EAClB,gBAAgB,EAChB;QACE,KAAK,EAAE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AAQ,CAAC,OAAO,CAAC,CAAA;QACpD,MAAM,QAAQ,GAAG,MAAM,+BAAc,CAAC,oBAAoB,CAAC,QAAQ,CAAC,CAAA;QAEpE,OAAO;YACL,OAAO;YACP,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,gBAAgB,EAAE,OAAO,CAAC,gBAAgB;YAC1C,UAAU,EAAE,OAAO,CAAC,UAAU;YAC9B,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,QAAQ;YACR,QAAQ;SACT,CAAA;IACH,CAAC,CAAC,CAAA;IAEF,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAA;IAElD,mBAAmB;IACnB,OAAO,SAAS,CAAC,MAAM,CACrB,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CACC,CAAA;AACnC,CAAC;AAED;;;GAGG;AACU,QAAA,iBAAiB,GAAG;IAC/B,4BAA4B;IAC5B,gBAAgB;IAChB,iCAAiC;IACjC,qCAAqC;IACrC,kCAAkC;IAClC,wBAAwB;IACxB,eAAe;CAChB,CAAA"}
@@ -0,0 +1,53 @@
1
+ import { POOL_NAME, POOL_TYPE } from '@huma-finance/shared';
2
+ /**
3
+ * Returns the subgraph URL for a given chain ID.
4
+ *
5
+ * @memberof SubgraphService
6
+ * @param {number} chainId - The ID of the chain.
7
+ * @returns {string} The subgraph URL for the given chain ID.
8
+ */
9
+ declare function getSubgraphUrlForChainId(chainId: number): string;
10
+ /**
11
+ * Represents the payload of a credit event.
12
+ * @typedef {Object} CreditEventPayload
13
+ */
14
+ export type CreditEventPayload = {
15
+ amount?: string;
16
+ timestamp?: string;
17
+ owner?: string;
18
+ pool?: string;
19
+ event?: string;
20
+ };
21
+ /**
22
+ * Returns the credit events for a given user.
23
+ *
24
+ * @memberof SubgraphService
25
+ * @param {string} userAddress - The address of the user.
26
+ * @param {number} chainId - The ID of the chain.
27
+ * @param {POOL_NAME} poolName - The name of the pool.
28
+ * @param {POOL_TYPE} poolType - The type of the pool.
29
+ * @param {number[]} event - The event types to filter by.
30
+ * @returns {Promise<CreditEventPayload[]>} The credit events for the given user.
31
+ */
32
+ declare function getCreditEventsForUser(userAddress: string, chainId: number, poolName: POOL_NAME, poolType: POOL_TYPE, event: number[]): Promise<CreditEventPayload[]>;
33
+ /**
34
+ * Returns the last factorized amount for a given user and pool.
35
+ *
36
+ * @memberof SubgraphService
37
+ * @param {string} userAddress - The address of the user.
38
+ * @param {number} chainId - The ID of the chain.
39
+ * @param {POOL_NAME} poolName - The name of the pool.
40
+ * @param {POOL_TYPE} poolType - The type of the pool.
41
+ * @returns {Promise<number>} The last factorized amount for the given user and pool.
42
+ */
43
+ declare function getLastFactorizedAmountFromPool(userAddress: string, chainId: number, poolName: POOL_NAME, poolType: POOL_TYPE): Promise<number>;
44
+ /**
45
+ * An object that contains functions to interact with Huma's Subgraph storage.
46
+ * @namespace SubgraphService
47
+ */
48
+ export declare const SubgraphService: {
49
+ getSubgraphUrlForChainId: typeof getSubgraphUrlForChainId;
50
+ getCreditEventsForUser: typeof getCreditEventsForUser;
51
+ getLastFactorizedAmountFromPool: typeof getLastFactorizedAmountFromPool;
52
+ };
53
+ export {};
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SubgraphService = void 0;
4
+ const shared_1 = require("@huma-finance/shared");
5
+ /**
6
+ * Returns the subgraph URL for a given chain ID.
7
+ *
8
+ * @memberof SubgraphService
9
+ * @param {number} chainId - The ID of the chain.
10
+ * @returns {string} The subgraph URL for the given chain ID.
11
+ */
12
+ function getSubgraphUrlForChainId(chainId) {
13
+ switch (chainId) {
14
+ case 5:
15
+ return 'https://api.thegraph.com/subgraphs/name/00labs/huma-goerli';
16
+ case 137:
17
+ return 'https://api.thegraph.com/subgraphs/name/00labs/huma-polygon';
18
+ case 80001:
19
+ return 'https://api.thegraph.com/subgraphs/name/00labs/huma-mumbai';
20
+ default:
21
+ return '';
22
+ }
23
+ }
24
+ /**
25
+ * Returns the credit events for a given user.
26
+ *
27
+ * @memberof SubgraphService
28
+ * @param {string} userAddress - The address of the user.
29
+ * @param {number} chainId - The ID of the chain.
30
+ * @param {POOL_NAME} poolName - The name of the pool.
31
+ * @param {POOL_TYPE} poolType - The type of the pool.
32
+ * @param {number[]} event - The event types to filter by.
33
+ * @returns {Promise<CreditEventPayload[]>} The credit events for the given user.
34
+ */
35
+ function getCreditEventsForUser(userAddress, chainId, poolName, poolType, event) {
36
+ var _a, _b, _c;
37
+ const url = getSubgraphUrlForChainId(chainId);
38
+ if (!url) {
39
+ return Promise.resolve([]);
40
+ }
41
+ const poolAddress = (_c = (_b = (_a = shared_1.PoolContractMap[chainId]) === null || _a === void 0 ? void 0 : _a[poolType]) === null || _b === void 0 ? void 0 : _b[poolName]) === null || _c === void 0 ? void 0 : _c.pool;
42
+ const query = `
43
+ query {
44
+ creditEvents(
45
+ where: {
46
+ owner: "${userAddress}",
47
+ pool: "${poolAddress}",
48
+ event_in: [${event.join(',')}]
49
+ }
50
+ orderBy: timestamp
51
+ orderDirection: desc
52
+ ) {
53
+ amount
54
+ timestamp
55
+ owner
56
+ pool
57
+ event
58
+ }
59
+ }
60
+ `;
61
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
+ return (0, shared_1.requestPost)(url, JSON.stringify({ query })).then((res) => {
63
+ if (res.errors) {
64
+ console.error(res.errors);
65
+ return [];
66
+ }
67
+ return res.data.creditEvents;
68
+ });
69
+ }
70
+ /**
71
+ * Returns the last factorized amount for a given user and pool.
72
+ *
73
+ * @memberof SubgraphService
74
+ * @param {string} userAddress - The address of the user.
75
+ * @param {number} chainId - The ID of the chain.
76
+ * @param {POOL_NAME} poolName - The name of the pool.
77
+ * @param {POOL_TYPE} poolType - The type of the pool.
78
+ * @returns {Promise<number>} The last factorized amount for the given user and pool.
79
+ */
80
+ function getLastFactorizedAmountFromPool(userAddress, chainId, poolName, poolType) {
81
+ return getCreditEventsForUser(userAddress, chainId, poolName, poolType, [
82
+ shared_1.CreditEvent.DrawdownMadeWithReceivable,
83
+ ]).then((events) => Number(events[0].amount));
84
+ }
85
+ /**
86
+ * An object that contains functions to interact with Huma's Subgraph storage.
87
+ * @namespace SubgraphService
88
+ */
89
+ exports.SubgraphService = {
90
+ getSubgraphUrlForChainId,
91
+ getCreditEventsForUser,
92
+ getLastFactorizedAmountFromPool,
93
+ };
94
+ //# sourceMappingURL=SubgraphService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubgraphService.js","sourceRoot":"","sources":["../../../src/services/SubgraphService.ts"],"names":[],"mappings":";;;AAAA,iDAM6B;AAE7B;;;;;;GAMG;AACH,SAAS,wBAAwB,CAAC,OAAe;IAC/C,QAAQ,OAAO,EAAE;QACf,KAAK,CAAC;YACJ,OAAO,4DAA4D,CAAA;QACrE,KAAK,GAAG;YACN,OAAO,6DAA6D,CAAA;QACtE,KAAK,KAAK;YACR,OAAO,4DAA4D,CAAA;QACrE;YACE,OAAO,EAAE,CAAA;KACZ;AACH,CAAC;AAcD;;;;;;;;;;GAUG;AACH,SAAS,sBAAsB,CAC7B,WAAmB,EACnB,OAAe,EACf,QAAmB,EACnB,QAAmB,EACnB,KAAe;;IAEf,MAAM,GAAG,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAA;IAC7C,IAAI,CAAC,GAAG,EAAE;QACR,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;KAC3B;IAED,MAAM,WAAW,GAAG,MAAA,MAAA,MAAA,wBAAe,CAAC,OAAO,CAAC,0CAAG,QAAQ,CAAC,0CAAG,QAAQ,CAAC,0CAAE,IAAI,CAAA;IAE1E,MAAM,KAAK,GAAG;;;;oBAII,WAAW;mBACZ,WAAW;uBACP,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC;;;;;;;;;;;;GAYnC,CAAA;IAED,8DAA8D;IAC9D,OAAO,IAAA,oBAAW,EAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAQ,EAAE,EAAE;QACnE,IAAI,GAAG,CAAC,MAAM,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;YACzB,OAAO,EAAE,CAAA;SACV;QACD,OAAO,GAAG,CAAC,IAAI,CAAC,YAAY,CAAA;IAC9B,CAAC,CAAC,CAAA;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,+BAA+B,CACtC,WAAmB,EACnB,OAAe,EACf,QAAmB,EACnB,QAAmB;IAEnB,OAAO,sBAAsB,CAAC,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE;QACtE,oBAAW,CAAC,0BAA0B;KACvC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;AAC/C,CAAC;AAED;;;GAGG;AACU,QAAA,eAAe,GAAG;IAC7B,wBAAwB;IACxB,sBAAsB;IACtB,+BAA+B;CAChC,CAAA"}
@@ -0,0 +1,4 @@
1
+ export * from './ARWeaveService';
2
+ export * from './EAService';
3
+ export * from './SubgraphService';
4
+ export * from './ReceivableService';
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./ARWeaveService"), exports);
5
+ tslib_1.__exportStar(require("./EAService"), exports);
6
+ tslib_1.__exportStar(require("./SubgraphService"), exports);
7
+ tslib_1.__exportStar(require("./ReceivableService"), exports);
8
+ //# sourceMappingURL=index.js.map