@first-ledger/nu-client
v1.0.4-b.10
Published
A newly designed and optimized client plugin for interacting with the XRP Ledger.
Readme
[nu.client] - XRP Client with Speed
xrp | xrpl | plugin | http | client | websocket | performance | rate-limiting | throttle | ledger | query-builder
[nu.client] is a newly designed and optimized client for interacting with the XRP Ledger (XRPL). It's tailored to enhance performance for queries and requests, providing a more streamlined and efficient interface for developers working with XRP Ledger.
How does this work?
We enhanced the xrpl.js client by adding an object named
nu. Thisnuobject contains all available RPC methods in an abstracted function call. When you call one of these methods, the client first checks if the WebSocket connection is active and ready for requests. If it is, we use the WebSocket for the interaction. However, if the WebSocket isn't connected, or is in the process of connecting/switching states, the client will automatically fallback to using an HTTP request. This feature ensures seamless operation even during socket transitions or when dealing with connection issues.
Features
[nu.client] brings a suite of features designed to make your interaction with the XRP Ledger (XRPL) more efficient, intuitive, and performant:
Support for Both WebSocket and HTTP Requests
[nu.client]supports both WebSocket connections for real-time data and HTTP requests for more traditional query patterns. This dual support allows for flexibility depending on your application's needs, whether it's for real-time transaction monitoring or batch data retrieval.Built-in Rate Limiting and Throttling To address issues with infrastructure providers who have decided to imposed strict limits and degraded service for public requests,
[nu.client]includes configurable rate limiting parameters and throttling. This helps manage the frequency of requests, ensuring your application doesn't overwhelm the XRPL nodes and respects any imposed limitations, thereby maintaining a stable and predictable performance.Simplified Request Methods The client provides a streamlined API for making requests to XRPL, abstracting away the complexities of constructing and sending requests. With methods like
client.nu.server_info(), you can fetch data with minimal boilerplate code.Caching
[nu.client]includes built-in caching mechanisms to reduce unnecessary network calls. This feature helps in speeding up repeated queries by storing the results in memory, thus improving response times for subsequent similar requests.Query with State Management
[nu.client]introduces an advanced state management system for queries. This allows for: - Query Lifecycle Management: Easily manage the lifecycle of queries with built-in support for states like loading, success, error, and idle, making it simpler to handle UI states in applications. - Subscription to State Changes: You can subscribe to state changes of a query, which is particularly useful in UI frameworks where you might want to react to data changes without polling.
Getting Started
Installation
To use [nu.client] in your project, you'll need to install it via npm or yarn:
npm install nu-clientor
yarn add nu-clientQuick Start
After installation, you can import and start using [nu.client]:
import * as nu from 'nu-client';
const run = async () => {
const client = new nu.client({
ws: 'wss://honeycluster.dev',
http: 'https://honeycluster.dev',
});
await client.connect();
const serverInfo = await client.nu.server_info({});
console.log(serverInfo);
await client.disconnect();
};Configuration Options
interface nuConfigs = {
/* === General Nu Parameters === */
// Manadate a particular request protocol, Default: null
mandate: 'websocket' | 'http' | null;
// Enable caching requests, Default: true
caching: boolean;
// Time when cached data becomes stale in milliseconds, Default: 300000
staleTime: number;
// Time between requests in milliseconds, Default: -1 (Disabled)
rateLimitMs: number;
// Number of requests per second. Default: 0 (Disabled)
throttle: number;
// Log messages to console for debugging, Default: false
verbose: boolean;
/* === Manager Only Parameters === */
// If you need network switching and auto-reconnect features, you can try out the client manager
// Whether the manger should autoconnect, Default: false
autoConnect: boolean;
// Whether the manger should retry connection if error, Default: false
autoRetry: boolean;
// Maximum number of retrys before gracefully disconnecting and ending service, Default: 0
maxRetryAttempts: number;
}Examples
For more in-depth examples on how to use [nu.client], check out our examples directory. Here you'll find various scenarios from basic usage to complex queries:
- Basic Connection: Demonstrates how to connect to the XRP Ledger.
- Query Examples: Shows different types of queries you can perform.
- Transaction Handling: Examples on how to manage transactions.
Plugin for XRPL.js
[nu.client] includes a plugin that allows you to use existing xrpl.js implementations with enhanced capabilities. Here's how to apply the plugin to an existing XRPL client:
import * as xrpl from 'xrpl';
import * as nu from 'nu-client';
const pluginConfig = {
mandate: null, // Support both http and websocket requests
caching: true, // Enable caching requests by id
staleTime: 1000 * 60 * 10, // 10 minutes
rateLimitMs: 200, // Queue all requests and delay 200ms between requests
throttle: 10, // Limit to 10 request per second and delay if limit is hit
verbose: true, // Enable debugging messaging
};
const run = async () => {
const xrpljs = new xrpl.Client('wss://honeycluster.dev');
const client = nu.plugin(
xrpljs,
{
ws: 'wss://honeycluster.dev',
http: 'https://honeycluster.dev',
},
pluginConfig
);
// Demonstration using nu (before client socket is connected)
let serverInfo = await client.nu.server_info({});
console.log(serverInfo);
// The plugin maintains everything from xrpljs and doesnt modify the underlying package
// Continue to use xrpl.js within your codebase as normal
await client.connect();
serverInfo = await client.request({
command: 'server_info',
});
console.log(serverInfo);
await client.disconnect();
};import * as nu from 'nu-client';
const managerConfig = {
mandate: null, // Support both http and websocket requests
caching: true, // Enable caching requests by id
staleTime: 1000 * 60 * 10, // 10 minutes
rateLimitMs: 200, // Queue all requests and delay 200ms between requests
throttle: 10, // Limit to 10 request per second and delay if limit is hit
verbose: true, // Enable debugging messaging
autoConnect: true, // No need to call connect, will autoconnect
autoRetry: true, // Retry connection if disconnects
maxRetryAttempts: 3, // 3 retries before shutdown
};
const run = async () => {
const manager = new nu.Manager({
// Array of ws/http providers for auto rotation
provider: [
{
ws: 'wss://honeycluster.dev',
http: 'https://honeycluster.dev',
},
],
// nu manager options
config: managerConfig,
// xrpljs options
options: {
feeCushion: 1.2,
maxFeeXRP: '2',
timeout: 1000,
},
});
await manager.connect();
let serverInfo = await manager.client?.nu.server_info({});
console.log(serverInfo);
await manager.switch({
id: 'next',
ws: 'wss://honeycluster.dev',
http: 'https://honeycluster.dev',
autoConnect: true,
});
await manager.connect();
serverInfo = await manager.client?.nu.server_info({});
console.log(serverInfo);
await manager.terminate();
};Speed off the line
This plugin enhances your existing XRPL.js client with [nu.client]'s optimized methods, making your XRPL interactions more efficient without needing to rewrite your codebase.
Speed Comparison
[nu.client] has been designed for speed during initial requests. Here's a basic comparison script to illustrate the performance benefits:
import * as nu from 'nu-client';
const original = async () => {
let client = new nu.client({
ws: 'wss://honeycluster.dev',
http: 'https://honeycluster.dev',
});
await client.connect();
let server_info = await client.request({
command: 'server_info',
});
await client.disconnect();
};
const nu = async () => {
let client = new nu.client({
ws: 'wss://honeycluster.dev',
http: 'https://honeycluster.dev',
});
let server_info = await client.nu.server_info({});
};
// nu.client compared to started xrpl.js client
// Query take advantage of http requests when the socket while in connecting/switching state
// Time Saved: 0.250sThis script compares the time taken for a simple server_info request using the traditional method versus using [nu.client]'s optimized nu.server_info method. The difference in execution time can give you an idea of the performance gains [nu.client] offers.
Please note that results can vary based on network conditions, server load, and other factors, so consider running this test multiple times or in different environments for more accurate comparisons.
Contributors
Contributing
We welcome contributions to [nu.client]! See our CONTRIBUTING.md for guidelines on how to get started.
For bug reports, feature requests, or questions, please open an issue on the GitHub repository. We appreciate your feedback and collaboration in making [nu.client] better!
Disclaimer
[nu.client] is provided as-is, with no warranties or guarantees of performance, reliability, or suitability for any particular purpose. While we strive to ensure it works seamlessly with the XRP Ledger, users should test and validate its functionality in their specific environments. The developers are not liable for any damages, losses, or issues arising from its use. Always ensure compliance with XRPL infrastructure providers’ terms of service and rate limits when using this client.
License
[nu.client] is licensed under the MIT License. You are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, provided that the copyright notice and permission notice are included in all copies or substantial portions of the software. See the LICENSE file in the repository for full details.

