@mentaproject/client 0.1.37 → 0.2.0

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.
package/dist/index.js CHANGED
@@ -10,15 +10,12 @@ import {
10
10
  getBalance,
11
11
  getBlockNumber,
12
12
  getCode,
13
- getTransaction,
14
13
  getTransactionCount,
15
- sendTransaction,
16
14
  traceFilter
17
15
  } from "@mentaproject/core/actions";
18
-
19
- // src/structures/Transaction.ts
20
- import { getBlock, getTransactionReceipt, traceTransaction, waitForTransactionReceipt } from "@mentaproject/core/actions";
21
- import { hexToBigInt } from "@mentaproject/core/utils";
16
+ import { Transaction } from "@mentaproject/transactions";
17
+ import { toHex } from "@mentaproject/core/utils";
18
+ import { getContractType } from "@mentaproject/contracts";
22
19
 
23
20
  // src/utils/toJSON.ts
24
21
  function isClassInstance(obj) {
@@ -88,70 +85,121 @@ async function toJSON({ obj, depth = 0 }) {
88
85
  return convertBigintsToStrings(data);
89
86
  }
90
87
 
91
- // src/structures/Block.ts
92
- var Block = class {
93
- /**
94
- * @description Creates an instance of Block.
95
- * @param client - The instance of MentaClient used to interact with the blockchain.
96
- * @param data The raw block data conforming to IBlockData.
97
- * @param includeTransactions Whether to include full transaction objects. Defaults to false.
98
- */
99
- constructor(client, data) {
88
+ // src/structures/Account.ts
89
+ var Account = class {
90
+ constructor(client, data, persistenceManager) {
100
91
  this.client = client;
101
- this.baseFeePerGas = data.baseFeePerGas;
102
- this.blobGasUsed = data.blobGasUsed;
103
- this.difficulty = data.difficulty;
104
- this.excessBlobGas = data.excessBlobGas;
105
- this.extraData = data.extraData;
106
- this.gasLimit = data.gasLimit;
107
- this.gasUsed = data.gasUsed;
108
- this.hash = data.hash;
109
- this.logsBloom = data.logsBloom;
110
- this.mixHash = data.mixHash;
111
- this.nonce = data.nonce;
112
- this.number = data.number;
113
- this.parentBeaconBlockRoot = data.parentBeaconBlockRoot;
114
- this.parentHash = data.parentHash;
115
- this.receiptsRoot = data.receiptsRoot;
116
- this.sealFields = data.sealFields;
117
- this.sha3Uncles = data.sha3Uncles;
118
- this.size = data.size;
119
- this.stateRoot = data.stateRoot;
120
- this.timestamp = data.timestamp;
121
- this.totalDifficulty = data.totalDifficulty;
122
- this.transactionsRoot = data.transactionsRoot;
123
- this.uncles = data.uncles;
124
- this.withdrawals = data.withdrawals;
125
- this.withdrawalsRoot = data.withdrawalsRoot;
126
- this.miner = new Account(this.client, { address: data.miner });
127
- if (!data.transactions || data.transactions.length === 0) {
128
- const parsed = data.transactions.map((data2) => typeof data2 === "string" ? data2 : new Transaction(this.client, data2));
129
- this.transactions = parsed;
130
- }
92
+ this.address = data.address;
93
+ this.persistenceManager = persistenceManager;
131
94
  }
132
- includeTransactions() {
133
- if (!this.transactions || this.transactions.length === 0) return false;
95
+ async isContract() {
96
+ const code = await getCode(this.client.rpc, { address: this.address });
97
+ if (!code || code === "0x") return false;
134
98
  return true;
135
99
  }
100
+ async contractType() {
101
+ const isContract = await this.isContract();
102
+ if (!isContract) return void 0;
103
+ return await getContractType(this.client.rpc, this.address);
104
+ }
136
105
  /**
137
- * @description Converts the Block instance to a JSON representation.
138
- * This method serializes the block's properties into a plain JavaScript object,
139
- * suitable for JSON serialization.
140
- * @param depth The depth of the conversion. Defaults to 1.
141
- * @returns A promise that resolves to the JSON representation of the block.
142
- */
106
+ * Creates a Transaction to send ETH to this account.
107
+ *
108
+ * @param amount The amount of ETH to send, in wei.
109
+ * @returns A Transaction with .call(), .simulate(), and .execute() methods.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * // Direct execution
114
+ * const pending = await account.sendEth(parseEther("1")).execute();
115
+ * const receipt = await pending.confirm();
116
+ *
117
+ * // Batch with MulticallTransaction
118
+ * multicall.addCall(account.sendEth(parseEther("1")));
119
+ * ```
120
+ */
121
+ sendEth(amount) {
122
+ return new Transaction(this.client.rpc, {
123
+ to: this.address,
124
+ value: amount
125
+ });
126
+ }
127
+ async ETHBalance() {
128
+ return await getBalance(this.client.rpc, { address: this.address });
129
+ }
130
+ async transactionCount() {
131
+ return await getTransactionCount(this.client.rpc, { address: this.address });
132
+ }
133
+ async transactions(params, forceFetch = false) {
134
+ if (!this.persistenceManager || forceFetch) {
135
+ const hashes = await this._fetchTransactions(params);
136
+ const transactions = await Promise.all(
137
+ hashes.map((hash) => this.client.transactions.get({ hash }))
138
+ );
139
+ return transactions;
140
+ }
141
+ const jsons = await this.persistenceManager.getTransactions(
142
+ this.address,
143
+ params
144
+ );
145
+ return jsons.map((j) => this.client.transactions.parse(j));
146
+ }
147
+ async syncTransactions(limit = 1e3) {
148
+ if (!this.persistenceManager)
149
+ throw new Error("The persistence module is not configured.");
150
+ await this.persistenceManager.syncTransactions(this, limit);
151
+ }
152
+ async tokenTransactions(tokenAddress) {
153
+ if (!this.persistenceManager)
154
+ throw new Error("The persistence module is not configured.");
155
+ return {};
156
+ }
143
157
  async toJSON(depth) {
144
158
  return await toJSON({
145
159
  obj: {
146
- ...this
160
+ address: this.address,
161
+ isContract: this.isContract.bind(this),
162
+ contractType: this.contractType.bind(this),
163
+ ETHBalance: this.ETHBalance.bind(this),
164
+ transactionCount: this.transactionCount.bind(this)
147
165
  },
148
166
  depth
149
167
  });
150
168
  }
169
+ async _fetchTransactions({
170
+ fromBlock,
171
+ toBlock,
172
+ limit = 50
173
+ }) {
174
+ const lastBlock = await getBlockNumber(this.client.rpc);
175
+ const onBlockRange = async ({ fromBlock: fromBlock2, toBlock: toBlock2 }, stop) => {
176
+ const outgoing = await traceFilter(this.client.rpc, {
177
+ fromBlock: toHex(fromBlock2),
178
+ toBlock: toHex(toBlock2),
179
+ fromAddress: this.address
180
+ });
181
+ const incoming = await traceFilter(this.client.rpc, {
182
+ fromBlock: toHex(fromBlock2),
183
+ toBlock: toHex(toBlock2),
184
+ toAddress: this.address
185
+ });
186
+ const traces = outgoing.concat(incoming).sort((a, b) => a.blockNumber - b.blockNumber);
187
+ return traces.map((t) => t.transactionHash);
188
+ };
189
+ return await fetchByBlockRange({
190
+ toBlock: BigInt(toBlock !== void 0 ? toBlock : 0),
191
+ fromBlock: BigInt(fromBlock !== void 0 ? fromBlock : lastBlock),
192
+ direction: "backward",
193
+ itemLimit: limit,
194
+ onBlockRange
195
+ });
196
+ }
151
197
  };
152
198
 
153
199
  // src/structures/Transaction.ts
154
- var Transaction = class {
200
+ import { getBlock, getTransactionReceipt, traceTransaction, waitForTransactionReceipt } from "@mentaproject/core/actions";
201
+ import { hexToBigInt } from "@mentaproject/core/utils";
202
+ var Transaction2 = class {
155
203
  /**
156
204
  * Creates an instance of Transaction.
157
205
  * @description Initializes a new Transaction instance with the provided RPC client and transaction data.
@@ -258,187 +306,66 @@ var Transaction = class {
258
306
  }
259
307
  };
260
308
 
261
- // src/structures/Account.ts
262
- import { toHex } from "@mentaproject/core/utils";
263
- import { getContractType } from "@mentaproject/contracts";
264
- var Account = class {
309
+ // src/structures/Block.ts
310
+ var Block = class {
265
311
  /**
266
- * Creates an instance of the Account class.
267
- * @param client.rpc The CoreClient instance used for blockchain interactions.
268
- * @param address The blockchain address of the account.
269
- * @param persistenceManager An optional PersistenceManager instance for caching and data synchronization.
312
+ * @description Creates an instance of Block.
313
+ * @param client - The instance of MentaClient used to interact with the blockchain.
314
+ * @param data The raw block data conforming to IBlockData.
315
+ * @param includeTransactions Whether to include full transaction objects. Defaults to false.
270
316
  */
271
- constructor(client, data, persistenceManager) {
317
+ constructor(client, data) {
272
318
  this.client = client;
273
- this.address = data.address;
274
- this.persistenceManager = persistenceManager;
275
- }
276
- /**
277
- * Checks if the account's address belongs to a smart contract.
278
- * @description This method queries the blockchain for the code associated with the account's address.
279
- * If code is found, it indicates that the account is a contract.
280
- * @returns {Promise<boolean>} A promise that resolves to `true` if the account is a contract, `false` otherwise.
281
- */
282
- async isContract() {
283
- const code = await getCode(this.client.rpc, { address: this.address });
284
- if (!code || code === "0x") return false;
285
- return true;
286
- }
287
- /**
288
- * Retrieves the type of the contract if the account is a smart contract.
289
- * @description This method first checks if the account is a contract using `isContract()`.
290
- * If it is a contract, it then attempts to determine and return its type.
291
- * @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.
292
- */
293
- async contractType() {
294
- const isContract = await this.isContract();
295
- if (!isContract) return void 0;
296
- return await getContractType(this.client.rpc, this.address);
297
- }
298
- /**
299
- * Sends a specified amount of native cryptocurrency (ETH) to this account.
300
- * @description This method constructs and sends a transaction to transfer ETH to the account's address.
301
- * @param {bigint} amount The amount of ETH to send, specified in wei (the smallest denomination of Ether).
302
- * @returns {Promise<Transaction>} A promise that resolves to a `Transaction` object representing the sent transaction.
303
- */
304
- async sendETH(amount) {
305
- const hash = await sendTransaction(this.client.rpc, {
306
- calls: [
307
- {
308
- to: this.address,
309
- value: amount
310
- }
311
- ]
312
- });
313
- const data = await getTransaction(this.client.rpc, { hash });
314
- return new Transaction(this.client, data);
315
- }
316
- /**
317
- * Retrieves the current native cryptocurrency (ETH) balance of the account.
318
- * @description This method queries the blockchain to get the balance associated with the account's address.
319
- * @returns {Promise<bigint>} A promise that resolves to the ETH balance of the account, in wei.
320
- */
321
- async ETHBalance() {
322
- return await getBalance(this.client.rpc, {
323
- address: this.address
324
- });
325
- }
326
- /**
327
- * Retrieves the transaction count (nonce) for the account.
328
- * @description The transaction count represents the number of transactions sent from this account,
329
- * which is also used as the nonce for new transactions to prevent replay attacks.
330
- * @returns {Promise<number>} A promise that resolves to the transaction count of the account.
331
- */
332
- async transactionCount() {
333
- return await getTransactionCount(this.client.rpc, {
334
- address: this.address
335
- });
336
- }
337
- /**
338
- * Retrieves all transactions involving this account.
339
- * @description If a `PersistenceManager` is configured, this method will first attempt to retrieve transactions from the local cache.
340
- * If not found in cache or if no `PersistenceManager` is configured, it will fetch transactions directly from the remote RPC.
341
- * @param {GetTransactionsOptions} [options] - Optional parameters for filtering, pagination, and sorting the transactions.
342
- * @param {number} [options.startBlock] - The starting block number (inclusive) from which to retrieve transactions.
343
- * @param {number} [options.endBlock] - The ending block number (inclusive) up to which to retrieve transactions.
344
- * @param {number} [options.page] - The page number for paginated results.
345
- * @param {number} [options.offset] - The number of items to skip from the beginning of the result set.
346
- * @param {'asc' | 'desc'} [options.sort] - The sorting order for transactions based on block number ('asc' for ascending, 'desc' for descending).
347
- * @param {boolean} [forceFetch=false] - Forces the method to fetch transactions from the remote source even if they are already cached. (mostly used internally)
348
- * @returns {Promise<Transaction[]>} A promise that resolves to an array of transactions.
349
- */
350
- async transactions(params, forceFetch = false) {
351
- if (!this.persistenceManager || forceFetch) {
352
- const hashes = await this._fetchTransactions(params);
353
- const transactions = await Promise.all(
354
- hashes.map((hash) => this.client.transactions.get({ hash }))
355
- );
356
- return transactions;
319
+ this.baseFeePerGas = data.baseFeePerGas;
320
+ this.blobGasUsed = data.blobGasUsed;
321
+ this.difficulty = data.difficulty;
322
+ this.excessBlobGas = data.excessBlobGas;
323
+ this.extraData = data.extraData;
324
+ this.gasLimit = data.gasLimit;
325
+ this.gasUsed = data.gasUsed;
326
+ this.hash = data.hash;
327
+ this.logsBloom = data.logsBloom;
328
+ this.mixHash = data.mixHash;
329
+ this.nonce = data.nonce;
330
+ this.number = data.number;
331
+ this.parentBeaconBlockRoot = data.parentBeaconBlockRoot;
332
+ this.parentHash = data.parentHash;
333
+ this.receiptsRoot = data.receiptsRoot;
334
+ this.sealFields = data.sealFields;
335
+ this.sha3Uncles = data.sha3Uncles;
336
+ this.size = data.size;
337
+ this.stateRoot = data.stateRoot;
338
+ this.timestamp = data.timestamp;
339
+ this.totalDifficulty = data.totalDifficulty;
340
+ this.transactionsRoot = data.transactionsRoot;
341
+ this.uncles = data.uncles;
342
+ this.withdrawals = data.withdrawals;
343
+ this.withdrawalsRoot = data.withdrawalsRoot;
344
+ this.miner = new Account(this.client, { address: data.miner });
345
+ if (!data.transactions || data.transactions.length === 0) {
346
+ const parsed = data.transactions.map((data2) => typeof data2 === "string" ? data2 : new Transaction2(this.client, data2));
347
+ this.transactions = parsed;
357
348
  }
358
- const jsons = await this.persistenceManager.getTransactions(
359
- this.address,
360
- params
361
- );
362
- return jsons.map((j) => this.client.transactions.parse(j));
363
349
  }
364
- /**
365
- * Synchronizes the account's transactions with the remote data source using the configured `PersistenceManager`.
366
- * @description This method initiates a synchronization process to ensure that the local cache of transactions
367
- * for this account is up-to-date with the blockchain.
368
- * @param {number} [limit] The maximum number of transactions to synchronize.
369
- * @returns {Promise<void>} A promise that resolves when the synchronization process is complete.
370
- * @throws {Error} If the persistence module is not configured.
371
- */
372
- async syncTransactions(limit = 1e3) {
373
- if (!this.persistenceManager)
374
- throw new Error("The persistence module is not configured.");
375
- await this.persistenceManager.syncTransactions(this, limit);
376
- }
377
- /**
378
- * Retrieves transactions involving a specific token. (not implemented yet)
379
- * @description This method queries the persistence adapter to retrieve transactions involving a specific token.
380
- * @param {Address} tokenAddress The address of the token.
381
- * @returns {Promise<any>} A promise that resolves to an array of transactions involving the token.
382
- * @throws {Error} If the persistence module is not configured.
383
- */
384
- async tokenTransactions(tokenAddress) {
385
- if (!this.persistenceManager)
386
- throw new Error("The persistence module is not configured.");
387
- return {};
350
+ includeTransactions() {
351
+ if (!this.transactions || this.transactions.length === 0) return false;
352
+ return true;
388
353
  }
389
354
  /**
390
- * Converts the Account instance into a JSON-serializable representation.
391
- * @description This method leverages a utility function to convert the `Account` object,
392
- * including its asynchronous properties (like `isContract`, `ETHBalance`), into a plain JSON object.
393
- * @param {number} [depth=1] The depth to which nested objects should be converted. A depth of 1 means only direct properties are included.
394
- * @returns {Promise<object>} A promise that resolves to the JSON representation of the account.
355
+ * @description Converts the Block instance to a JSON representation.
356
+ * This method serializes the block's properties into a plain JavaScript object,
357
+ * suitable for JSON serialization.
358
+ * @param depth The depth of the conversion. Defaults to 1.
359
+ * @returns A promise that resolves to the JSON representation of the block.
395
360
  */
396
361
  async toJSON(depth) {
397
362
  return await toJSON({
398
363
  obj: {
399
- address: this.address,
400
- isContract: this.isContract.bind(this),
401
- contractType: this.contractType.bind(this),
402
- ETHBalance: this.ETHBalance.bind(this),
403
- transactionCount: this.transactionCount.bind(this)
364
+ ...this
404
365
  },
405
366
  depth
406
367
  });
407
368
  }
408
- /**
409
- * Fetches transactions from the account using a block range exploration with trace_filter calls.
410
- *
411
- * @param params - The parameters for the block range exploration.
412
- * @returns A Promise that resolves to an array of transaction hashes.
413
- */
414
- async _fetchTransactions({
415
- fromBlock,
416
- toBlock,
417
- limit = 50
418
- }) {
419
- const lastBlock = await getBlockNumber(this.client.rpc);
420
- const onBlockRange = async ({ fromBlock: fromBlock2, toBlock: toBlock2 }, stop) => {
421
- const outgoing = await traceFilter(this.client.rpc, {
422
- fromBlock: toHex(fromBlock2),
423
- toBlock: toHex(toBlock2),
424
- fromAddress: this.address
425
- });
426
- const incoming = await traceFilter(this.client.rpc, {
427
- fromBlock: toHex(fromBlock2),
428
- toBlock: toHex(toBlock2),
429
- toAddress: this.address
430
- });
431
- const traces = outgoing.concat(incoming).sort((a, b) => a.blockNumber - b.blockNumber);
432
- return traces.map((t) => t.transactionHash);
433
- };
434
- return await fetchByBlockRange({
435
- toBlock: BigInt(toBlock !== void 0 ? toBlock : 0),
436
- fromBlock: BigInt(fromBlock !== void 0 ? fromBlock : lastBlock),
437
- direction: "backward",
438
- itemLimit: limit,
439
- onBlockRange
440
- });
441
- }
442
369
  };
443
370
 
444
371
  // src/structures/MentaClient.ts
@@ -490,7 +417,8 @@ var BlockManager = class {
490
417
  };
491
418
 
492
419
  // src/managers/TransactionManager.ts
493
- import { getTransaction as getTransaction2, sendTransaction as sendTransaction2 } from "@mentaproject/core/actions";
420
+ import { MulticallTransaction } from "@mentaproject/transactions";
421
+ import { getTransaction, sendTransaction } from "@mentaproject/core/actions";
494
422
 
495
423
  // src/utils/bigint.ts
496
424
  var bigIntMax = (...args) => args.reduce((m, e) => e > m ? e : m);
@@ -546,36 +474,49 @@ function parseBingints(obj) {
546
474
 
547
475
  // src/managers/TransactionManager.ts
548
476
  var TransactionManager = class {
549
- /**
550
- * Creates an instance of `TransactionManager`.
551
- * @constructor
552
- * @param {MentaClient} client - The instance of MentaClient used to interact with the blockchain.
553
- */
554
477
  constructor(client) {
555
478
  this.client = client;
556
479
  }
557
480
  /**
558
- * Retrieves a transaction by its hash or block number and index.
559
- * @description This method fetches detailed information about a specific transaction
560
- * from the blockchain using the provided parameters.
561
- * @param {GetTransactionParameters} params - The parameters for retrieving the transaction,
562
- * typically including `hash` or `blockNumber` and `index`.
563
- * @returns {Promise<Transaction>} A promise that resolves to a {@link Transaction} instance
564
- * containing the retrieved transaction data.
481
+ * Creates a new MulticallTransaction for batching multiple calls.
482
+ *
483
+ * @returns A MulticallTransaction builder
484
+ *
565
485
  * @example
566
- * const txHash = '0x...'; // Replace with a valid transaction hash
567
- * const transaction = await client.transactions.get({ hash: txHash });
568
- * console.log(transaction);
486
+ * ```ts
487
+ * const pending = await client.transactions.create()
488
+ * .addCall(account.sendEth(parseEther("1")))
489
+ * .addCall(erc20.transfer(to, amount))
490
+ * .execute();
491
+ * ```
492
+ */
493
+ create() {
494
+ return new MulticallTransaction(this.client.rpc);
495
+ }
496
+ /**
497
+ * Retrieves a rich transaction by its hash.
498
+ *
499
+ * @param hash - The transaction hash
500
+ * @returns A rich Transaction with receipt, block, etc.
501
+ *
502
+ * @example
503
+ * ```ts
504
+ * const tx = await client.transactions.fromHash(hash);
505
+ * console.log(tx.from, tx.to, tx.value);
506
+ * ```
507
+ */
508
+ async fromHash(hash) {
509
+ return this.get({ hash });
510
+ }
511
+ /**
512
+ * Retrieves a transaction by its hash or block number and index.
569
513
  */
570
514
  async get(params) {
571
- const data = await getTransaction2(this.client.rpc, params);
572
- return new Transaction(this.client, data);
515
+ const data = await getTransaction(this.client.rpc, params);
516
+ return new Transaction2(this.client, data);
573
517
  }
574
518
  /**
575
519
  * Parse a transaction object from a JSON converted transaction data object.
576
- *
577
- * @param {J} data - The JSON converted transaction data object.
578
- * @returns {Transaction} A Transaction instance representing the parsed transaction.
579
520
  */
580
521
  parse(data) {
581
522
  const parsed = parseBingints(data);
@@ -584,35 +525,14 @@ var TransactionManager = class {
584
525
  from: parsed.from.address,
585
526
  to: parsed.to ? parsed.to.address : null
586
527
  };
587
- return new Transaction(this.client, rawData);
528
+ return new Transaction2(this.client, rawData);
588
529
  }
589
530
  /**
590
531
  * Sends a transaction to the blockchain network.
591
- * @description This method submits a new transaction to the blockchain. After the transaction
592
- * is successfully sent, it retrieves and returns the full transaction details.
593
- * @param {SendTransactionParameters} params - The parameters required to send the transaction,
594
- * such as `to`, `value`, `data`, `gasLimit`, etc.
595
- * @returns {Promise<Transaction>} A promise that resolves to a {@link Transaction} instance
596
- * representing the sent transaction, including its hash and other details.
597
- * @example
598
- * import { MentaClient } from '@mentaproject/client';
599
- * import { http } from '@mentaproject/core';
600
- *
601
- * // This example assumes you have an account with funds, which is available to the client.
602
- * const client = new MentaClient({
603
- * chain: 'mainnet',
604
- * transport: http('http://rpcurlhere.com')
605
- * });
606
- *
607
- * const transactionResult = await client.transactions.send({
608
- * to: '0xRecipientAddress...', // Replace with a valid recipient address
609
- * value: 1000000000000000000n, // 1 ETH in wei
610
- * });
611
- *
612
- * console.log('Transaction sent with hash:', transactionResult.hash);
532
+ * @deprecated Use client.transactions.create() for new transactions
613
533
  */
614
534
  async send(params) {
615
- const hash = await sendTransaction2(this.client.rpc, params);
535
+ const hash = await sendTransaction(this.client.rpc, params);
616
536
  return await this.get({ hash });
617
537
  }
618
538
  };
@@ -1009,7 +929,7 @@ export {
1009
929
  ContractManager,
1010
930
  MemoryCache,
1011
931
  MentaClient,
1012
- Transaction,
932
+ Transaction2 as Transaction,
1013
933
  TransactionManager,
1014
934
  bigIntMax,
1015
935
  bigIntMin,