UNPKG

@chainreactionom/nano-mcp

Version:

NANO cryptocurrency wallet implementation for MCP with comprehensive testing

336 lines (251 loc) 10.4 kB
# NANO Transaction Utilities ## What is NANO? NANO is a revolutionary digital currency designed for instant, fee-less transactions with unlimited scalability. Unlike traditional cryptocurrencies, NANO uses a unique block-lattice architecture where each account has its own blockchain, enabling near-instantaneous transactions and infinite scalability. ### Configuration The library requires proper configuration before use. There are three required parameters that must be set: 1. `NANO_RPC_URL` - The URL of your NANO RPC server (default: https://rpc.nano.to/) 2. `NANO_RPC_KEY` - Your RPC authentication key (get a free key from [nano.to](https://rpc.nano.to/)) 3. `NANO_GPU_KEY` - Your GPU service key for work generation #### Getting Your API Keys 1. **RPC API Key**: - Visit [rpc.nano.to](https://rpc.nano.to/) - This is a high-performance public enterprise node (RPC) for the Nano blockchain - Get your free RPC API key for development and testing - The service is optimized for high-throughput and reliability Optional parameters: - `NANO_DEFAULT_REPRESENTATIVE` - The default representative for new accounts (defaults to `nano_3arg3asgtigae3xckabaaewkx3bzsh7nwz7jkmjos79ihyaxwphhm6qgjps4` if not set) #### Choosing a Representative The representative you choose helps secure and decentralize the NANO network. To choose a good representative: 1. Visit [NANO Representatives List](https://nanexplorer.com/nano/representatives) 2. Look for representatives with: - High uptime (reliability) - Reasonable voting weight (not too concentrated) - Good performance metrics 3. Copy the representative's address and use it in your configuration A well-chosen representative contributes to: - Network decentralization - Better security - Faster consensus - Overall network health You can configure the library in two ways: #### 1. Environment Variables ```bash # Create a .env file in your project root cp .env.example .env # Edit the .env file with your configuration NANO_RPC_URL=https://rpc.nano.to/ # Required: Default public RPC node NANO_RPC_KEY=your-rpc-key-here # Required: Get from https://rpc.nano.to/ NANO_GPU_KEY=your-gpu-key-here # Required # Choose your representative from https://nanexplorer.com/nano/representatives NANO_DEFAULT_REPRESENTATIVE=nano_3arg3asgtigae3xckabaaewkx3bzsh7nwz7jkmjos79ihyaxwphhm6qgjps4 # Optional ``` #### 2. Programmatic Configuration ```typescript import { NanoMCP } from '@chainreactionom/nano-mcp-server'; // Initialize with custom configuration const mcp = await NanoMCP.initialize({ rpcUrl: 'https://rpc.nano.to/', rpcKey: 'your-rpc-key', gpuKey: 'your-gpu-key', defaultRepresentative: 'your-representative-address' // Optional }); // The initialize method will validate the configuration // If validation fails, it will throw an error with details ``` ### Configuration Validation The library performs strict validation of the configuration: - Required parameters must be set - RPC URL must be a valid URL format - Configuration must be initialized before using the library - Warnings are issued for optional parameters using defaults If validation fails, you'll receive detailed error messages: ```typescript try { const mcp = await NanoMCP.initialize(); } catch (error) { console.error('Configuration validation failed:', error.message); // Example error message: // Configuration validation failed: // Errors: // - NANO_RPC_KEY is required but not set // - NANO_GPU_KEY is required but not set // Warnings: // - Using default representative address } ``` ### Why NANO is Ideal for Agentic Transactions 1. **Instant Finality**: - Transactions complete in less than 1 second - Perfect for real-time agent-to-agent interactions - No waiting for multiple block confirmations like Bitcoin (10+ minutes) 2. **Zero Fees**: - Completely fee-less transactions - Agents can perform unlimited micro-transactions without cost - Enables efficient resource allocation and micro-payments 3. **Energy Efficiency**: - Uses minimal energy compared to Proof-of-Work chains - Environmentally sustainable for large-scale agent networks - ~0.000112 kWh per transaction vs Bitcoin's 707 kWh 4. **Scalability**: - Block-lattice architecture allows parallel processing - Each account has its own blockchain - Perfect for large-scale agent networks with millions of transactions 5. **Deterministic Finality**: - No need for probabilistic confirmation - Agents can be certain of transaction status immediately - Enables reliable decision-making in agent systems 6. **Simple Integration**: - Straightforward API for basic operations - No complex smart contract overhead - Ideal for focused agent-to-agent value transfer This package provides a comprehensive set of utilities for handling NANO cryptocurrency transactions, enabling seamless integration into agent-based systems. ## Features - Work generation with multiple fallback services - Account information retrieval - Pending blocks management - Block creation and processing: - Opening blocks - Receive blocks - Send blocks - Transaction utilities: - Send NANO - Receive pending transactions - Balance conversion ## Installation ```bash npm install nanocurrency nanocurrency-web node-fetch ``` ## Usage ### Basic Setup ```typescript import { NanoTransactions } from './utils/nano-transactions'; const nano = new NanoTransactions({ apiUrl: 'https://rpc.nano.to/', // Your RPC node URL rpcKey: 'your-rpc-key', // Optional: Your RPC authentication key gpuKey: 'your-gpu-key' // Optional: Your GPU service key for work generation }); ``` ### Generate Work ```typescript const hash = '000000000000000000000000000000000000000000000000000000000000000A'; const work = await nano.generateWork(hash); console.log('Generated work:', work); ``` ### Get Account Information ```typescript const account = 'nano_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3'; const info = await nano.getAccountInfo(account); console.log('Account info:', info); ``` ### Send NANO ```typescript const fromAddress = 'your-source-address'; const privateKey = 'your-private-key'; const toAddress = 'destination-address'; const amount = '0.00001'; // First get account info const accountInfo = await nano.getAccountInfo(fromAddress); if (accountInfo.error) { throw new Error(`Failed to get account info: ${accountInfo.error}`); } const result = await nano.createSendBlock(fromAddress, privateKey, toAddress, amount, accountInfo); console.log('Send transaction result:', result); ``` ### Receive Pending Transactions ```typescript const address = 'your-address'; const privateKey = 'your-private-key'; const result = await nano.receiveAllPending(address, privateKey); console.log('Receive transaction result:', result); ``` ## Testing To run the tests: ```bash # Set up environment variables export RPC_KEY=your-rpc-key export GPU_KEY=your-gpu-key export TEST_ADDRESS=your-test-address export TEST_PRIVATE_KEY=your-test-private-key export TEST_SOURCE_BLOCK=source-block-hash export TEST_SOURCE_AMOUNT=0.0001 export SOURCE_ADDRESS=your-source-address export SOURCE_PRIVATE_KEY=your-source-private-key export RECEIVE_ADDRESS=your-receive-address export RECEIVE_PRIVATE_KEY=your-receive-private-key # Run specific tests export TEST_OPEN=true # Test opening blocks export TEST_SEND=true # Test send transactions export TEST_RECEIVE=true # Test receive transactions # Run the test suite node test-nano-utils.js ``` ## Security Considerations - Never share your private keys - Always validate addresses before sending transactions - Use secure RPC nodes - Implement proper error handling - Consider using environment variables for sensitive data ## Error Handling The utilities include comprehensive error handling: - Invalid addresses - Insufficient balance - Network errors - Invalid private keys - Block processing failures Each function returns detailed error information when something goes wrong. ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. # NANO MCP Implementation This is a NANO cryptocurrency wallet implementation for MCP that includes a comprehensive test scenario. ## Test Scenario The test scenario demonstrates the following workflow: 1. **Wallet Creation and Validation** - Creates a first wallet - Validates the key pair - Displays wallet address and QR code for receiving funds 2. **Fund Reception** - Waits for 4 minutes for funds to be received - Checks balance every 10 seconds - Processes pending transactions when detected - Verifies successful fund reception 3. **Second Wallet Creation** - Creates a second wallet - Validates the key pair - Prepares for fund transfer 4. **Fund Transfer Test** - Sends all funds from Wallet 1 to Wallet 2 - Waits for transaction processing - Verifies successful reception in Wallet 2 5. **Return Transfer Test** - Sends all funds back from Wallet 2 to Wallet 1 - Waits for transaction processing - Verifies final balances ## Implementation Details - Uses `nanocurrency-web` for cryptographic operations - Connects to NANO RPC node at rpc.nano.to - Includes proper error handling and logging - Validates all key pairs and transactions - Handles both send and receive operations ## Running the Test ```bash # Install dependencies npm install # Run the test npm start ``` ## Test Flow 1. The test will generate a new wallet and display its address 2. Send exactly 0.00001 NANO to the displayed address 3. The test will automatically: - Monitor for incoming funds - Create a second wallet - Transfer funds between wallets - Verify all transactions ## Error Handling The test includes comprehensive error handling for: - Network issues - Transaction failures - Invalid states - Timeout conditions ## Logging All operations are logged with timestamps and full details in the `logs` directory.