2a854aea5b87c8508acf9ae3064de7771f107c53
Add missing LoggerComponent import that was causing ReferenceError when trying to use logger in start() method
libp2p-native-bridge
Native libp2p bridge for React Native applications, providing a unified interface for iOS and Android libp2p implementations.
Installation
Via IOR (Interoperable Object Reference)
import { Libp2pComponent } from 'ior:gitea:gitea.metatrom.net:universal-components/libp2p-native-bridge@1.0.0';
Via npm/yarn (if published)
npm install @metatrom/libp2p-native-bridge
# or
yarn add @metatrom/libp2p-native-bridge
Features
- 🌐 Unified libp2p interface for React Native
- 📱 iOS and Android native module support
- 🔧 Configurable settings management
- 🎛️ Settings UI component
- 🔌 Protocol handler support
- 🔍 Peer discovery and connection management with configurable TTL
- 🚀 TypeScript support with self-contained type definitions for IOR compatibility
Usage
Basic Setup
import { Libp2pComponent } from '@metatrom/libp2p-native-bridge';
// Create libp2p instance
const libp2p = new Libp2pComponent({
config: {
tcpPort: 10000,
wsPort: 10005,
},
protocols: [
{
protocolId: '/my-protocol/1.0.0',
handler: async ({ peerId, data }) => {
console.log(`Received data from ${peerId}:`, data);
},
},
],
});
// Start the node
await libp2p.start();
// Listen for peer discovery
libp2p.addEventListener('peer:discovery', (evt) => {
console.log('Discovered peer:', evt.detail.id.toString());
});
// Connect to a peer
await libp2p.dial('/ip4/192.168.1.2/tcp/10000/p2p/12D3KooW...');
Using with React Hook
import { useLibp2p } from './hooks/useLibp2p';
import { Libp2pComponent } from '@metatrom/libp2p-native-bridge';
function MyComponent() {
const { isStarted, peerId, discoveredPeers, start, stop } = useLibp2p({
config: {
tcpPort: 10000,
wsPort: 10005,
},
});
return (
<View>
<Text>Status: {isStarted ? 'Started' : 'Stopped'}</Text>
<Text>Peer ID: {peerId?.toString()}</Text>
<Button title="Start" onPress={start} />
<Button title="Stop" onPress={stop} />
</View>
);
}
Settings Management
import { getSettingsService, SettingsUI } from '@metatrom/libp2p-native-bridge';
// Get settings service instance
const settingsService = getSettingsService();
// Load settings
const settings = await settingsService.loadSettings();
// Update settings
await settingsService.updateSetting('tcpPort', 10100);
// Use the Settings UI component
<SettingsUI
initialSettings={settings}
onSettingsChange={(newSettings) => {
console.log('Settings changed:', newSettings);
}}
/>
API Reference
Libp2pComponent
Main class for interacting with the native libp2p implementation.
Constructor Options
interface Libp2pOptions {
config?: {
tcpPort?: number; // Default: 10000
wsPort?: number; // Default: 10005
};
protocols?: ProtocolHandler[];
keypair?: {
privateKey: Uint8Array;
publicKey: Uint8Array;
};
}
Methods
start(): Start the libp2p nodestop(): Stop the libp2p nodedial(multiaddr: string): Connect to a peerhangUp(peerId: string): Disconnect from a peergetConnections(peerId?: string): Get active connectionssendProtocolData(peerId: string, protocolId: string, data: Uint8Array): Send data via protocolrefreshDiscovery(): Refresh peer discoverypingPeer(peerId: string): Ping a peer
Events
peer:discovery: New peer discoveredpeer:lost: Peer lostpeer:connect: Peer connectedpeer:disconnect: Peer disconnectedconnection:open: Connection openedconnection:close: Connection closedself:peer:update: Own peer info updated
SettingsService
Singleton service for managing application settings.
Methods
getInstance(): Get singleton instanceinitialize(): Initialize settingsloadSettings(): Load settings from storagesaveSettings(settings): Save settingsgetSettings(): Get current settingsupdateSetting(key, value): Update specific settingresetAllData(): Reset all application data
Native Module Requirements
This package requires the following native modules to be implemented in your React Native project:
iOS
Libp2pModule: Swift implementation of libp2pDiscoveryModule: mDNS/Bonjour discoverySecureStorageModule: Keychain storage (optional)
Android
Libp2pModule: Kotlin implementation of libp2pDiscoveryModule: Network Service DiscoverySecureStorageModule: Keystore storage (optional)
Configuration
Default Settings
{
tcpPort: 10000,
wsPort: 10005,
discoveryTimeout: 30000, // Discovery TTL in milliseconds (30 seconds)
enableDebugLogs: false,
autoDiscovery: false,
useCustomPorts: false,
dhtServerUrl: 'ws://192.168.188.40:3000/ws'
}
Discovery TTL (Time To Live)
The discoveryTimeout setting controls how long the peer discovery process runs before timing out. This acts as a TTL (Time To Live) for discovery operations:
- Default: 30000ms (30 seconds)
- Minimum: 5000ms (5 seconds)
- Maximum: 300000ms (5 minutes)
- Can be configured via SettingsUI or programmatically through SettingsService
Platform Considerations
iOS
- Uses Swift libp2p packages
- Native Bonjour/mDNS discovery
- Compile-time protocol registration
Android
- Uses Kotlin with JVM libp2p
- Network Service Discovery (NSD)
- Dynamic protocol registration
Recent Updates
TypeScript Declarations
- Self-contained type definitions for improved IOR (Interoperable Object Reference) compatibility
- All types are now bundled directly in the package for better type generation support
Discovery TTL Configuration
- Added configurable TTL for peer discovery operations via
discoveryTimeoutsetting - Improved discovery lifecycle management with timeout controls
Dependencies
Peer Dependencies
react: >=18.0.0react-native: >=0.72.0@react-native-async-storage/async-storage: *
External IOR Dependencies
ior:gitea:gitea.metatrom.net:universal-components/logger@1.0.0
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For issues and questions, please open an issue on the repository.
Description
v1.1.0
Latest
Languages
TypeScript
100%