@huma-finance/sdk 0.0.35 → 0.0.36

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 (115) hide show
  1. package/API.md +822 -822
  2. package/LICENSE +660 -660
  3. package/README.md +37 -37
  4. package/dist/cjs/graphql/generatedTypes.d.ts +40 -40
  5. package/dist/cjs/graphql/generatedTypes.js +8 -8
  6. package/dist/cjs/graphql/index.d.ts +1 -1
  7. package/dist/cjs/graphql/index.js +4 -4
  8. package/dist/cjs/helpers/ERC20TransferableReceivableContractHelper.d.ts +10 -10
  9. package/dist/cjs/helpers/ERC20TransferableReceivableContractHelper.js +21 -21
  10. package/dist/cjs/helpers/PoolContractHelper.d.ts +119 -119
  11. package/dist/cjs/helpers/PoolContractHelper.js +143 -143
  12. package/dist/cjs/helpers/RealWorldReceivableContractHelper.d.ts +10 -10
  13. package/dist/cjs/helpers/RealWorldReceivableContractHelper.js +21 -21
  14. package/dist/cjs/helpers/index.d.ts +3 -3
  15. package/dist/cjs/helpers/index.js +6 -6
  16. package/dist/cjs/hooks/index.d.ts +4 -4
  17. package/dist/cjs/hooks/index.js +7 -7
  18. package/dist/cjs/hooks/useContract.d.ts +13 -13
  19. package/dist/cjs/hooks/useContract.js +30 -30
  20. package/dist/cjs/hooks/useERC20TransferableReceivableContract.d.ts +12 -12
  21. package/dist/cjs/hooks/useERC20TransferableReceivableContract.js +20 -20
  22. package/dist/cjs/hooks/usePoolContract.d.ts +60 -60
  23. package/dist/cjs/hooks/usePoolContract.js +53 -53
  24. package/dist/cjs/hooks/useRealWorldReceivableContract.d.ts +10 -10
  25. package/dist/cjs/hooks/useRealWorldReceivableContract.js +19 -19
  26. package/dist/cjs/index.d.ts +4 -4
  27. package/dist/cjs/index.js +7 -7
  28. package/dist/cjs/services/ARWeaveService.d.ts +106 -106
  29. package/dist/cjs/services/ARWeaveService.js +190 -190
  30. package/dist/cjs/services/EAService.d.ts +20 -20
  31. package/dist/cjs/services/EAService.js +33 -33
  32. package/dist/cjs/services/ReceivableService.d.ts +104 -104
  33. package/dist/cjs/services/ReceivableService.js +308 -308
  34. package/dist/cjs/services/SubgraphService.d.ts +53 -53
  35. package/dist/cjs/services/SubgraphService.js +93 -93
  36. package/dist/cjs/services/index.d.ts +4 -4
  37. package/dist/cjs/services/index.js +7 -7
  38. package/dist/cjs/utils/chain.d.ts +15 -15
  39. package/dist/cjs/utils/chain.js +37 -37
  40. package/dist/cjs/utils/index.d.ts +4 -4
  41. package/dist/cjs/utils/index.js +7 -7
  42. package/dist/cjs/utils/maticGasStation.d.ts +3 -3
  43. package/dist/cjs/utils/maticGasStation.js +38 -38
  44. package/dist/cjs/utils/poolInfo.d.ts +8 -8
  45. package/dist/cjs/utils/poolInfo.js +12 -12
  46. package/dist/cjs/utils/web3.d.ts +5 -5
  47. package/dist/cjs/utils/web3.js +33 -33
  48. package/dist/graphql/generatedTypes.d.ts +40 -40
  49. package/dist/graphql/generatedTypes.js +4 -4
  50. package/dist/graphql/index.d.ts +1 -1
  51. package/dist/graphql/index.js +1 -1
  52. package/dist/helpers/ERC20TransferableReceivableContractHelper.d.ts +10 -10
  53. package/dist/helpers/ERC20TransferableReceivableContractHelper.js +17 -17
  54. package/dist/helpers/PoolContractHelper.d.ts +119 -119
  55. package/dist/helpers/PoolContractHelper.js +134 -134
  56. package/dist/helpers/RealWorldReceivableContractHelper.d.ts +10 -10
  57. package/dist/helpers/RealWorldReceivableContractHelper.js +17 -17
  58. package/dist/helpers/index.d.ts +3 -3
  59. package/dist/helpers/index.js +3 -3
  60. package/dist/hooks/index.d.ts +4 -4
  61. package/dist/hooks/index.js +4 -4
  62. package/dist/hooks/useContract.d.ts +13 -13
  63. package/dist/hooks/useContract.js +26 -26
  64. package/dist/hooks/useERC20TransferableReceivableContract.d.ts +12 -12
  65. package/dist/hooks/useERC20TransferableReceivableContract.js +16 -16
  66. package/dist/hooks/usePoolContract.d.ts +60 -60
  67. package/dist/hooks/usePoolContract.js +48 -48
  68. package/dist/hooks/useRealWorldReceivableContract.d.ts +10 -10
  69. package/dist/hooks/useRealWorldReceivableContract.js +15 -15
  70. package/dist/index.d.ts +4 -4
  71. package/dist/index.js +4 -4
  72. package/dist/services/ARWeaveService.d.ts +106 -106
  73. package/dist/services/ARWeaveService.js +185 -185
  74. package/dist/services/EAService.d.ts +20 -20
  75. package/dist/services/EAService.js +30 -30
  76. package/dist/services/ReceivableService.d.ts +104 -104
  77. package/dist/services/ReceivableService.js +305 -305
  78. package/dist/services/SubgraphService.d.ts +53 -53
  79. package/dist/services/SubgraphService.js +90 -90
  80. package/dist/services/index.d.ts +4 -4
  81. package/dist/services/index.js +4 -4
  82. package/dist/tsconfig.cjs.tsbuildinfo +1 -1
  83. package/dist/utils/chain.d.ts +15 -15
  84. package/dist/utils/chain.js +31 -31
  85. package/dist/utils/index.d.ts +4 -4
  86. package/dist/utils/index.js +4 -4
  87. package/dist/utils/maticGasStation.d.ts +3 -3
  88. package/dist/utils/maticGasStation.js +33 -33
  89. package/dist/utils/poolInfo.d.ts +8 -8
  90. package/dist/utils/poolInfo.js +8 -8
  91. package/dist/utils/web3.d.ts +5 -5
  92. package/dist/utils/web3.js +27 -27
  93. package/getting-started.md +190 -190
  94. package/package.json +4 -3
  95. package/dist/cjs/helpers/BaseCreditPoolReceivableContractHelper.d.ts +0 -10
  96. package/dist/cjs/helpers/BaseCreditPoolReceivableContractHelper.js +0 -22
  97. package/dist/cjs/helpers/BaseCreditPoolReceivableContractHelper.js.map +0 -1
  98. package/dist/cjs/hooks/useBaseCreditPoolReceivableContract.d.ts +0 -10
  99. package/dist/cjs/hooks/useBaseCreditPoolReceivableContract.js +0 -20
  100. package/dist/cjs/hooks/useBaseCreditPoolReceivableContract.js.map +0 -1
  101. package/dist/cjs/hooks/useReceivableFactoringPoolContract.d.ts +0 -10
  102. package/dist/cjs/hooks/useReceivableFactoringPoolContract.js +0 -17
  103. package/dist/cjs/hooks/useReceivableFactoringPoolContract.js.map +0 -1
  104. package/dist/helpers/BaseCreditPoolReceivableContractHelper.d.ts +0 -10
  105. package/dist/helpers/BaseCreditPoolReceivableContractHelper.js +0 -18
  106. package/dist/helpers/BaseCreditPoolReceivableContractHelper.js.map +0 -1
  107. package/dist/hooks/useBaseCreditPoolReceivableContract.d.ts +0 -10
  108. package/dist/hooks/useBaseCreditPoolReceivableContract.js +0 -16
  109. package/dist/hooks/useBaseCreditPoolReceivableContract.js.map +0 -1
  110. package/dist/hooks/usePool.d.ts +0 -0
  111. package/dist/hooks/usePool.js +0 -2
  112. package/dist/hooks/usePool.js.map +0 -1
  113. package/dist/hooks/useReceivableFactoringPoolContract.d.ts +0 -10
  114. package/dist/hooks/useReceivableFactoringPoolContract.js +0 -13
  115. package/dist/hooks/useReceivableFactoringPoolContract.js.map +0 -1
