@mentaproject/client 0.1.24 → 0.1.28

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.
@@ -1,8 +1,26 @@
1
- import { fetchByBlockRange, getBalance, getBlockNumber, getCode, getTransaction, getTransactionCount, sendTransaction, traceFilter } from "@mentaproject/core/actions";
2
- import type { Address, Hash, onBlockRangeCallback } from "@mentaproject/core/types";
1
+ import {
2
+ fetchByBlockRange,
3
+ getBalance,
4
+ getBlockNumber,
5
+ getCode,
6
+ getTransaction,
7
+ getTransactionCount,
8
+ sendTransaction,
9
+ traceFilter,
10
+ } from "@mentaproject/core/actions";
11
+ import type {
12
+ Address,
13
+ Hash,
14
+ onBlockRangeCallback,
15
+ } from "@mentaproject/core/types";
3
16
  import { Transaction } from "./Transaction";
4
17
  import { toHex } from "@mentaproject/core/utils";
5
- import { AccountData, FetchTransactionParams, GetTransactionsParams, JSONAccount } from "../types/Account";
18
+ import {
19
+ AccountData,
20
+ FetchTransactionParams,
21
+ GetTransactionsParams,
22
+ JSONAccount,
23
+ } from "../types/Account";
6
24
  import { getContractType } from "@mentaproject/contracts";
7
25
  import { toJSON } from "../utils/toJSON";
8
26
  import { PersistenceManager } from "../managers/PersistenceManager";
@@ -13,194 +31,221 @@ import { MentaClient } from "./MentaClient";
13
31
  * This class provides methods to query account information, send transactions, and manage account-related data.
14
32
  */
