@mentaproject/client 0.1.23 → 0.1.25

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 (37) hide show
  1. package/dist/managers/PersistenceManager.d.ts +3 -3
  2. package/dist/managers/TransactionManager.d.ts +1 -1
  3. package/dist/structures/Account.d.ts +1 -1
  4. package/dist/structures/Account.js +21 -19
  5. package/dist/structures/MentaClient.d.ts +5 -2
  6. package/dist/structures/MentaClient.js +24 -5
  7. package/dist/types/MentaClient.d.ts +10 -2
  8. package/dist/types/MentaClient.js +0 -2
  9. package/dist/types/PersistenceAdapter.d.ts +3 -2
  10. package/package.json +4 -4
  11. package/src/index.ts +21 -0
  12. package/src/managers/AccountManager.ts +51 -0
  13. package/src/managers/BlockManager.ts +51 -0
  14. package/src/managers/ContractManager.ts +60 -0
  15. package/src/managers/PersistenceManager.ts +59 -0
  16. package/src/managers/TransactionManager.ts +92 -0
  17. package/src/managers/index.ts +4 -0
  18. package/src/structures/Account.ts +251 -0
  19. package/src/structures/Block.ts +185 -0
  20. package/src/structures/Cache.ts +126 -0
  21. package/src/structures/MentaClient.ts +152 -0
  22. package/src/structures/Transaction.ts +220 -0
  23. package/src/structures/index.ts +5 -0
  24. package/src/types/Account.ts +44 -0
  25. package/src/types/Block.ts +14 -0
  26. package/src/types/Cache.ts +55 -0
  27. package/src/types/JsonRPC.ts +126 -0
  28. package/src/types/MentaClient.ts +79 -0
  29. package/src/types/PersistenceAdapter.ts +44 -0
  30. package/src/types/Transaction.ts +52 -0
  31. package/src/types/Utils.ts +30 -0
  32. package/src/types/index.ts +8 -0
  33. package/src/utils/bigint.ts +59 -0
  34. package/src/utils/toJSON.ts +123 -0
  35. package/src/utils/withCache.ts +50 -0
  36. package/test.ts +0 -89
  37. package/transactions.json +0 -1302
@@ -1,7 +1,7 @@
1
1
  import { Address } from '@mentaproject/core/types';
2
2
  import { Account } from '../structures/Account';
3
- import { MentaClient, Transaction } from '../structures';
4
- import { GetTransactionsParams, IPersistenceAdapter } from 'src/types';
3
+ import { MentaClient } from '../structures';
4
+ import { GetTransactionsParams, IPersistenceAdapter, JSONTransaction } from 'src/types';
5
5
  /**
6
6
  * Manages the persistence of data, including transactions, using a specified persistence adapter.
7
7
  * It handles fetching data from both local storage and remote sources, and synchronizing them.
@@ -20,7 +20,7 @@ export declare class PersistenceManager {
20
20
  * @param params - Parameters for retrieving transactions.
21
21
  * @returns A promise that resolves to an array of transactions with associated account information.
22
22
  */
23
- getTransactions(address: Address, params: GetTransactionsParams): Promise<Transaction[]>;
23
+ getTransactions(address: Address, params: GetTransactionsParams): Promise<JSONTransaction<0>[]>;
24
24
  /**
25
25
  * Synchronizes an account's transactions from the remote source to the local persistence.
26
26
  * It fetches new transactions starting from the last synced block and updates the local storage.
@@ -40,7 +40,7 @@ export declare class TransactionManager {
40
40
  * @param {J} data - The JSON converted transaction data object.
41
41
  * @returns {Transaction} A Transaction instance representing the parsed transaction.
42
42
  */
43
- parse<J extends JSONTransaction<number>>(data: J): Transaction;
43
+ parse<J extends JSONTransaction<0>>(data: J): Transaction;
44
44
  /**
45
45
  * Sends a transaction to the blockchain network.
46
46
  * @description This method submits a new transaction to the blockchain. After the transaction
@@ -100,5 +100,5 @@ export declare class Account implements AccountData {
100
100
  * @param params - The parameters for the block range exploration.
101
101
  * @returns A Promise that resolves to an array of transaction hashes.
102
102
  */