@@ -1,309 +1,309 @@
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
- * Declares a payment on a RealWorldReceivable given a reference Id of the receivable, which was used as an index for ARWeave data.
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 getTokenIdByARWeaveId(signer, arweaveId) {
22
- var _a, _b, _c, _d;
23
- if (arweaveId === 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: `https://arweave.net/${arweaveId}`,
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 ARWeave Id.');
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
- console.log(`This owner has multiple receivables with the same ARWeave URI, so we don't know which to use. Please burn
57
- unnecessary receivables or pay the correct token manually using declareReceivablePaymentByTokenId`);
58
- return null;
59
- }
60
- return (_d = receivablesData === null || receivablesData === void 0 ? void 0 : receivablesData.receivables[0]) === null || _d === void 0 ? void 0 : _d.tokenId;
61
- }
62
- /**
63
- * Declares a payment on a RealWorldReceivable given a reference Id of the receivable, which was used as an index for ARWeave data.
64
- *
65
- * @async
66
- * @function
67
- * @memberof ReceivableService
68
- * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
69
- * @param {string} referenceId - An internal identifier value added as a tag on ARWeave
70
- * @param {number} paymentAmount - The amount to declare paid to the receivable.
71
- * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
72
- * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
73
- */
74
- async function declareReceivablePaymentByReferenceId(signer, referenceId, paymentAmount, gasOpts = {}) {
75
- const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
76
- const signerAddress = await signer.getAddress();
77
- if (!chainId) {
78
- throw new Error('No Chain Id found');
79
- }
80
- // Get ARWeave Id
81
- const dataId = await ARWeaveService_1.ARWeaveService.queryForMetadata(chainId, signerAddress, referenceId);
82
- // Fetch receivables with the same ARWeave Id
83
- const tokenId = await getTokenIdByARWeaveId(signer, dataId);
84
- if (tokenId == null) {
85
- throw new Error('Could not find tokenId for this ARWeave Id. Please check your logs for more details.');
86
- }
87
- const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
88
- if (!contract) {
89
- throw new Error('Could not find RealWorldReceivable contract');
90
- }
91
- gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
92
- return contract.declarePayment(tokenId, paymentAmount, gasOpts);
93
- }
94
- /**
95
- * Declares a payment on a RealWorldReceivable given a tokenId of the receivable.
96
- *
97
- * @async
98
- * @function
99
- * @memberof ReceivableService
100
- * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
101
- * @param {BigNumberish} receivableTokenId - The Id of the receivable token to pay.
102
- * @param {number} paymentAmount - The amount to pay the receivable.
103
- * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
104
- * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
105
- * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network.
106
- */
107
- async function declareReceivablePaymentByTokenId(signer, receivableTokenId, paymentAmount, gasOpts = {}) {
108
- var _a;
109
- const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
110
- if (!chainId) {
111
- throw new Error('No Chain Id found');
112
- }
113
- const realWorldReceivable = (_a = shared_1.SupplementaryContractsMap[chainId]) === null || _a === void 0 ? void 0 : _a[shared_1.SupplementaryContracts.RealWorldReceivable];
114
- if (!realWorldReceivable) {
115
- throw new Error('RealWorldReceivable is not available on this network');
116
- }
117
- const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
118
- if (!contract) {
119
- throw new Error('Could not find RealWorldReceivable contract');
120
- }
121
- gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
122
- return contract.declarePayment(receivableTokenId, paymentAmount, gasOpts);
123
- }
124
- /**
125
- * Creates a new RealWorldReceivable token on the given chain of the signer
126
- *
127
- * @async
128
- * @function
129
- * @memberof ReceivableService
130
- * @param {ethers.Signer} signer - The signer used to send the transaction.
131
- * @param {POOL_NAME} poolName - The name of the credit pool to mint the receivable token from. Used to lookup the pool address.
132
- * @param {POOL_TYPE} poolType - The type of the credit pool to mint the receivable token from. Used to lookup the pool address.
133
- * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
134
- * @param {number} receivableAmount - The amount of the receivable token to mint.
135
- * @param {number} maturityDate - The maturity date of the receivable token, in UNIX timestamp format.
136
- * @param {string} uri - The URI of the receivable token metadata.
137
- * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
138
- * @returns {Promise<TransactionResponse>} - A Promise of the transaction response.
139
- * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network.
140
- */
141
- async function createReceivable(signer, poolName, poolType, currencyCode, receivableAmount, maturityDate, uri, gasOpts = {}) {
142
- var _a, _b;
143
- const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
144
- if (!chainId) {
145
- throw new Error('No Chain Id found');
146
- }
147
- const poolInfo = chainId
148
- ? (_b = (_a = shared_1.PoolContractMap[chainId]) === null || _a === void 0 ? void 0 : _a[poolType]) === null || _b === void 0 ? void 0 : _b[poolName]
149
- : undefined;
150
- if (!poolInfo) {
151
- throw new Error('RealWorldReceivable is not available on this network');
152
- }
153
- const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
154
- if (!contract) {
155
- throw new Error('Could not find RealWorldReceivable contract');
156
- }
157
- gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
158
- return contract.createRealWorldReceivable(poolInfo.pool, currencyCode, receivableAmount, maturityDate, uri, gasOpts);
159
- }
160
- /**
161
- * Creates a RealWorldReceivable token with metadata uploaded onto ARWeave
162
- *
163
- * @async
164
- * @function
165
- * @memberof ReceivableService
166
- * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
167
- * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
168
- * from server calls.
169
- * @param {string | null} privateKey - Private key of the wallet used to upload metadata to ARWeave. Only required if calling this function from a server.
170
- * @param {number} chainId - The chain ID to mint the receivable token on and pay ARWeave funds from.
171
- * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
172
- * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
173
- * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
174
- * @param {number} receivableAmount - The receivable amount.
175
- * @param {number} maturityDate - The maturity date of the receivable, in UNIX timestamp format.
176
- * @param {Record<string, any>} metadata - The metadata in JSON format. This will be uploaded onto ARWeave
177
- * @param {number} 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
- * @param {Overrides} [gasOpts] - Optional gas overrides for the transaction.
183
- * @returns {Promise<TransactionResponse>} - The transaction receipt.
184
- */
185
- async function createReceivableWithMetadata(signerOrProvider, privateKey, chainId, poolName, poolType, currencyCode, receivableAmount, maturityDate, metadata, referenceId, extraTags, lazyFund = true, gasOpts) {
186
- if (typeof metadata !== 'object' || Array.isArray(metadata)) {
187
- throw new Error('Input must be a JSON object.');
188
- }
189
- const config = ARWeaveService_1.ARWeaveService.getBundlrNetworkConfig(chainId);
190
- try {
191
- // Check to see if metadata with referenceId has already been minted
192
- const signer = signerOrProvider instanceof providers_1.Web3Provider
193
- ? signerOrProvider.getSigner()
194
- : signerOrProvider;
195
- const signerAddress = await signer.getAddress();
196
- const dataId = await ARWeaveService_1.ARWeaveService.queryForMetadata(chainId, signerAddress, referenceId);
197
- let arweaveId;
198
- if (dataId != null) {
199
- // If there already exists metadata with this reference Id, check if there exists
200
- // a token with that ARWeave Id as metadata.
201
- const tokenId = await getTokenIdByARWeaveId(signer, dataId);
202
- if (tokenId == null) {
203
- console.log(`Reusing existing metadata ${dataId} to mint new receivable`);
204
- arweaveId = dataId;
205
- }
206
- else {
207
- throw new Error('A token already exists with this reference Id, canceling mint');
208
- }
209
- }
210
- else {
211
- const tags = [
212
- { name: 'Content-Type', value: 'application/json' },
213
- { name: 'appName', value: 'HumaFinance' },
214
- { name: 'poolName', value: poolName },
215
- { name: 'poolType', value: poolType },
216
- { name: 'referenceId', value: referenceId },
217
- ...extraTags,
218
- ];
219
- // Append referenceId to metadata (if it's not already there)
220
- if (!Object.prototype.hasOwnProperty.call(metadata, 'referenceId')) {
221
- metadata.referenceId = referenceId;
222
- }
223
- const response = await ARWeaveService_1.ARWeaveService.storeData(config, signerOrProvider instanceof providers_1.Web3Provider
224
- ? signerOrProvider
225
- : privateKey, metadata, tags, lazyFund);
226
- arweaveId = response.id;
227
- console.log(`Data uploaded ==> https://arweave.net/${arweaveId}`);
228
- }
229
- return await createReceivable(signer, poolName, poolType, currencyCode, receivableAmount, maturityDate, `https://arweave.net/${arweaveId}`, gasOpts);
230
- }
231
- catch (e) {
232
- console.error(e);
233
- throw e;
234
- }
235
- }
236
- /**
237
- * Loads all RWRs belonging to the specified owner, including the RWR metadata
238
- *
239
- * @async
240
- * @function
241
- * @memberof ReceivableService
242
- * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
243
- * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
244
- * from server calls.
245
- * @param {string} owner - The receivable token owner to query from.
246
- * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
247
- * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
248
- * @returns {Promise<RealWorldReceivableInfo[]>} - An array of receivables owned by the owner for the pool.
249
- */
250
- async function loadReceivablesOfOwnerWithMetadata(signerOrProvider, owner, poolName, poolType) {
251
- var _a, _b;
252
- if (!ethers_1.ethers.utils.isAddress(owner)) {
253
- throw new Error('Invalid owner address');
254
- }
255
- const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signerOrProvider);
256
- if (!chainId) {
257
- throw new Error('No Chain Id found');
258
- }
259
- const poolInfo = chainId
260
- ? (_b = (_a = shared_1.PoolContractMap[chainId]) === null || _a === void 0 ? void 0 : _a[poolType]) === null || _b === void 0 ? void 0 : _b[poolName]
261
- : undefined;
262
- if (!poolInfo) {
263
- throw new Error('RealWorldReceivable is not available on this network');
264
- }
265
- const rwrContract = (0, helpers_1.getRealWorldReceivableContract)(signerOrProvider, chainId);
266
- if (!rwrContract) {
267
- throw new Error('Could not find RealWorldReceivable contract');
268
- }
269
- // Load all receivables of owner
270
- const balance = await rwrContract.balanceOf(owner);
271
- // Create empty array with length of balance
272
- const tokens = Array.from(Array(balance.toNumber()));
273
- const fetchPromises = tokens.map(async (_, tokenIndex) => {
274
- const tokenId = await rwrContract.tokenOfOwnerByIndex(owner, tokenIndex);
275
- const rwrInfo = await rwrContract.rwrInfoMapping(tokenId);
276
- // If a RWR uploaded by an owner is not for this specific pool, skip it
277
- if (rwrInfo.poolAddress.toLowerCase() !== poolInfo.pool.toLowerCase()) {
278
- return undefined;
279
- }
280
- const tokenURI = await rwrContract.tokenURI(tokenId);
281
- const metadata = await ARWeaveService_1.ARWeaveService.fetchMetadataFromUrl(tokenURI);
282
- return {
283
- tokenId,
284
- poolAddress: rwrInfo.poolAddress,
285
- receivableAmount: rwrInfo.receivableAmount,
286
- paidAmount: rwrInfo.paidAmount,
287
- creationDate: rwrInfo.creationDate,
288
- maturityDate: rwrInfo.maturityDate,
289
- currencyCode: rwrInfo.currencyCode,
290
- tokenURI,
291
- metadata,
292
- };
293
- });
294
- const tokenData = await Promise.all(fetchPromises);
295
- // Filter undefined
296
- return tokenData.filter((token) => token !== undefined);
297
- }
298
- /**
299
- * An object that contains functions to interact with Huma's receivables.
300
- * @namespace ReceivableService
301
- */
302
- exports.ReceivableService = {
303
- createReceivableWithMetadata,
304
- createReceivable,
305
- declareReceivablePaymentByTokenId,
306
- declareReceivablePaymentByReferenceId,
307
- loadReceivablesOfOwnerWithMetadata,
308
- };
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
+ * Declares a payment on a RealWorldReceivable given a reference Id of the receivable, which was used as an index for ARWeave data.
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 getTokenIdByARWeaveId(signer, arweaveId) {
22
+ var _a, _b, _c, _d;
23
+ if (arweaveId === 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: `https://arweave.net/${arweaveId}`,
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 ARWeave Id.');
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
+ console.log(`This owner has multiple receivables with the same ARWeave URI, so we don't know which to use. Please burn
57
+ unnecessary receivables or pay the correct token manually using declareReceivablePaymentByTokenId`);
58
+ return null;
59
+ }
60
+ return (_d = receivablesData === null || receivablesData === void 0 ? void 0 : receivablesData.receivables[0]) === null || _d === void 0 ? void 0 : _d.tokenId;
61
+ }
62
+ /**
63
+ * Declares a payment on a RealWorldReceivable given a reference Id of the receivable, which was used as an index for ARWeave data.
64
+ *
65
+ * @async
66
+ * @function
67
+ * @memberof ReceivableService
68
+ * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
69
+ * @param {string} referenceId - An internal identifier value added as a tag on ARWeave
70
+ * @param {number} paymentAmount - The amount to declare paid to the receivable.
71
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
72
+ * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
73
+ */
74
+ async function declareReceivablePaymentByReferenceId(signer, referenceId, paymentAmount, gasOpts = {}) {
75
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
76
+ const signerAddress = await signer.getAddress();
77
+ if (!chainId) {
78
+ throw new Error('No Chain Id found');
79
+ }
80
+ // Get ARWeave Id
81
+ const dataId = await ARWeaveService_1.ARWeaveService.queryForMetadata(chainId, signerAddress, referenceId);
82
+ // Fetch receivables with the same ARWeave Id
83
+ const tokenId = await getTokenIdByARWeaveId(signer, dataId);
84
+ if (tokenId == null) {
85
+ throw new Error('Could not find tokenId for this ARWeave Id. Please check your logs for more details.');
86
+ }
87
+ const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
88
+ if (!contract) {
89
+ throw new Error('Could not find RealWorldReceivable contract');
90
+ }
91
+ gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
92
+ return contract.declarePayment(tokenId, paymentAmount, gasOpts);
93
+ }
94
+ /**
95
+ * Declares a payment on a RealWorldReceivable given a tokenId of the receivable.
96
+ *
97
+ * @async
98
+ * @function
99
+ * @memberof ReceivableService
100
+ * @param {ethers.Signer} signer - The signer used to send the transaction. Note only the receivable owner can pay the receivable.
101
+ * @param {BigNumberish} receivableTokenId - The Id of the receivable token to pay.
102
+ * @param {number} paymentAmount - The amount to pay the receivable.
103
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
104
+ * @returns {Promise<TransactionResponse>} - A Promise of the transaction receipt.
105
+ * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network.
106
+ */
107
+ async function declareReceivablePaymentByTokenId(signer, receivableTokenId, paymentAmount, gasOpts = {}) {
108
+ var _a;
109
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
110
+ if (!chainId) {
111
+ throw new Error('No Chain Id found');
112
+ }
113
+ const realWorldReceivable = (_a = shared_1.SupplementaryContractsMap[chainId]) === null || _a === void 0 ? void 0 : _a[shared_1.SupplementaryContracts.RealWorldReceivable];
114
+ if (!realWorldReceivable) {
115
+ throw new Error('RealWorldReceivable is not available on this network');
116
+ }
117
+ const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
118
+ if (!contract) {
119
+ throw new Error('Could not find RealWorldReceivable contract');
120
+ }
121
+ gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
122
+ return contract.declarePayment(receivableTokenId, paymentAmount, gasOpts);
123
+ }
124
+ /**
125
+ * Creates a new RealWorldReceivable token on the given chain of the signer
126
+ *
127
+ * @async
128
+ * @function
129
+ * @memberof ReceivableService
130
+ * @param {ethers.Signer} signer - The signer used to send the transaction.
131
+ * @param {POOL_NAME} poolName - The name of the credit pool to mint the receivable token from. Used to lookup the pool address.
132
+ * @param {POOL_TYPE} poolType - The type of the credit pool to mint the receivable token from. Used to lookup the pool address.
133
+ * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
134
+ * @param {number} receivableAmount - The amount of the receivable token to mint.
135
+ * @param {number} maturityDate - The maturity date of the receivable token, in UNIX timestamp format.
136
+ * @param {string} uri - The URI of the receivable token metadata.
137
+ * @param {Overrides} [gasOpts] - The gas options to use for the transaction.
138
+ * @returns {Promise<TransactionResponse>} - A Promise of the transaction response.
139
+ * @throws {Error} - Throws an error if the RealWorldReceivable contract is not available on the network.
140
+ */
141
+ async function createReceivable(signer, poolName, poolType, currencyCode, receivableAmount, maturityDate, uri, gasOpts = {}) {
142
+ var _a, _b;
143
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signer);
144
+ if (!chainId) {
145
+ throw new Error('No Chain Id found');
146
+ }
147
+ const poolInfo = chainId
148
+ ? (_b = (_a = shared_1.PoolContractMap[chainId]) === null || _a === void 0 ? void 0 : _a[poolType]) === null || _b === void 0 ? void 0 : _b[poolName]
149
+ : undefined;
150
+ if (!poolInfo) {
151
+ throw new Error('RealWorldReceivable is not available on this network');
152
+ }
153
+ const contract = (0, helpers_1.getRealWorldReceivableContract)(signer, chainId);
154
+ if (!contract) {
155
+ throw new Error('Could not find RealWorldReceivable contract');
156
+ }
157
+ gasOpts = await (0, utils_1.getDefaultGasOptions)(gasOpts, chainId);
158
+ return contract.createRealWorldReceivable(poolInfo.pool, currencyCode, receivableAmount, maturityDate, uri, gasOpts);
159
+ }
160
+ /**
161
+ * Creates a RealWorldReceivable token with metadata uploaded onto ARWeave
162
+ *
163
+ * @async
164
+ * @function
165
+ * @memberof ReceivableService
166
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
167
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
168
+ * from server calls.
169
+ * @param {string | null} privateKey - Private key of the wallet used to upload metadata to ARWeave. Only required if calling this function from a server.
170
+ * @param {number} chainId - The chain ID to mint the receivable token on and pay ARWeave funds from.
171
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
172
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
173
+ * @param {number} currencyCode - The ISO 4217 currency code that the receivable is denominated in
174
+ * @param {number} receivableAmount - The receivable amount.
175
+ * @param {number} maturityDate - The maturity date of the receivable, in UNIX timestamp format.
176
+ * @param {Record<string, any>} metadata - The metadata in JSON format. This will be uploaded onto ARWeave
177
+ * @param {number} 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
+ * @param {Overrides} [gasOpts] - Optional gas overrides for the transaction.
183
+ * @returns {Promise<TransactionResponse>} - The transaction receipt.
184
+ */
185
+ async function createReceivableWithMetadata(signerOrProvider, privateKey, chainId, poolName, poolType, currencyCode, receivableAmount, maturityDate, metadata, referenceId, extraTags, lazyFund = true, gasOpts) {
186
+ if (typeof metadata !== 'object' || Array.isArray(metadata)) {
187
+ throw new Error('Input must be a JSON object.');
188
+ }
189
+ const config = ARWeaveService_1.ARWeaveService.getBundlrNetworkConfig(chainId);
190
+ try {
191
+ // Check to see if metadata with referenceId has already been minted
192
+ const signer = signerOrProvider instanceof providers_1.Web3Provider
193
+ ? signerOrProvider.getSigner()
194
+ : signerOrProvider;
195
+ const signerAddress = await signer.getAddress();
196
+ const dataId = await ARWeaveService_1.ARWeaveService.queryForMetadata(chainId, signerAddress, referenceId);
197
+ let arweaveId;
198
+ if (dataId != null) {
199
+ // If there already exists metadata with this reference Id, check if there exists
200
+ // a token with that ARWeave Id as metadata.
201
+ const tokenId = await getTokenIdByARWeaveId(signer, dataId);
202
+ if (tokenId == null) {
203
+ console.log(`Reusing existing metadata ${dataId} to mint new receivable`);
204
+ arweaveId = dataId;
205
+ }
206
+ else {
207
+ throw new Error('A token already exists with this reference Id, canceling mint');
208
+ }
209
+ }
210
+ else {
211
+ const tags = [
212
+ { name: 'Content-Type', value: 'application/json' },
213
+ { name: 'appName', value: 'HumaFinance' },
214
+ { name: 'poolName', value: poolName },
215
+ { name: 'poolType', value: poolType },
216
+ { name: 'referenceId', value: referenceId },
217
+ ...extraTags,
218
+ ];
219
+ // Append referenceId to metadata (if it's not already there)
220
+ if (!Object.prototype.hasOwnProperty.call(metadata, 'referenceId')) {
221
+ metadata.referenceId = referenceId;
222
+ }
223
+ const response = await ARWeaveService_1.ARWeaveService.storeData(config, signerOrProvider instanceof providers_1.Web3Provider
224
+ ? signerOrProvider
225
+ : privateKey, metadata, tags, lazyFund);
226
+ arweaveId = response.id;
227
+ console.log(`Data uploaded ==> https://arweave.net/${arweaveId}`);
228
+ }
229
+ return await createReceivable(signer, poolName, poolType, currencyCode, receivableAmount, maturityDate, `https://arweave.net/${arweaveId}`, gasOpts);
230
+ }
231
+ catch (e) {
232
+ console.error(e);
233
+ throw e;
234
+ }
235
+ }
236
+ /**
237
+ * Loads all RWRs belonging to the specified owner, including the RWR metadata
238
+ *
239
+ * @async
240
+ * @function
241
+ * @memberof ReceivableService
242
+ * @param {Web3Provider | ethers.Signer} signerOrProvider - If calling this function from a browser, this function expects a Web3Provider.
243
+ * If calling this function from a server, this function expects an ethers Signer. Note that privateKey only needs to be included
244
+ * from server calls.
245
+ * @param {string} owner - The receivable token owner to query from.
246
+ * @param {POOL_NAME} poolName - The pool name. Used to lookup the pool address to pay to.
247
+ * @param {POOL_TYPE} poolType - The pool type. Used to lookup the pool address to pay to.
248
+ * @returns {Promise<RealWorldReceivableInfo[]>} - An array of receivables owned by the owner for the pool.
249
+ */
250
+ async function loadReceivablesOfOwnerWithMetadata(signerOrProvider, owner, poolName, poolType) {
251
+ var _a, _b;
252
+ if (!ethers_1.ethers.utils.isAddress(owner)) {
253
+ throw new Error('Invalid owner address');
254
+ }
255
+ const chainId = await (0, utils_1.getChainIdFromSignerOrProvider)(signerOrProvider);
256
+ if (!chainId) {
257
+ throw new Error('No Chain Id found');
258
+ }
259
+ const poolInfo = chainId
260
+ ? (_b = (_a = shared_1.PoolContractMap[chainId]) === null || _a === void 0 ? void 0 : _a[poolType]) === null || _b === void 0 ? void 0 : _b[poolName]
261
+ : undefined;
262
+ if (!poolInfo) {
263
+ throw new Error('RealWorldReceivable is not available on this network');
264
+ }
265
+ const rwrContract = (0, helpers_1.getRealWorldReceivableContract)(signerOrProvider, chainId);
266
+ if (!rwrContract) {
267
+ throw new Error('Could not find RealWorldReceivable contract');
268
+ }
269
+ // Load all receivables of owner
270
+ const balance = await rwrContract.balanceOf(owner);
271
+ // Create empty array with length of balance
272
+ const tokens = Array.from(Array(balance.toNumber()));
273
+ const fetchPromises = tokens.map(async (_, tokenIndex) => {
274
+ const tokenId = await rwrContract.tokenOfOwnerByIndex(owner, tokenIndex);
275
+ const rwrInfo = await rwrContract.rwrInfoMapping(tokenId);
276
+ // If a RWR uploaded by an owner is not for this specific pool, skip it
277
+ if (rwrInfo.poolAddress.toLowerCase() !== poolInfo.pool.toLowerCase()) {
278
+ return undefined;
279
+ }
280
+ const tokenURI = await rwrContract.tokenURI(tokenId);
281
+ const metadata = await ARWeaveService_1.ARWeaveService.fetchMetadataFromUrl(tokenURI);
282
+ return {
283
+ tokenId,
284
+ poolAddress: rwrInfo.poolAddress,
285
+ receivableAmount: rwrInfo.receivableAmount,
286
+ paidAmount: rwrInfo.paidAmount,
287
+ creationDate: rwrInfo.creationDate,
288
+ maturityDate: rwrInfo.maturityDate,
289
+ currencyCode: rwrInfo.currencyCode,
290
+ tokenURI,
291
+ metadata,
292
+ };
293
+ });
294
+ const tokenData = await Promise.all(fetchPromises);
295
+ // Filter undefined
296
+ return tokenData.filter((token) => token !== undefined);
297
+ }
298
+ /**
299
+ * An object that contains functions to interact with Huma's receivables.
300
+ * @namespace ReceivableService
301
+ */
302
+ exports.ReceivableService = {
303
+ createReceivableWithMetadata,
304
+ createReceivable,
305
+ declareReceivablePaymentByTokenId,
306
+ declareReceivablePaymentByReferenceId,
307
+ loadReceivablesOfOwnerWithMetadata,
308
+ };
309
309
  //# sourceMappingURL=ReceivableService.js.map