@huma-finance/sdk 0.0.39 → 0.0.41

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