103
- protected _fetchTransactions({ fromBlock, toBlock, limit }: FetchTransactionParams): Promise<Hash[]>;
103
+ protected _fetchTransactions({ fromBlock, toBlock, limit, }: FetchTransactionParams): Promise<Hash[]>;
104
104
  }
@@ -1,4 +1,4 @@
1
- import { fetchByBlockRange, getBalance, getBlockNumber, getCode, getTransaction, getTransactionCount, sendTransaction, traceFilter } from "@mentaproject/core/actions";
1
+ import { fetchByBlockRange, getBalance, getBlockNumber, getCode, getTransaction, getTransactionCount, sendTransaction, traceFilter, } from "@mentaproject/core/actions";
2
2
  import { Transaction } from "./Transaction";
3
3
  import { toHex } from "@mentaproject/core/utils";
4
4
  import { getContractType } from "@mentaproject/contracts";
@@ -31,7 +31,6 @@ export class Account {
31
31
  return false;
32
32
  return true;
33
33
  }
34
- ;
35
34
  /**
36
35
  * Retrieves the type of the contract if the account is a smart contract.
37
36
  * @description This method first checks if the account is a contract using `isContract()`.
@@ -44,7 +43,6 @@ export class Account {
44
43
  return undefined;
45
44
  return await getContractType(this.client.rpc, this.address);
46
45
  }
47
- ;
48
46
  /**
49
47
  * Sends a specified amount of native cryptocurrency (ETH) to this account.
50
48
  * @description This method constructs and sends a transaction to transfer ETH to the account's address.
@@ -53,15 +51,16 @@ export class Account {
53
51
  */
54
52
  async sendETH(amount) {
55
53
  const hash = await sendTransaction(this.client.rpc, {
56
- calls: [{
54
+ calls: [
55
+ {
57
56
  to: this.address,
58
57
  value: amount,
59
- }]
58
+ },
59
+ ],
60
60
  });
61
61
  const data = await getTransaction(this.client.rpc, { hash });
62
62
  return new Transaction(this.client, data);
63
63
  }
64
- ;
65
64
  /**
66
65
  * Retrieves the current native cryptocurrency (ETH) balance of the account.
67
66
  * @description This method queries the blockchain to get the balance associated with the account's address.
@@ -72,7 +71,6 @@ export class Account {
72
71
  address: this.address,
73
72
  });
74
73
  }
75
- ;
76
74
  /**
77
75
  * Retrieves the transaction count (nonce) for the account.
78
76
  * @description The transaction count represents the number of transactions sent from this account,
@@ -80,7 +78,9 @@ export class Account {
80
78
  * @returns {Promise<number>} A promise that resolves to the transaction count of the account.
81
79
  */
82
80
  async transactionCount() {
83
- return await getTransactionCount(this.client.rpc, { address: this.address });
81
+ return await getTransactionCount(this.client.rpc, {
82
+ address: this.address,
83
+ });
84
84
  }
85
85
  /**
86
86
  * Retrieves all transactions involving this account.
@@ -99,10 +99,11 @@ export class Account {
99
99
  if (!this.persistenceManager || forceFetch) {
100
100
  // If persistence is not configured, fetch directly from remote
101
101
  const hashes = await this._fetchTransactions(params);
102
- const transactions = await Promise.all(hashes.map(hash => this.client.transactions.get({ hash })));
102
+ const transactions = await Promise.all(hashes.map((hash) => this.client.transactions.get({ hash })));
103
103
  return transactions;
104
104
  }
105
- return await this.persistenceManager.getTransactions(this.address, params);
105
+ const jsons = await this.persistenceManager.getTransactions(this.address, params);
106
+ return jsons.map((j) => this.client.transactions.parse(j));
106
107
  }
107
108
  /**
108
109
  * Synchronizes the account's transactions with the remote data source using the configured `PersistenceManager`.
@@ -126,7 +127,7 @@ export class Account {
126
127
  */
127
128
  async tokenTransactions(tokenAddress) {
128
129
  if (!this.persistenceManager)
129
- throw new Error('The persistence module is not configured.');
130
+ throw new Error("The persistence module is not configured.");
130
131
  return {};
131
132
  }