15
33
  export class Account implements AccountData {
16
- /**
17
- * The blockchain address of the account.
18
- */
19
- public address: Address;
20
-
21
- private persistenceManager?: PersistenceManager;
22
-
23
- /**
24
- * Creates an instance of the Account class.
25
- * @param client.rpc The CoreClient instance used for blockchain interactions.
26
- * @param address The blockchain address of the account.
27
- * @param persistenceManager An optional PersistenceManager instance for caching and data synchronization.
28
- */
29
- constructor(public client: MentaClient, data: AccountData, persistenceManager?: PersistenceManager) {
30
- this.address = data.address;
31
- this.persistenceManager = persistenceManager;
34
+ /**
35
+ * The blockchain address of the account.
36
+ */
37
+ public address: Address;
38
+
39
+ private persistenceManager?: PersistenceManager;
40
+
41
+ /**
42
+ * Creates an instance of the Account class.
43
+ * @param client.rpc The CoreClient instance used for blockchain interactions.
44
+ * @param address The blockchain address of the account.
45
+ * @param persistenceManager An optional PersistenceManager instance for caching and data synchronization.
46
+ */
47
+ constructor(
48
+ public client: MentaClient,
49
+ data: AccountData,
50
+ persistenceManager?: PersistenceManager,
51
+ ) {
52
+ this.address = data.address;
53
+ this.persistenceManager = persistenceManager;
54
+ }
55
+
56
+ /**
57
+ * Checks if the account's address belongs to a smart contract.
58
+ * @description This method queries the blockchain for the code associated with the account's address.
59
+ * If code is found, it indicates that the account is a contract.
60
+ * @returns {Promise<boolean>} A promise that resolves to `true` if the account is a contract, `false` otherwise.
61
+ */
62
+ async isContract(): Promise<boolean> {
63
+ const code = await getCode(this.client.rpc, { address: this.address });
64
+
65
+ if (!code || code === "0x") return false;
66
+ return true;
67
+ }
68
+
69
+ /**
70
+ * Retrieves the type of the contract if the account is a smart contract.
71
+ * @description This method first checks if the account is a contract using `isContract()`.
72
+ * If it is a contract, it then attempts to determine and return its type.
73
+ * @returns {Promise<any>} A promise that resolves to the contract type (e.g., 'ERC20', 'ERC721') or `undefined` if the account is not a contract or its type cannot be determined.
74
+ */
75
+ async contractType(): Promise<any> {
76
+ const isContract = await this.isContract();
77
+ if (!isContract) return undefined;
78
+
79
+ return await getContractType(this.client.rpc, this.address);
80
+ }
81
+
82
+ /**
83
+ * Sends a specified amount of native cryptocurrency (ETH) to this account.
84
+ * @description This method constructs and sends a transaction to transfer ETH to the account's address.
85
+ * @param {bigint} amount The amount of ETH to send, specified in wei (the smallest denomination of Ether).
86
+ * @returns {Promise<Transaction>} A promise that resolves to a `Transaction` object representing the sent transaction.
87
+ */
88
+ async sendETH(amount: bigint): Promise<Transaction> {
89
+ const hash = await sendTransaction(this.client.rpc, {
90
+ calls: [
91
+ {
92
+ to: this.address,
93
+ value: amount,
94
+ },
95
+ ],
96
+ });
97
+
98
+ const data = await getTransaction(this.client.rpc, { hash });
99
+ return new Transaction(this.client, data);
100
+ }
101
+
102
+ /**
103
+ * Retrieves the current native cryptocurrency (ETH) balance of the account.
104
+ * @description This method queries the blockchain to get the balance associated with the account's address.
105
+ * @returns {Promise<bigint>} A promise that resolves to the ETH balance of the account, in wei.
106
+ */
107
+ async ETHBalance(): Promise<bigint> {
108
+ return await getBalance(this.client.rpc, {
109
+ address: this.address,
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Retrieves the transaction count (nonce) for the account.
115
+ * @description The transaction count represents the number of transactions sent from this account,
116
+ * which is also used as the nonce for new transactions to prevent replay attacks.
117
+ * @returns {Promise<number>} A promise that resolves to the transaction count of the account.
118
+ */
119
+ async transactionCount(): Promise<number> {
120
+ return await getTransactionCount(this.client.rpc, {
121
+ address: this.address,
122
+ });
123
+ }
124
+
125
+ /**
126
+ * Retrieves all transactions involving this account.
127
+ * @description If a `PersistenceManager` is configured, this method will first attempt to retrieve transactions from the local cache.
128
+ * If not found in cache or if no `PersistenceManager` is configured, it will fetch transactions directly from the remote RPC.
129
+ * @param {GetTransactionsOptions} [options] - Optional parameters for filtering, pagination, and sorting the transactions.
130
+ * @param {number} [options.startBlock] - The starting block number (inclusive) from which to retrieve transactions.
131
+ * @param {number} [options.endBlock] - The ending block number (inclusive) up to which to retrieve transactions.
132
+ * @param {number} [options.page] - The page number for paginated results.
133
+ * @param {number} [options.offset] - The number of items to skip from the beginning of the result set.
134
+ * @param {'asc' | 'desc'} [options.sort] - The sorting order for transactions based on block number ('asc' for ascending, 'desc' for descending).
135
+ * @param {boolean} [forceFetch=false] - Forces the method to fetch transactions from the remote source even if they are already cached. (mostly used internally)
136
+ * @returns {Promise<Transaction[]>} A promise that resolves to an array of transactions.
137
+ */
138
+ async transactions(
139
+ params: GetTransactionsParams,
140
+ forceFetch = false,
141
+ ): Promise<Transaction[]> {
142
+ if (!this.persistenceManager || forceFetch) {
143
+ // If persistence is not configured, fetch directly from remote
144
+ const hashes = await this._fetchTransactions(params);
145
+ const transactions = await Promise.all(
146
+ hashes.map((hash) => this.client.transactions.get({ hash })),
147
+ );
148
+
149
+ return transactions;
32
150
  }
33
151
 
34
- /**
35
- * Checks if the account's address belongs to a smart contract.
36
- * @description This method queries the blockchain for the code associated with the account's address.
37
- * If code is found, it indicates that the account is a contract.
38
- * @returns {Promise<boolean>} A promise that resolves to `true` if the account is a contract, `false` otherwise.
39
- */
40
- async isContract(): Promise<boolean> {
41
- const code = await getCode(this.client.rpc, { address: this.address });
42
-
43
- if (!code || code === "0x") return false;
44
- return true;
152
+ const jsons = await this.persistenceManager.getTransactions(
153
+ this.address,
154
+ params,
155
+ );
156
+ return jsons.map((j) => this.client.transactions.parse(j));
157
+ }
158
+
159
+ /**
160
+ * Synchronizes the account's transactions with the remote data source using the configured `PersistenceManager`.
161
+ * @description This method initiates a synchronization process to ensure that the local cache of transactions
162
+ * for this account is up-to-date with the blockchain.
163
+ * @param {number} [limit] The maximum number of transactions to synchronize.
164
+ * @returns {Promise<void>} A promise that resolves when the synchronization process is complete.
165
+ * @throws {Error} If the persistence module is not configured.
166
+ */
167
+ async syncTransactions(limit: number = 1000): Promise<void> {
168
+ if (!this.persistenceManager)
169
+ throw new Error("The persistence module is not configured.");
170
+ await this.persistenceManager.syncTransactions(this, limit);
171
+ }
172
+
173
+ /**
174
+ * Retrieves transactions involving a specific token. (not implemented yet)
175
+ * @description This method queries the persistence adapter to retrieve transactions involving a specific token.
176
+ * @param {Address} tokenAddress The address of the token.
177
+ * @returns {Promise<any>} A promise that resolves to an array of transactions involving the token.
178
+ * @throws {Error} If the persistence module is not configured.
179
+ */
180
+ async tokenTransactions(tokenAddress: Address): Promise<any> {
181
+ if (!this.persistenceManager)
182
+ throw new Error("The persistence module is not configured.");
183
+
184
+ return {};
185
+ }
186
+
187
+ /**
188
+ * Converts the Account instance into a JSON-serializable representation.
189
+ * @description This method leverages a utility function to convert the `Account` object,
190
+ * including its asynchronous properties (like `isContract`, `ETHBalance`), into a plain JSON object.
191
+ * @param {number} [depth=1] The depth to which nested objects should be converted. A depth of 1 means only direct properties are included.
192
+ * @returns {Promise<object>} A promise that resolves to the JSON representation of the account.
193
+ */
194
+ async toJSON<D extends number = 1>(depth: D): Promise<JSONAccount<D>> {
195
+ return await toJSON({
196
+ obj: {
197
+ address: this.address,
198
+ isContract: this.isContract.bind(this),
199
+ contractType: this.contractType.bind(this),
200
+ ETHBalance: this.ETHBalance.bind(this),
201
+ transactionCount: this.transactionCount.bind(this),
202
+ },
203
+ depth,
204
+ });
205
+ }
206
+
207
+ /**
208
+ * Fetches transactions from the account using a block range exploration with trace_filter calls.
209
+ *
210
+ * @param params - The parameters for the block range exploration.
211
+ * @returns A Promise that resolves to an array of transaction hashes.
212
+ */
213
+ protected async _fetchTransactions({
214
+ fromBlock,
215
+ toBlock,
216
+ limit = 50,
217
+ }: FetchTransactionParams): Promise<Hash[]> {
218
+ const lastBlock = await getBlockNumber(this.client.rpc);
219
+
220
+ const onBlockRange: onBlockRangeCallback = async (
221
+ { fromBlock, toBlock },
222
+ stop,
223
+ ) => {
224
+ const outgoing = await traceFilter(this.client.rpc, {
225
+ fromBlock: toHex(fromBlock),
226
+ toBlock: toHex(toBlock),
227
+ fromAddress: this.address,
228
+ });
229
+
230
+ const incoming = await traceFilter(this.client.rpc, {
231
+ fromBlock: toHex(fromBlock),
232
+ toBlock: toHex(toBlock),
233
+ toAddress: this.address,
234
+ });
235
+
236
+ const traces = outgoing
237
+ .concat(incoming)
238
+ .sort((a, b) => a.blockNumber - b.blockNumber);
239
+
240
+ return traces.map((t) => t.transactionHash as Hash);
45
241
  };
46
242
 
47
- /**
48
- * Retrieves the type of the contract if the account is a smart contract.
49
- * @description This method first checks if the account is a contract using `isContract()`.
50
- * If it is a contract, it then attempts to determine and return its type.
51
- * @returns {Promise<any>} A promise that resolves to the contract type (e.g., 'ERC20', 'ERC721') or `undefined` if the account is not a contract or its type cannot be determined.
52
- */
53
- async contractType(): Promise<any> {
54
- const isContract = await this.isContract();
55
- if (!isContract) return undefined;
56
-
57
- return await getContractType(this.client.rpc, this.address);
58
- };
59
-
60
- /**
61
- * Sends a specified amount of native cryptocurrency (ETH) to this account.
62
- * @description This method constructs and sends a transaction to transfer ETH to the account's address.
63
- * @param {bigint} amount The amount of ETH to send, specified in wei (the smallest denomination of Ether).
64
- * @returns {Promise<Transaction>} A promise that resolves to a `Transaction` object representing the sent transaction.
65
- */
66
- async sendETH(amount: bigint): Promise<Transaction> {
67
- const hash = await sendTransaction(this.client.rpc, {
68
- calls: [{
69
- to: this.address,
70
- value: amount,
71
- }]
72
- });
73
-
74
- const data = await getTransaction(this.client.rpc, { hash });
75
- return new Transaction(this.client, data);
76
- };
77
-
78
- /**
79
- * Retrieves the current native cryptocurrency (ETH) balance of the account.
80
- * @description This method queries the blockchain to get the balance associated with the account's address.
81
- * @returns {Promise<bigint>} A promise that resolves to the ETH balance of the account, in wei.
82
- */
83
- async ETHBalance(): Promise<bigint> {
84
- return await getBalance(this.client.rpc, {
85
- address: this.address,
86
- });
87
- };
88
-
89
- /**
90
- * Retrieves the transaction count (nonce) for the account.
91
- * @description The transaction count represents the number of transactions sent from this account,
92
- * which is also used as the nonce for new transactions to prevent replay attacks.
93
- * @returns {Promise<number>} A promise that resolves to the transaction count of the account.
94
- */
95
- async transactionCount(): Promise<number> {
96
- return await getTransactionCount(this.client.rpc, { address: this.address });
97
- }
98
-
99
- /**
100
- * Retrieves all transactions involving this account.
101
- * @description If a `PersistenceManager` is configured, this method will first attempt to retrieve transactions from the local cache.
102
- * If not found in cache or if no `PersistenceManager` is configured, it will fetch transactions directly from the remote RPC.
103
- * @param {GetTransactionsOptions} [options] - Optional parameters for filtering, pagination, and sorting the transactions.
104
- * @param {number} [options.startBlock] - The starting block number (inclusive) from which to retrieve transactions.
105
- * @param {number} [options.endBlock] - The ending block number (inclusive) up to which to retrieve transactions.
106
- * @param {number} [options.page] - The page number for paginated results.
107
- * @param {number} [options.offset] - The number of items to skip from the beginning of the result set.
108
- * @param {'asc' | 'desc'} [options.sort] - The sorting order for transactions based on block number ('asc' for ascending, 'desc' for descending).
109
- * @param {boolean} [forceFetch=false] - Forces the method to fetch transactions from the remote source even if they are already cached. (mostly used internally)
110
- * @returns {Promise<Transaction[]>} A promise that resolves to an array of transactions.
111
- */
112
- async transactions(params: GetTransactionsParams, forceFetch = false): Promise<Transaction[]> {
113
- if (!this.persistenceManager || forceFetch) {
114
- // If persistence is not configured, fetch directly from remote
115
- const hashes = await this._fetchTransactions(params);
116
- const transactions = await Promise.all(hashes.map(hash => this.client.transactions.get({ hash })));
117
-
118
- return transactions;
119
- }
120
-
121
- const jsons = await this.persistenceManager.getTransactions(this.address, params);
122
- return jsons.map(j => this.client.transactions.parse(j));
123
- }
124
-
125
- /**
126
- * Synchronizes the account's transactions with the remote data source using the configured `PersistenceManager`.
127
- * @description This method initiates a synchronization process to ensure that the local cache of transactions
128
- * for this account is up-to-date with the blockchain.
129
- * @param {number} [limit] The maximum number of transactions to synchronize.
130
- * @returns {Promise<void>} A promise that resolves when the synchronization process is complete.
131
- * @throws {Error} If the persistence module is not configured.
132
- */
133
- async syncTransactions(limit: number = 1000): Promise<void> {
134
- if (!this.persistenceManager) throw new Error("The persistence module is not configured.");
135
- await this.persistenceManager.syncTransactions(this, limit);
136
- }
137
-
138
- /**
139
- * Retrieves transactions involving a specific token. (not implemented yet)
140
- * @description This method queries the persistence adapter to retrieve transactions involving a specific token.
141
- * @param {Address} tokenAddress The address of the token.
142
- * @returns {Promise<any>} A promise that resolves to an array of transactions involving the token.
143
- * @throws {Error} If the persistence module is not configured.
144
- */
145
- async tokenTransactions(tokenAddress: Address): Promise<any> {
146
- if (!this.persistenceManager) throw new Error('The persistence module is not configured.');
147
-
148
- return {};
149
- }
150
-
151
- /**
152
- * Converts the Account instance into a JSON-serializable representation.
153
- * @description This method leverages a utility function to convert the `Account` object,
154
- * including its asynchronous properties (like `isContract`, `ETHBalance`), into a plain JSON object.
155
- * @param {number} [depth=1] The depth to which nested objects should be converted. A depth of 1 means only direct properties are included.
156
- * @returns {Promise<object>} A promise that resolves to the JSON representation of the account.
157
- */
158
- async toJSON<D extends number = 1>(depth: D): Promise<JSONAccount<D>> {
159
- return await toJSON({
160
- obj: {
161
- address: this.address,
162
- isContract: this.isContract.bind(this),
163
- contractType: this.contractType.bind(this),
164
- ETHBalance: this.ETHBalance.bind(this),
165
- transactionCount: this.transactionCount.bind(this),
166
- },
167
- depth
168
- });
169
- }
170
-
171
- /**
172
- * Fetches transactions from the account using a block range exploration with trace_filter calls.
173
- *
174
- * @param params - The parameters for the block range exploration.
175
- * @returns A Promise that resolves to an array of transaction hashes.
176
- */
177
- protected async _fetchTransactions({ fromBlock, toBlock, limit = 50 }: FetchTransactionParams): Promise<Hash[]> {
178
- const lastBlock = await getBlockNumber(this.client.rpc);
179
-
180
- const onBlockRange: onBlockRangeCallback = async ({ fromBlock, toBlock }, stop) => {
181
- const outgoing = await traceFilter(this.client.rpc, {
182
- fromBlock: toHex(fromBlock),
183
- toBlock: toHex(toBlock),
184
- fromAddress: this.address
185
- });
186
-
187
- const incoming = await traceFilter(this.client.rpc, {
188
- fromBlock: toHex(fromBlock),
189
- toBlock: toHex(toBlock),
190
- toAddress: this.address
191
- });
192
-
193
- const traces = outgoing.concat(incoming).sort((a, b) => a.blockNumber - b.blockNumber);
194
-
195
- return traces.map(t => t.transactionHash as Hash)
196
- };
197
-
198
- return await fetchByBlockRange({
199
- toBlock: BigInt(toBlock !== undefined ? toBlock : 0),
200
- fromBlock: BigInt(fromBlock !== undefined ? fromBlock : lastBlock),
201
- direction: "backward",
202
- itemLimit: limit,
203
- onBlockRange
204
- });
205
- }
206
- };
243
+ return await fetchByBlockRange({
244
+ toBlock: BigInt(toBlock !== undefined ? toBlock : 0),
245
+ fromBlock: BigInt(fromBlock !== undefined ? fromBlock : lastBlock),
246
+ direction: "backward",
247
+ itemLimit: limit,
248
+ onBlockRange,
249
+ });
250
+ }
251
+ }