react-native-nft
v0.1.0
Published
A universal React Native library for NFT operations across multiple blockchains
Maintainers
Readme
react-native-nft
A universal React Native library for NFT operations across multiple blockchains. This library provides a unified interface for working with NFTs across different blockchain networks through pluggable providers.
Features
- Multi-Blockchain Support: Ethereum, Polygon, BSC, Avalanche, Arbitrum, Optimism, Solana, ICP, Flow, Tezos
- Provider Architecture: Pluggable providers for NFT, Wallet, and Marketplace operations
- Unified Interface: Consistent API across all supported blockchains
- NFT Operations: Fetch, transfer, and manage NFTs
- Wallet Integration: Connect wallets and manage connections
- Marketplace Support: Create listings, make offers, and execute trades
- Transaction History: Track NFT transactions and transfers
- Metadata Support: Rich metadata handling with attributes and media
Installation
npm install react-native-nft
# or
yarn add react-native-nftQuick Start
Basic Setup
import { NFTClient, BlockchainNetwork, createNFTClient } from 'react-native-nft';
// Create NFT client
const nftClient = createNFTClient();
// Initialize the client
await nftClient.initialize();Register Providers
import { MyEthereumNFTProvider, MyEthereumWalletProvider } from './providers';
// Register providers
nftClient.registerNFTProvider(new MyEthereumNFTProvider());
nftClient.registerWalletProvider(new MyEthereumWalletProvider());
// Set default providers for networks
nftClient.setDefaultProvider(BlockchainNetwork.ETHEREUM, 'ethereum-provider');Usage Examples
NFT Operations
// Get a specific NFT
const nft = await nftClient.getNFT(
BlockchainNetwork.ETHEREUM,
'0x1234...', // contract address
'123' // token ID
);
console.log(`NFT: ${nft.metadata.name} owned by ${nft.owner}`);
// Get all NFTs owned by an address
const nfts = await nftClient.getNFTs(
BlockchainNetwork.ETHEREUM,
'0xowner...', // owner address
{
limit: 50,
offset: 0,
}
);
console.log(`Found ${nfts.length} NFTs`);Wallet Operations
// Connect wallet
const connection = await nftClient.connectWallet(BlockchainNetwork.ETHEREUM);
console.log(`Connected: ${connection.address}`);
// Transfer NFT
const txHash = await nftClient.transferNFT(
BlockchainNetwork.ETHEREUM,
{
contractAddress: '0x1234...',
tokenId: '123',
to: '0xrecipient...',
}
);
console.log(`Transfer transaction: ${txHash}`);Marketplace Operations
// Create a listing
const listing = await nftClient.createListing(
BlockchainNetwork.ETHEREUM,
{
contractAddress: '0x1234...',
tokenId: '123',
price: 1.5, // 1.5 ETH
currency: 'ETH',
duration: 7 * 24 * 60 * 60, // 7 days
}
);
console.log(`Listing created: ${listing.id}`);
// Buy an NFT
const purchaseTx = await nftClient.buyNFT(
BlockchainNetwork.ETHEREUM,
'listing-id-123'
);
console.log(`Purchase transaction: ${purchaseTx}`);Supported Networks
enum BlockchainNetwork {
ETHEREUM = 'ethereum',
POLYGON = 'polygon',
BSC = 'bsc',
AVALANCHE = 'avalanche',
ARBITRUM = 'arbitrum',
OPTIMISM = 'optimism',
SOLANA = 'solana',
ICP = 'icp',
FLOW = 'flow',
TEZOS = 'tezos',
}Provider Interfaces
NFT Provider
interface NFTProvider {
readonly id: string;
readonly name: string;
readonly supportedNetworks: BlockchainNetwork[];
initialize(config?: any): Promise<void>;
dispose(): Promise<void>;
// NFT operations
getNFT(contractAddress: string, tokenId: string): Promise<NFT>;
getNFTs(owner: string, options?: {
contractAddress?: string;
limit?: number;
offset?: number;
}): Promise<NFT[]>;
getNFTMetadata(tokenUri: string): Promise<NFTMetadata>;
// Contract operations
getContractInfo(contractAddress: string): Promise<{
name: string;
symbol: string;
totalSupply?: number;
owner?: string;
}>;
// Transaction operations
getTransactionHistory(options: {
contractAddress?: string;
tokenId?: string;
owner?: string;
limit?: number;
}): Promise<NFTTransaction[]>;
}Wallet Provider
interface WalletProvider {
readonly id: string;
readonly name: string;
readonly supportedNetworks: BlockchainNetwork[];
initialize(config?: any): Promise<void>;
dispose(): Promise<void>;
// Connection operations
connect(): Promise<WalletConnection>;
disconnect(): Promise<void>;
isConnected(): Promise<boolean>;
getConnection(): Promise<WalletConnection | null>;
// Balance operations
getBalance(address?: string): Promise<number>;
// Transaction operations
transferNFT(params: {
contractAddress: string;
tokenId: string;
to: string;
from?: string;
}): Promise<string>;
approveNFT(params: {
contractAddress: string;
tokenId: string;
spender: string;
}): Promise<string>;
}Marketplace Provider
interface MarketplaceProvider {
readonly id: string;
readonly name: string;
readonly supportedNetworks: BlockchainNetwork[];
initialize(config?: any): Promise<void>;
dispose(): Promise<void>;
// Listing operations
createListing(params: {
contractAddress: string;
tokenId: string;
price: number;
currency: string;
duration?: number;
}): Promise<NFTListing>;
cancelListing(listingId: string): Promise<void>;
updateListing(listingId: string, params: {
price?: number;
duration?: number;
}): Promise<NFTListing>;
getListings(options?: {
contractAddress?: string;
seller?: string;
status?: string;
limit?: number;
offset?: number;
}): Promise<NFTListing[]>;
// Offer operations
createOffer(params: {
contractAddress: string;
tokenId: string;
amount: number;
currency: string;
duration?: number;
}): Promise<NFTOffer>;
cancelOffer(offerId: string): Promise<void>;
acceptOffer(offerId: string): Promise<string>;
// Purchase operations
buyNFT(listingId: string): Promise<string>;
}Data Types
NFT
interface NFT {
id: string;
tokenId: string;
contractAddress: string;
network: BlockchainNetwork;
owner: string;
creator?: string;
metadata: NFTMetadata;
tokenUri?: string;
mintedAt?: number;
lastTransferredAt?: number;
}NFT Metadata
interface NFTMetadata {
name: string;
description?: string;
image?: string;
external_url?: string;
attributes?: Array<{
trait_type: string;
value: string | number;
display_type?: string;
}>;
animation_url?: string;
background_color?: string;
[key: string]: any;
}NFT Listing
interface NFTListing {
id: string;
nft: NFT;
price: number;
currency: string;
seller: string;
marketplace: string;
status: 'active' | 'sold' | 'cancelled' | 'expired';
createdAt: number;
updatedAt: number;
expiresAt?: number;
}NFT Offer
interface NFTOffer {
id: string;
nft: NFT;
amount: number;
currency: string;
buyer: string;
seller?: string;
status: 'pending' | 'accepted' | 'rejected' | 'expired' | 'cancelled';
createdAt: number;
updatedAt: number;
expiresAt: number;
}Error Handling
import {
NFTException,
NFTNetworkException,
NFTProviderException,
NFTNotSupportedException,
NFTContractException,
} from 'react-native-nft';
try {
const nft = await nftClient.getNFT(network, contractAddress, tokenId);
} catch (error) {
if (error instanceof NFTProviderException) {
console.error('Provider error:', error.message);
} else if (error instanceof NFTNetworkException) {
console.error('Network error:', error.message);
} else if (error instanceof NFTContractException) {
console.error('Contract error:', error.message);
}
}Creating Custom Providers
Example NFT Provider
import { NFTProvider, BlockchainNetwork, NFT, NFTMetadata } from 'react-native-nft';
class MyCustomNFTProvider implements NFTProvider {
readonly id = 'my-custom-provider';
readonly name = 'My Custom NFT Provider';
readonly supportedNetworks = [BlockchainNetwork.ETHEREUM];
async initialize(config?: any): Promise<void> {
// Initialize your provider
}
async dispose(): Promise<void> {
// Cleanup resources
}
async getNFT(contractAddress: string, tokenId: string): Promise<NFT> {
// Implement NFT fetching logic
return {
id: `${contractAddress}-${tokenId}`,
tokenId,
contractAddress,
network: BlockchainNetwork.ETHEREUM,
owner: '0x...',
metadata: {
name: 'My NFT',
description: 'A custom NFT',
image: 'https://...',
},
};
}
// Implement other required methods...
}
// Register the provider
nftClient.registerNFTProvider(new MyCustomNFTProvider());Best Practices
- Provider Management: Register all needed providers before initializing the client
- Network Support: Check if a network is supported before making operations
- Error Handling: Always wrap NFT operations in try-catch blocks
- Resource Cleanup: Call dispose() when done with the client
- Provider Configuration: Configure providers with appropriate API keys and endpoints
Network Utilities
// Check supported networks
const supportedNetworks = nftClient.getSupportedNetworks();
console.log('Supported networks:', Array.from(supportedNetworks));
// Check if a network is supported
const isSupported = nftClient.isNetworkSupported(BlockchainNetwork.ETHEREUM);
console.log('Ethereum supported:', isSupported);
// Get provider statistics
const stats = nftClient.getProviderStats();
console.log('Provider stats:', stats);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.