132
133
  /**
@@ -145,7 +146,7 @@ export class Account {
145
146
  ETHBalance: this.ETHBalance.bind(this),
146
147
  transactionCount: this.transactionCount.bind(this),
147
148
  },
148
- depth
149
+ depth,
149
150
  });
150
151
  }
151
152
  /**
@@ -154,29 +155,30 @@ export class Account {
154
155
  * @param params - The parameters for the block range exploration.
155
156
  * @returns A Promise that resolves to an array of transaction hashes.
156
157
  */
157
- async _fetchTransactions({ fromBlock, toBlock, limit = 50 }) {
158
+ async _fetchTransactions({ fromBlock, toBlock, limit = 50, }) {
158
159
  const lastBlock = await getBlockNumber(this.client.rpc);
159
160
  const onBlockRange = async ({ fromBlock, toBlock }, stop) => {
160
161
  const outgoing = await traceFilter(this.client.rpc, {
161
162
  fromBlock: toHex(fromBlock),
162
163
  toBlock: toHex(toBlock),
163
- fromAddress: this.address
164
+ fromAddress: this.address,
164
165
  });
165
166
  const incoming = await traceFilter(this.client.rpc, {
166
167
  fromBlock: toHex(fromBlock),
167
168
  toBlock: toHex(toBlock),
168
- toAddress: this.address
169
+ toAddress: this.address,
169
170
  });
170
- const traces = outgoing.concat(incoming).sort((a, b) => a.blockNumber - b.blockNumber);
171
- return traces.map(t => t.transactionHash);
171
+ const traces = outgoing
172
+ .concat(incoming)
173
+ .sort((a, b) => a.blockNumber - b.blockNumber);
174
+ return traces.map((t) => t.transactionHash);
172
175
  };
173
176
  return await fetchByBlockRange({
174
177
  toBlock: BigInt(toBlock !== undefined ? toBlock : 0),
175
178
  fromBlock: BigInt(fromBlock !== undefined ? fromBlock : lastBlock),
176
179
  direction: "backward",
177
180
  itemLimit: limit,
178
- onBlockRange
181
+ onBlockRange,
179
182
  });
180
183
  }
181
184
  }
182
- ;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @module MentaClient
3
3
  */
4
- import type { CoreClient } from "@mentaproject/core/types";
4
+ import type { MentaAccountClient } from "@mentaproject/core/types";
5
5
  import { BlockManager } from "../managers/BlockManager";
6
6
  import { TransactionManager } from "../managers/TransactionManager";
7
7
  import { ContractManager } from "../managers/ContractManager";
@@ -17,11 +17,13 @@ import { ClientEvents, GetListenerCallback, MentaClientConfig } from "../types/M
17
17
  * simplifying common operations.
18
18
  */
