react-native-icp
v0.1.0
Published
React Native library for Internet Computer Protocol (ICP) blockchain operations
Maintainers
Readme
react-native-icp
React Native library for Internet Computer Protocol (ICP) blockchain operations. This library provides comprehensive ICP blockchain functionality including wallet operations, canister interactions, and transaction management.
Features
- ICP Client: Singleton client for managing ICP connections
- Canister Operations: Query and update calls to ICP canisters
- Wallet Integration: Balance checking and token transfers
- Transaction History: Retrieve and manage transaction records
- Caching: Built-in caching system for improved performance
- Error Handling: Comprehensive error types for different scenarios
- Network Connectivity: Automatic network connectivity testing
Installation
npm install react-native-icp
# or
yarn add react-native-icpQuick Start
Basic Setup
import { initializeICP, ICPClient, ICPConfig } from 'react-native-icp';
const config: ICPConfig = {
networkUrl: 'https://ic0.app',
canisterIds: {
ledger: 'rrkah-fqaaa-aaaaa-aaaaq-cai',
},
enableCaching: true,
debugLogging: true,
};
// Initialize the client
const client = await initializeICP(config);Alternative Initialization
import { createICPClient } from 'react-native-icp';
const client = createICPClient();
await client.initialize(config);Usage Examples
Balance Operations
// Get account balance
const balance = await client.getBalance('account-id-here');
console.log(`Balance: ${balance} ICP`);
// Transfer tokens
const txId = await client.transfer({
to: 'recipient-account-id',
amount: 1.5, // 1.5 ICP
memo: 'Payment for services',
});
console.log(`Transfer completed: ${txId}`);Canister Interactions
// Query call (read-only)
const result = await client.query({
canisterId: 'your-canister-id',
method: 'get_data',
args: { key: 'some-key' },
});
// Update call (state-changing)
const updateResult = await client.update({
canisterId: 'your-canister-id',
method: 'set_data',
args: { key: 'some-key', value: 'some-value' },
options: {
sender: 'your-principal-id',
},
});Transaction History
// Get transaction history
const transactions = await client.getTransactionHistory('account-id', 50);
transactions.forEach(tx => {
console.log(`Transaction ${tx.id}: ${tx.from} -> ${tx.to} (${tx.amount} ICP)`);
});Canister Information
// Get canister status and info
const canisterInfo = await client.getCanisterInfo('canister-id');
console.log('Canister info:', canisterInfo);Cache Management
// Clear cache
client.clearCache();
// Get cache statistics
const cacheStats = client.getCacheStats();
console.log('Cache entries:', cacheStats.entries);
console.log('Cache enabled:', cacheStats.enabled);
// Get client statistics
const stats = client.getStats();
console.log('Client stats:', stats);Configuration Options
interface ICPConfig {
networkUrl: string; // ICP network URL
canisterIds?: { [key: string]: string }; // Named canister IDs
requestTimeout?: number; // Request timeout in ms (default: 30000)
enableCaching?: boolean; // Enable response caching (default: true)
cacheTtl?: number; // Cache TTL in seconds (default: 300)
debugLogging?: boolean; // Enable debug logging (default: false)
customHeaders?: { [key: string]: string }; // Custom HTTP headers
}Error Handling
The library provides comprehensive error types:
import {
ICPException,
ICPNetworkException,
ICPConfigurationException,
ICPQueryException,
ICPUpdateException,
ICPTimeoutException,
ICPTransactionException,
ICPServiceNotInitializedException,
ICPServiceAlreadyInitializedException,
} from 'react-native-icp';
try {
const balance = await client.getBalance('account-id');
} catch (error) {
if (error instanceof ICPNetworkException) {
console.error('Network error:', error.message);
} else if (error instanceof ICPTimeoutException) {
console.error('Request timed out:', error.message);
} else if (error instanceof ICPException) {
console.error('ICP error:', error.message);
}
}Types
Core Interfaces
interface ICPAccount {
accountId: string;
balance: number;
publicKey?: string;
}
interface ICPTransaction {
id: string;
from: string;
to: string;
amount: number;
timestamp: number;
memo?: string;
status: 'pending' | 'completed' | 'failed';
}
interface ICPNft {
id: string;
canisterId: string;
tokenId: string;
owner: string;
metadata: {
name: string;
description?: string;
image?: string;
attributes?: { [key: string]: any };
};
}Best Practices
- Initialize Once: Use the singleton pattern to initialize the client once in your app
- Error Handling: Always wrap ICP operations in try-catch blocks
- Caching: Enable caching for better performance, especially for read operations
- Timeouts: Configure appropriate timeouts based on your network conditions
- Logging: Enable debug logging during development
Network Configuration
Mainnet
const mainnetConfig: ICPConfig = {
networkUrl: 'https://ic0.app',
canisterIds: {
ledger: 'rrkah-fqaaa-aaaaa-aaaaq-cai',
},
};Local Development
const localConfig: ICPConfig = {
networkUrl: 'http://localhost:8000',
canisterIds: {
ledger: 'rrkah-fqaaa-aaaaa-aaaaq-cai',
},
debugLogging: true,
};Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support, please open an issue on our GitHub repository or contact our team.
