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