@mentaproject/client
v0.2.2
Published
High level EVM library used into the Menta App to facilitate Blockchain interactions.
Downloads
1,578
Readme
@mentaproject/client
@mentaproject/client is the main client of the Menta App used for interacting with Ethereum ecosystem. It provides a high-level interface to simplify interactions with the blockchain, encapsulating the complexity of the underlying protocols. The client offers specialized managers for blocks, transactions, smart contracts, and accounts, allowing for complete and intuitive management of operations on the blockchain. It is originally developed for the Menta App to reduce the codebase complexity, but can be used for any EVM like based application.
The central class of this package is MentaClient, which serves as the entry point for all functionalities.
Installation
You can install the client using npm:
npm install @mentaproject/clientClient Initialization
To start using the client, you must first create an instance of it. The MentaClient constructor takes a configuration object that specifies how to connect to your RPC node.
Here is a basic initialization example:
import { MentaClient } from '@mentaproject/client';
import { http } from '@mentaproject/core';
import { mainnet } from '@mentaproject/core/chains';
// Simple initialization with the RPC node URL
const client = new MentaClient({
chain: mainnet,
transport: http('http://rpcurlhere.com'),
});The client can also be configured with more advanced features, such as a cache to optimize repeated requests:
import { MentaClient } from '@mentaproject/client';
import { http } from '@mentaproject/core';
import { mainnet } from '@mentaproject/core/chains';
// Initialization with a cache (TTL of 1 minute)
const clientWithCache = new MentaClient({
chain: mainnet,
transport: http('http://rpcurlhere.com'),
cache: {
ttl: 60000, // 1 minute
},
});Account Management
Account management is handled by AccountManager, accessible via client.accounts. This manager primarily allows retrieving instances of existing accounts.
Note: The current API does not provide a method for creating a new account (e.g., generating a new key pair). You must use an existing account.
To get an instance of an account via its address:
import { MentaClient } from '@mentaproject/client';
import { http } from '@mentaproject/core';
import { mainnet } from '@mentaproject/core/chains';
const client = new MentaClient({
chain: mainnet,
transport: http('http://rpcurlhere.com')
});
// Address of the account to retrieve
const accountAddress = '0x1234567890123456789012345678901234567890';
// Retrieve the account instance
const account = client.accounts.get(accountAddress);
console.log(account.address); // Displays the account addressBasic Operations
Once you have an account instance, you can perform basic operations like checking the balance or sending transactions.
Get Account Balance
To get the balance of an account, you can use the getBalance() method on an Account instance.
import { MentaClient } from '@mentaproject/client';
import { http } from '@mentaproject/core';
import { mainnet } from '@mentaproject/core/chains';
async function getAccountBalance(client: MentaClient, accountAddress: string) {
try {
const account = client.accounts.get(accountAddress);
const balance = await account.getBalance();
console.log(`Balance of account ${account.address}: ${balance}`);
return balance;
} catch (error) {
console.error("Error getting balance:", error);
}
}
// Usage
const client = new MentaClient({ chain: mainnet, transport: http('http://rpcurlhere.com') });
const myAddress = '0x123...'; // Replace with an account address
getAccountBalance(client, myAddress);Send a Transaction
To send a transaction, you can use the sendTransaction method available on the client instance.
const transaction = await client.transactions.send({
from: "0x...", // Sender's address
to: "0x...", // Recipient's address
value: 1000000000000000000n, // 0.1 ETH in wei
// Other fields like 'gas', 'gasPrice', 'data', 'nonce' may be necessary
});
const receipt = await transaction.waitForReceipt();
console.log(`Transaction sent. Hash: ${transaction.hash}`);Interaction with Smart Contracts
Interaction with smart contracts is managed by the ContractManager, accessible via client.contracts. This manager provides the necessary tools to interact with their methods and events.
// Define the ABI and address for the smart contract
const abi = [
{
"type": "function",
"name": "greet",
"stateMutability": "view",
"inputs": [],
"outputs": [{ "name": "", "type": "string" }]
}
] as const; // as const is important !
const contractAddress = '0x...'; // Replace with your contract address
// Retrieve the contract instance
const contract = client.contracts.get({
abi,
address: contractAddress,
});
// Example of interacting with the contract
const greeting = await contract.greet();Persistence System
The client includes an optional persistence system to store retreived transactions locally (Only for account.transactions). Retreiving account's transactions rely on complex trace_filter RPC calls that can be heavy and slow for most usecases, so storing them locally can significantly improve performance.
Configuration
To enable persistence, you must provide an implementation of the IPersistenceAdapter interface when initializing the client.
import { MentaClient, IPersistenceAdapter } from '@mentaproject/client';
import { http } from '@mentaproject/core';
import { mainnet } from '@mentaproject/core/chains';
// Your custom implementation of the persistence adapter
class MyPersistenceAdapter implements IPersistenceAdapter {
// Implement the required methods: getTransactions, upsertTransactions etc...
}
const client = new MentaClient({
chain: mainnet,
transport: http('http://rpcurlhere.com'),
persistenceAdapter: new MyPersistenceAdapter(),
});How it works
When persistence is enabled, the PersistenceManager is used to manage data storage and retrieval. For example, retrieving transaction history follows a "stale-while-revalidate" strategy: data is first read from the local cache (via the adapter), then updated from the network if necessary.
Methods that depend on persistence (like account.tokenTransactions on an account) will throw an error if no persistenceAdapter is configured.