19
19
  export declare class MentaClient {
20
+ protected params: MentaClientConfig;
21
+ protected _rpc?: MentaAccountClient;
20
22
  /**
21
23
  * The underlying RPC client used for blockchain interactions.
22
24
  * @description This client is responsible for low-level communication with the RPC node.
23
25
  */
24
- rpc: CoreClient;
26
+ get rpc(): MentaAccountClient;
25
27
  /**
26
28
  * Manager for block-related operations.
27
29
  * @description Provides methods to query and interact with blockchain blocks.
@@ -85,6 +87,7 @@ export declare class MentaClient {
85
87
  * });
86
88
  */
87
89
  constructor(params: MentaClientConfig);
90
+ init(): Promise<void>;
88
91
  /**
89
92
  * Optional manager for persistence-related operations.
90
93
  * @description This manager is initialized if a persistence adapter is provided in the client configuration,
@@ -1,11 +1,12 @@
1
- import { createClient } from "@mentaproject/core";
1
+ import { createMentaAccount } from "@mentaproject/core/clients";
2
2
  import { BlockManager } from "../managers/BlockManager";
3
3
  import { TransactionManager } from "../managers/TransactionManager";
4
4
  import { ContractManager } from "../managers/ContractManager";
5
5
  import { AccountManager } from "../managers/AccountManager";
6
6
  import { PersistenceManager } from "../managers/PersistenceManager";
7
- import { ClientEvents } from "../types/MentaClient";
7
+ import { ClientEvents, } from "../types/MentaClient";
8
8
  import { withCache } from "../utils/withCache";
9
+ import { createClient } from "@mentaproject/core";
9
10
  /**
10
11
  * The main client for interacting with the Menta API.
11
12
  * It provides managers for blocks, transactions, contracts, and accounts.
@@ -15,6 +16,16 @@ import { withCache } from "../utils/withCache";
15
16
  * simplifying common operations.
16
17
  */
17
18
  export class MentaClient {
19
+ /**
20
+ * The underlying RPC client used for blockchain interactions.
21
+ * @description This client is responsible for low-level communication with the RPC node.
22
+ */
23
+ get rpc() {
24
+ if (!this._rpc) {
25
+ throw new Error("RPC client not initialized");
26
+ }
27
+ return this._rpc;
28
+ }
18
29
  /**
19
30
  * Subscribes to a specific client event.
20
31
  * @template TEvent The type of the event to listen for.
@@ -66,9 +77,7 @@ export class MentaClient {
66
77
  * });
67
78
  */
68
79
  constructor(params) {
69
- this.rpc = createClient(params);
70
- if (params.cache)
71
- this.rpc = withCache(this.rpc, params.cache);
80
+ this.params = params;
72
81
  this.blocks = new BlockManager(this);
73
82
  this.transactions = new TransactionManager(this);
74
83
  this.contracts = new ContractManager(this);
@@ -80,4 +89,14 @@ export class MentaClient {
80
89
  this.accounts = new AccountManager(this);
81
90
  }
82
91
  }
92
+ async init() {
93
+ let coreClient = createClient(this.params);
94
+ if (this.params.cache) {
95
+ coreClient = withCache(coreClient, this.params.cache);
96
+ }
97
+ this._rpc = await createMentaAccount(coreClient, {
98
+ signer: this.params.signer,
99
+ bundlerTransport: this.params.bundlerTransport,
100
+ });
101
+ }
83
102
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @module MentaClientTypes
3
3
  */
4
- import { CoreClientConfig } from "@mentaproject/core/types";
4
+ import { CoreClientConfig, PasskeySigner, Transport } from "@mentaproject/core/types";
5
5
  import { ICache } from "./Cache";
6
6
  import { watchBlockNumber, watchBlocks } from "@mentaproject/core/actions";
7
7
  import { IPersistenceAdapter } from "./PersistenceAdapter";
@@ -33,6 +33,14 @@ export interface MentaClientConfig extends CoreClientConfig {
33
33
  * If provided, the client will use this adapter to persist and retrieve data.
34
34
  */
35
35
  persistenceAdapter?: IPersistenceAdapter;
36
+ /**
37
+ * Bundler transport used for userOperations
38
+ */
39
+ bundlerTransport: Transport;
40
+ /**
41
+ * Passkey compatible signer used for signing user operations
42
+ */
43
+ signer: PasskeySigner;
36
44
  }
37
45
  /**
38
46
  * Defines the available client events and their corresponding watch functions.
@@ -55,6 +63,6 @@ export declare const ClientEvents: {
55
63
  * This type dynamically determines the expected callback signature for a specific client event.
56
64
  * @template TEvent The name of the event (e.g., 'block' or 'blockNumber') for which to get the listener callback type.
57
65
  */
58
- export type GetListenerCallback<TEvent extends keyof typeof ClientEvents> = Parameters<typeof ClientEvents[TEvent]>[1] extends infer P ? P extends {
66
+ export type GetListenerCallback<TEvent extends keyof typeof ClientEvents> = Parameters<(typeof ClientEvents)[TEvent]>[1] extends infer P ? P extends {
59
67
  [K in `on${Capitalize<TEvent>}`]: infer TCallback;
60
68
  } ? TCallback : never : never;
@@ -1,6 +1,4 @@
1
1
  import { watchBlockNumber, watchBlocks } from "@mentaproject/core/actions";
2
- ;
3
- ;
4
2
  /**
5
3
  * Defines the available client events and their corresponding watch functions.
6
4
  * These functions are used to subscribe to real-time updates from the client.
@@ -1,6 +1,7 @@
1
1
  import { Address } from '@mentaproject/core/types';
2
2
  import { Transaction } from '../structures/Transaction';
3
3
  import { GetTransactionsParams } from './Account';
4
+ import { JSONTransaction } from './Transaction';
4
5
  /**
5
6
  * @interface IPersistenceAdapter
6
7
  * @description Defines the contract for persistence layers, ensuring consistent data storage and retrieval operations.
@@ -17,9 +18,9 @@ export interface IPersistenceAdapter {
17
18
  * @method getTransactions
18
19
  * @description Retrieves a paginated list of transactions for a specific account based on provided filters.
19
20
  * @param {GetTransactionsFilters} filters - An object containing filters for retrieving transactions, such as account address, block range, pagination, and sort order.
20
- * @returns {Promise<Transaction[]>} A Promise that resolves with transactions objects.
21
+ * @returns {Promise<JSONTransaction[]>} A Promise that resolves with transactions objects.
21
22
  */
22
- getTransactions(address: Address, params: GetTransactionsParams): Promise<Transaction[]>;
23
+ getTransactions(address: Address, params: GetTransactionsParams): Promise<JSONTransaction<0>[]>;
23
24
  /**
24
25
  * @method getLastSyncedBlock
25
26
  * @description Retrieves the last synced block number for a given account. This is used to track the synchronization progress of an account's transactions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentaproject/client",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
4
4
  "description": "High level EVM library used into the Menta App to facilitate Blockchain interactions. ",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "scripts": {
24
24
  "test:file": "tsx test.ts",
25
- "test": "jest",
25
+ "test": "jest -i",
26
26
  "build": "tsc --project tsconfig.json",
27
27
  "patch": "npm version patch && npm run build && npm publish --access public",
28
28
  "minor": "npm version minor && npm run build && npm publish --access public",
@@ -31,8 +31,8 @@
31
31
  "author": "@mentaproject",
32
32
  "license": "ISC",
33
33
  "dependencies": {
34
- "@mentaproject/contracts": "^0.0.9",
35
- "@mentaproject/core": "^0.5.3",
34
+ "@mentaproject/contracts": "^0.0.11",
35
+ "@mentaproject/core": "^0.5.13",
36
36
  "@modelcontextprotocol/sdk": "^1.13.0",
37
37
  "@shazow/whatsabi": "^0.21.1"
38
38
  },
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @module @mentaproject/client
3
+ * @description This library provides the client-side functionalities for interacting with the Menta blockchain.
4
+ * It includes managers for accounts, blocks, contracts, persistence, and transactions,
5
+ * as well as core data structures and utility types.
6
+ */
7
+
8
+ /**
9
+ * Re-exports all core data structures like MentaClient, Account, Block, and Transaction.
10
+ */
11
+ export * from './structures';
12
+ /**
13
+ * Re-exports all manager classes for interacting with different aspects of the Menta blockchain.
14
+ */
15
+ export * from './managers';
16
+ /**
17
+ * Re-exports the Cache structure for managing cached data.
18
+ */
19
+ export * from './structures/Cache';
20
+
21
+ export * from "./utils/bigint";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @module AccountManager
3
+ */
4
+ import { Address } from "@mentaproject/core/types";
5
+ import { Account } from "../structures/Account";
6
+ import { PersistenceManager } from "./PersistenceManager";
7
+ import { MentaClient } from "../structures";
8
+
9
+ /**
10
+ * Manages blockchain account operations.
11
+ * This class provides methods to interact with accounts,
12
+ * including retrieving and managing them via an RPC client and a persistence manager.
13
+ *
14
+ * @class AccountManager
15
+ */
16
+ export class AccountManager {
17
+ /**
18
+ * Creates an instance of AccountManager.
19
+ *
20
+ * @param {MentaClient} client - The instance of MentaClient used to interact with the blockchain.
21
+ * @param {persistenceManager} persistenceManager - The optional persistence manager to store and retrieve account data.
22
+ */
23
+ constructor(public client: MentaClient, private persistenceManager?: PersistenceManager) { };
24
+
25
+ /**
26
+ * Retrieves an account instance by its blockchain address.
27
+ * @param address - The blockchain address of the account to retrieve.
28
+ * @returns An instance of the `Account` class.
29
+ * @example
30
+ * ```typescript
31
+ * import { MentaClient } from '@mentaproject/client';
32
+ * import { http } from '@mentaproject/core';
33
+ *
34
+ * // Initialize the MentaClient
35
+ * const client = new MentaClient({
36
+ * transport: http('http://rpcurlhere.com'),
37
+ * });
38
+ *
39
+ * // The address of the account to retrieve
40
+ * const accountAddress = '0x1234567890123456789012345678901234567890';
41
+ *
42
+ * // Retrieve the account instance using the account manager from the client
43
+ * const account = client.accounts.get(accountAddress);
44
+ *
45
+ * console.log(account.address); // 0x1234567890123456789012345678901234567890
46
+ * ```
47
+ */
48
+ get(address: Address): Account {
49
+ return new Account(this.client, { address: address }, this.persistenceManager);
50
+ };
51
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @module BlockManager
3
+ */
4
+ import { BlockTag, GetBlockParameters } from "@mentaproject/core/types";
5
+ import { Block } from "../structures/Block";
6
+ import { getBlock } from "@mentaproject/core/actions";
7
+ import { MentaClient } from "../structures";
8
+
9
+ /**
10
+ * Manages blockchain block-related operations, providing methods to interact with and retrieve block data.
11
+ */
12
+ export class BlockManager {
13
+ /**
14
+ * Creates an instance of BlockManager.
15
+ * @param client - The instance of MentaClient used to interact with the blockchain.
16
+ */
17
+ constructor(public client: MentaClient) {};
18
+
19
+ /**
20
+ * Retrieves a block from the blockchain based on the provided parameters.
21
+ * This method uses the underlying RPC client to fetch block data and then
22
+ * encapsulates it within a {@link Block} instance.
23
+ * @param params The parameters for retrieving the block, including block hash, block number, or block tag.
24
+ * @returns A promise that resolves to a {@link Block} instance representing the retrieved block.
25
+ * @example
26
+ * import { http } from '@mentaproject/core';
27
+ * import { mainnet } from '@mentaproject/core/chains';
28
+ * import { MentaClient } from '@mentaproject/client';
29
+ *
30
+ * // Initialize the MentaClient
31
+ * const mentaClient = new MentaClient({ chain: mainnet, transport: http("http://rpcurlhere.com") });
32
+ *
33
+ * async function fetchBlock() {
34
+ * // Retrieve the latest block
35
+ * const latestBlock = await mentaClient.blocks.get({ blockTag: 'latest' });
36
+ * console.log('Latest block number:', latestBlock.number);
37
+ *
38
+ * // Retrieve a specific block by its number
39
+ * if (latestBlock.number) {
40
+ * const specificBlock = await mentaClient.blocks.get({ blockNumber: latestBlock.number - 10n });
41
+ * console.log('Specific block hash:', specificBlock.hash);
42
+ * }
43
+ * }
44
+ *
45
+ * fetchBlock();
46
+ */
47
+ async get(params: GetBlockParameters<boolean, BlockTag>): Promise<Block> {
48
+ const data = await getBlock(this.client.rpc, params);
49
+ return new Block(this.client, data);
50
+ };
51
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @module ContractManager
3
+ */
4
+ import type { AbiItem } from "@mentaproject/core/types";
5
+ import { getContract, GetContractParameters } from "@mentaproject/contracts";
6
+ import { MentaClient } from "../structures";
7
+
8
+ /**
9
+ * Manages smart contract-related operations within the Menta client.
10
+ * This class provides methods to interact with smart contracts deployed on the blockchain,
11
+ * facilitating the retrieval of contract instances for various operations.
12
+ */
13
+ export class ContractManager {
14
+ /**
15
+ * Creates an instance of ContractManager.
16
+ * @description Initializes the ContractManager with a CoreClient instance, which is used for RPC communication.
17
+ * @param client - The instance of MentaClient used to interact with the blockchain.
18
+ */
19
+ constructor(protected client: MentaClient) {};
20
+
21
+ /**
22
+ * Retrieves a contract instance to interact with it.
23
+ * @description This method fetches a contract instance based on the provided parameters, allowing for interaction with its methods and events.
24
+ * @template P The type of the contract retrieval parameters, extending `GetContractParameters` with `AbiItem` array.
25
+ * @param {P} params The parameters for retrieving the contract, including its Application Binary Interface (ABI) and address.
26
+ * @returns {ReturnType<typeof getContract<ReadonlyArray<AbiItem>, P>>} A contract instance that can be used to call contract methods or listen to events.
27
+ * @example
28
+ * import { MentaClient } from '@mentaproject/client';
29
+ * import { http } from '@mentaproject/core';
30
+ *
31
+ * // Initialize the MentaClient with a transport
32
+ * const client = new MentaClient({
33
+ * transport: http('http://rpcurlhere.com'),
34
+ * });
35
+ *
36
+ * // Define the ABI and address for the smart contract
37
+ * const abi = [
38
+ * {
39
+ * "type": "function",
40
+ * "name": "greet",
41
+ * "stateMutability": "view",
42
+ * "inputs": [],
43
+ * "outputs": [{ "name": "", "type": "string" }]
44
+ * }
45
+ * ] as const;
46
+ * const contractAddress = '0x...'; // Replace with your contract address
47
+ *
48
+ * // Retrieve the contract instance
49
+ * const contract = client.contracts.get({
50
+ * abi,
51
+ * address: contractAddress,
52
+ * });
53
+ *
54
+ * // Example of interacting with the contract
55
+ * const greeting = await contract.greet();
56
+ */
57
+ get<P extends GetContractParameters<ReadonlyArray<AbiItem>>>(params: P) {
58
+ return getContract(this.client.rpc, params);
59
+ };
60
+ };
@@ -0,0 +1,59 @@
1
+ import { getBlockNumber } from '@mentaproject/core/actions';
2
+ import { Address } from '@mentaproject/core/types';
3
+
4
+ import { Account } from '../structures/Account';
5
+ import { MentaClient, Transaction } from '../structures';
6
+ import { bigIntMax } from '../utils/bigint';
7
+ import { GetTransactionsParams, IPersistenceAdapter, JSONTransaction } from 'src/types';
8
+
9
+ /**
10
+ * Manages the persistence of data, including transactions, using a specified persistence adapter.
11
+ * It handles fetching data from both local storage and remote sources, and synchronizing them.
12
+ */
13
+ export class PersistenceManager {
14
+ /**
15
+ * Creates an instance of PersistenceManager.
16
+ * @param client - The instance of MentaClient used to interact with the blockchain.
17
+ * @param persistenceAdapter - The adapter responsible for actual data persistence operations.
18
+ */
19
+ constructor(
20
+ private client: MentaClient,
21
+ private persistenceAdapter: IPersistenceAdapter
22
+ ) {}
23
+
24
+ /**
25
+ * Retrieves transactions for a given account, applying a "stale-while-revalidate" strategy.
26
+ * @param params - Parameters for retrieving transactions.
27
+ * @returns A promise that resolves to an array of transactions with associated account information.
28
+ */
29
+ public async getTransactions(address: Address, params: GetTransactionsParams): Promise<JSONTransaction<0>[]> {
30
+ return await this.persistenceAdapter.getTransactions(address, params);
31
+ }
32
+
33
+ /**
34
+ * Synchronizes an account's transactions from the remote source to the local persistence.
35
+ * It fetches new transactions starting from the last synced block and updates the local storage.
36
+ * @param account - The account whose transactions are to be synchronized.
37
+ * @param limit - The maximum number of transactions to fetch.
38
+ * @returns A promise that resolves when the synchronization is complete.
39
+ */
40
+ public async syncTransactions(account: Account, limit: number = 100_000): Promise<void> {
41
+ const lastSyncedBlock = await this.persistenceAdapter.getLastSyncedBlock(account.address);
42
+ const lastBlock = lastSyncedBlock ?? 0n;
43
+
44
+ const fromBlock = lastSyncedBlock ? lastSyncedBlock + 1n : (await getBlockNumber(this.client.rpc));
45
+
46
+ const newTransactions = await account.transactions({
47
+ fromBlock: fromBlock,
48
+ toBlock: lastBlock,
49
+ limit: limit
50
+ }, true)
51
+
52
+ if (newTransactions.length > 0) {
53
+ await this.persistenceAdapter.upsertTransactions(newTransactions);
54
+
55
+ const latestBlock = bigIntMax(...newTransactions.map(t => t.blockNumber || 0n));
56
+ await this.persistenceAdapter.setLastSyncedBlock(account.address, latestBlock);
57
+ }
58
+ }
59
+ }