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