===============
LIBRARY RULES
===============
From library maintainers:
- Use TypeScript with strict type checking
- Follow React 18+ best practices
- Use Ethers.js v6 for Ethereum interactions
- Use Zustand for state management
- Use Tailwind CSS for styling
- Use Radix UI for accessible component primitives
- Support multi-platform environments (Web/Next.js, React Native, Node.js)
- Follow the platform adapter pattern for cross-platform compatibility
### Quick Start Wallet Setup
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Initialize the D-Sports wallet with D-Sports managed OAuth credentials for a quick setup. This is ideal for prototyping, development, and learning.
```typescript
import { createDSportsWalletQuickStart, mainnet, polygon } from '@d-sports/wallet';
// 🎉 ONE LINE SETUP - No OAuth configuration needed!
const wallet = createDSportsWalletQuickStart({
projectId: 'your-project-id',
chains: [mainnet, polygon],
metadata: {
name: 'My Awesome App',
description: 'Built with D-Sports Wallet',
url: 'https://my-app.com',
icons: ['https://my-app.com/icon.png']
}
});
// Connect with social login (Google, Facebook, Twitter, Discord, GitHub ready!)
await wallet.connect({ socialLogin: true });
console.log('🎊 Wallet connected with zero OAuth setup!');
```
--------------------------------
### Quick Start Wallet Initialization
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Initialize the wallet using the quick start configuration for rapid development and testing.
```APIDOC
## Quick Start Wallet Initialization
### Description
Initialize the wallet using the quick start configuration for rapid development and testing.
### Method
```typescript
createDSportsWalletQuickStart
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
const wallet = createDSportsWalletQuickStart({
projectId: 'your-project-id',
chains: [mainnet, polygon]
});
```
### Response
#### Success Response (200)
Wallet instance
#### Response Example
None
```
--------------------------------
### Install @d-sports/wallet
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/comprehensive-api-documentation.md
Install the SDK using npm. This is the first step to integrating wallet functionality into your application.
```bash
npm install @d-sports/wallet
```
--------------------------------
### Clone Repository and Install Dependencies
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Instructions for setting up the development environment by cloning the repository and installing dependencies using bun.
```bash
git clone https://github.com/D-Sports-Ecosystem/wallet.git
cd wallet
bun install
```
--------------------------------
### Start Development Mode with Bun
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Use this command to start the development server and enable hot-reloading for faster iteration.
```sh
bun run dev
```
--------------------------------
### Install @d-sports/wallet
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Install the @d-sports/wallet package using npm, yarn, or bun.
```bash
npm install @d-sports/wallet
# or
yarn add @d-sports/wallet
# or
bun add @d-sports/wallet
```
--------------------------------
### Quick Start Wallet Initialization
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Initializes the D-Sports wallet using the quick start configuration. This is suitable for development and testing purposes.
```typescript
const wallet = createDSportsWalletQuickStart({
projectId: 'your-project-id',
chains: [mainnet, polygon]
});
```
--------------------------------
### React Native Integration
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Example of setting up and connecting the D-Sports Wallet in a React Native application, including URL polyfill setup.
```APIDOC
## React Native Integration
### Description
This snippet shows how to set up the D-Sports Wallet for React Native, including the necessary URL polyfill and mobile-specific deep linking for social logins.
### Code
```typescript
import { createDSportsWallet, setupURLPolyfill } from '@d-sports/wallet/react-native';
setupURLPolyfill();
const wallet = createDSportsWallet({
projectId: 'your-project-id',
chains: [/* your chains */],
socialLogin: {
appSecret: 'your-app-secret',
redirectUri: 'dsports://auth/callback',
providers: {
google: {
clientId: 'your-google-client-id',
},
apple: {
clientId: 'your-apple-client-id',
},
},
},
});
await wallet.connect();
```
```
--------------------------------
### D-Sports OAuth Service - Create Quick Start Social Login
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Generates a configuration object for a quick start social login setup. This is useful for immediate development without manual OAuth app creation.
```typescript
import { DSportsOAuthService, createQuickStartSocialLogin } from '@d-sports/wallet';
const quickStartConfig = createQuickStartSocialLogin();
```
--------------------------------
### Fetch Token Data Example
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Example of how to fetch the latest token data for specified symbols using the TokenService. Ensure the TokenService instance is available.
```typescript
const tokens = await tokenService.fetchTokenData(['BTC', 'ETH']);
console.log(`Bitcoin price: ${tokens[0].price}`);
```
--------------------------------
### React Native Wallet Provider Setup
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/wallet-usage-examples.md
Sets up the wallet provider for a React Native application using `RNWalletProvider`. This example also includes basic navigation setup with React Navigation.
```tsx
// App.tsx
import { RNWalletProvider } from '@d-sports/wallet/react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function App() {
return (
);
}
export default App;
```
--------------------------------
### Web Animation Example
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/animation-system-example.md
Basic web animation example using `motion.div` with initial and animate states. Includes a transition duration.
```tsx
Content
```
--------------------------------
### OAuth Callback Page Example
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Example HTML structure for an OAuth callback page to handle responses.
```APIDOC
## OAuth Callback Page
### Description
This HTML serves as a template for your OAuth callback handler. It listens for messages from the wallet SDK to process authentication results.
### HTML Structure
```html
D-Sports Authentication
🏆
D-Sports Authentication
Processing your login...
```
```
--------------------------------
### Rainbow Kit Integration
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Example of creating a D-Sports Wallet connector for integration with Rainbow Kit.
```APIDOC
## Rainbow Kit Integration
### Description
This snippet demonstrates how to create a D-Sports Wallet connector compatible with Rainbow Kit, allowing seamless integration into Rainbow Kit's UI components.
### Code
```typescript
import { createDSportsRainbowKitConnector } from '@d-sports/wallet';
const connector = createDSportsRainbowKitConnector({
chains: [/* your chains */],
projectId: 'your-project-id',
appName: 'My App',
socialLogin: {
appSecret: 'your-app-secret',
redirectUri: 'https://your-app.com/auth/callback',
providers: {
google: {
clientId: 'your-google-client-id',
},
facebook: {
clientId: 'your-facebook-client-id',
},
},
},
});
const connectors = [
connector,
// ... other connectors
];
```
```
--------------------------------
### Next.js Integration
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Example of how to create and connect a D-Sports Wallet instance in a Next.js application.
```APIDOC
## Next.js Integration
### Description
This snippet demonstrates initializing the D-Sports Wallet for a Next.js environment, including project ID, chains, and social login configurations.
### Code
```typescript
import { createDSportsWallet } from '@d-sports/wallet/nextjs';
const wallet = createDSportsWallet({
projectId: 'your-project-id',
chains: [/* your chains */],
environment: 'production',
socialLogin: {
appSecret: 'your-app-secret',
redirectUri: 'https://your-app.com/auth/callback',
providers: {
google: {
clientId: 'your-google-client-id',
},
facebook: {
clientId: 'your-facebook-app-id',
},
twitter: {
clientId: 'your-twitter-client-id',
},
discord: {
clientId: 'your-discord-client-id',
},
},
},
});
await wallet.connect();
```
```
--------------------------------
### Wagmi Integration
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Example of creating a D-Sports Wallet connector for integration with Wagmi.
```APIDOC
## Wagmi Integration
### Description
This snippet shows how to create a D-Sports Wallet connector that can be used with Wagmi, facilitating wallet management within Wagmi's hooks and utilities.
### Code
```typescript
import { dsportsWagmiConnector } from '@d-sports/wallet';
const connector = dsportsWagmiConnector({
chains: [/* your chains */],
projectId: 'your-project-id',
socialLogin: {
appSecret: 'your-app-secret',
redirectUri: 'https://your-app.com/auth/callback',
providers: {
google: {
clientId: 'your-google-client-id',
},
},
},
});
const connectors = [
connector,
// ... other connectors
];
```
```
--------------------------------
### React Native Dependencies
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
For React Native projects, install react-native-keychain and react-native-url-polyfill.
```bash
npm install react-native-keychain react-native-url-polyfill
```
--------------------------------
### Basic Wallet Connection
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
A fundamental example of creating a D-Sports Wallet instance, connecting to it, and retrieving its state.
```APIDOC
## Basic Wallet Connection
### Description
This example illustrates the basic usage of the D-Sports Wallet SDK, including initialization, connecting to a wallet, checking its state, switching chains, and disconnecting.
### Code
```typescript
import { createDSportsWallet } from '@d-sports/wallet';
const wallet = createDSportsWallet({
projectId: 'your-project-id',
chains: [
{
id: 1,
name: 'Ethereum',
network: 'homestead',
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
rpcUrls: {
default: { http: ['https://mainnet.infura.io/v3/your-key'] },
public: { http: ['https://mainnet.infura.io/v3/your-key'] }
}
}
]
});
const account = await wallet.connect();
console.log('Connected account:', account);
const state = wallet.getState();
console.log('Wallet state:', state);
await wallet.switchChain(137);
await wallet.disconnect();
```
```
--------------------------------
### Web Wallet Integration
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/component-factory-summary.md
Integrates the @d-sports/wallet package for web applications. This example shows setting up the adapter and wallet instance, then using the WalletButton component.
```tsx
import { createDSportsWallet, createWebPlatformAdapter } from '@d-sports/wallet';
const adapter = createWebPlatformAdapter();
const wallet = createDSportsWallet({
appName: 'My App',
adapter
});
const WalletButton = wallet.components.WalletButton;
function ConnectButton() {
return Connect Wallet;
}
```
--------------------------------
### Production Wallet Initialization
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Initializes the D-Sports wallet with a production configuration. This includes environment validation and social login setup.
```typescript
const wallet = createDSportsWallet({
projectId: 'your-project-id',
chains: [mainnet, polygon],
environment: 'production',
socialLogin: {
appSecret: 'your-production-secret',
redirectUri: 'https://your-app.com/auth/callback',
providers: {
google: { clientId: 'your-google-client-id' },
facebook: { clientId: 'your-facebook-app-id' },
}
}
});
```
--------------------------------
### Next.js Wallet Provider Setup
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/component-factory-summary.md
Sets up the NextWalletProvider for Next.js applications. This component should wrap your application to provide wallet functionalities.
```tsx
import { NextWalletProvider } from '@d-sports/wallet/nextjs';
function MyApp({ Component, pageProps }) {
return (
);
}
```
--------------------------------
### React Native Animation Example
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/animation-system-example.md
Example of animation in React Native using `MotiView`. Specifies timing transition with a duration.
```tsx
Content
```
--------------------------------
### Virtualization for Long Lists
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/components/ui/README.md
Implement virtualization for long lists to render only the visible items, significantly improving performance. This example uses a `VirtualList` component.
```tsx
function VirtualizedList({ items }) {
return (
{({ index, style }) => (
{items[index].name}
)}
);
}
```
--------------------------------
### Get Default Platform Adapter (Async)
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/README.md
Retrieve the default platform adapter for the current environment. This is useful for accessing storage, crypto, and network functionalities abstractly.
```typescript
import { getDefaultPlatformAdapterAsync } from './platform-adapters';
async function myFunction() {
// Get the default platform adapter for the current environment
const adapter = await getDefaultPlatformAdapterAsync();
// Use the adapter
const data = await adapter.storage.getItem('my-key');
// Generate random bytes
const randomBytes = adapter.crypto.generateRandomBytes(32);
// Make network requests
const response = await adapter.network.fetch('https://api.example.com/data');
}
```
--------------------------------
### Start Automatic Token Updates
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-updates.md
Begin the process of automatically updating token data at configured intervals.
```typescript
// Start automatic token updates
updateService.start();
```
--------------------------------
### Next.js Wallet Provider Setup
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/wallet-usage-examples.md
Integrates the wallet functionality into a Next.js application by wrapping the root component with `NextWalletProvider`. Configure app name, supported chains, and social providers.
```tsx
// pages/_app.tsx
import { NextWalletProvider } from '@d-sports/wallet/nextjs';
import type { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
return (
);
}
export default MyApp;
```
--------------------------------
### Handle Wallet Connection Errors
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/wallet-usage-examples.md
Use the `useWallet` hook to manage wallet connections and implement error handling for connection attempts. This example shows how to catch and display connection errors to the user.
```tsx
import { useWallet } from '@d-sports/wallet';
import { useState } from 'react';
function WalletConnect() {
const { connect, isConnecting } = useWallet();
const [error, setError] = useState(null);
const handleConnect = async (connector) => {
try {
setError(null);
await connect(connector);
} catch (err) {
setError(err);
console.error('Connection error:', err);
}
};
return (
Connect Wallet
{error && (
Error: {error.message}
Please try again or use a different connection method.
)}
);
}
```
--------------------------------
### Start Automatic Token Updates
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Initiates automatic background updates for token data. Configure the update interval in milliseconds. Default is 5 minutes.
```typescript
tokenService.startAutoUpdate(10 * 60 * 1000);
```
--------------------------------
### Component Composition for Wallet Dashboard
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/component-lifecycle.md
Composes multiple wallet-related components to build a dashboard UI. This example shows integrating a button, modal, status display, and token list.
```tsx
function WalletDashboard() {
const { isOpen, onOpen, onClose } = useWalletModal();
return (
Connect
);
}
```
--------------------------------
### Checking Network Availability
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/README-network-adapter.md
Provides an example of how to check if the network is currently available using the `isNetworkAvailable` method of the network adapter. This is useful for conditionally performing network operations.
```typescript
const adapter = await createNetworkAdapter('web');
const isAvailable = await adapter.isNetworkAvailable();
if (isAvailable) {
// Make network requests
} else {
// Handle offline scenario
}
```
--------------------------------
### Create D-Sports Wallet for React Native
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Instantiate the D-Sports Wallet for React Native applications. Requires URL polyfill setup and uses deep links for social login callbacks.
```typescript
import { createDSportsWallet, setupURLPolyfill } from '@d-sports/wallet/react-native';
// Setup URL polyfill (required for React Native)
setupURLPolyfill();
// Create wallet instance
const wallet = createDSportsWallet({
projectId: 'your-project-id',
chains: [/* your chains */],
socialLogin: {
appSecret: 'your-app-secret',
redirectUri: 'dsports://auth/callback', // Deep link for mobile
providers: {
google: {
clientId: 'your-google-client-id',
},
apple: {
clientId: 'your-apple-client-id',
},
},
},
});
// Connect wallet
await wallet.connect();
```
--------------------------------
### D-Sports OAuth Service - Get Managed Credentials
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Retrieves managed OAuth credentials from the D-Sports OAuth Service for development environments. This simplifies setup by providing pre-configured credentials.
```typescript
import { DSportsOAuthService, createQuickStartSocialLogin } from '@d-sports/wallet';
const managed = DSportsOAuthService.getManagedCredentials({
environment: 'development'
});
```
--------------------------------
### Build Project
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Command to build the project using bun.
```bash
bun run build
```
--------------------------------
### Basic Network Request with Network Adapter
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/README-network-adapter.md
Demonstrates how to create a network adapter for the 'web' platform and use it to fetch data from an API. It also shows how to check network availability.
```typescript
import { createNetworkAdapter } from './network-adapter';
async function fetchData() {
// Create a network adapter for the current platform
const adapter = await createNetworkAdapter('web');
// Use the adapter to make network requests
const response = await adapter.fetch('https://api.example.com/data');
const data = await response.json();
// Check if network is available
const isNetworkAvailable = await adapter.isNetworkAvailable();
return data;
}
```
--------------------------------
### Production Wallet Initialization
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Initialize the wallet with production-ready configuration, including social login providers and environment settings.
```APIDOC
## Production Wallet Initialization
### Description
Initialize the wallet with production-ready configuration, including social login providers and environment settings.
### Method
```typescript
createDSportsWallet
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **projectId** (string) - Required - Your project ID.
- **chains** (Array) - Required - List of blockchain chains to support.
- **environment** (string) - Required - Set to 'production' to validate config.
- **socialLogin** (object) - Optional - Configuration for social login providers.
- **appSecret** (string) - Required - Your production secret.
- **redirectUri** (string) - Required - The URI for authentication callbacks.
- **providers** (object) - Required - Configuration for individual social login providers.
- **google** (object) - Optional - Google provider configuration.
- **clientId** (string) - Required - Your Google client ID.
- **facebook** (object) - Optional - Facebook provider configuration.
- **clientId** (string) - Required - Your Facebook app ID.
- ... other providers
### Request Example
```typescript
const wallet = createDSportsWallet({
projectId: 'your-project-id',
chains: [mainnet, polygon],
environment: 'production',
socialLogin: {
appSecret: 'your-production-secret',
redirectUri: 'https://your-app.com/auth/callback',
providers: {
google: { clientId: 'your-google-client-id' },
facebook: { clientId: 'your-facebook-app-id' },
// ... other providers
}
}
});
```
### Response
#### Success Response (200)
Wallet instance
#### Response Example
None
```
--------------------------------
### Initialize WalletProvider Component
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/component-lifecycle.md
The WalletProvider initializes the wallet store, sets up the platform adapter, initializes connectors, sets up event listeners, attempts to restore a previous session, and renders children with context. It requires configuration props.
```typescript
/**
* WalletProvider component lifecycle:
*
* 1. Initialize wallet store with configuration
* 2. Set up platform adapter
* 3. Initialize connectors
* 4. Set up event listeners
* 5. Attempt to restore previous session
* 6. Render children with context
*/
function WalletProvider({ children, ...config }: WalletProviderProps) {
// Initialize wallet store
const [store] = useState(() => createWalletStore(config));
// Set up platform adapter
useEffect(() => {
store.setPlatformAdapter(config.adapter || createWebPlatformAdapter());
return () => {
// Clean up adapter resources
store.cleanup();
};
}, [store]);
// Initialize connectors
useEffect(() => {
store.initializeConnectors();
}, [store]);
// Set up event listeners
useEffect(() => {
const unsubscribe = store.subscribe((state) => {
// Handle state changes
});
return () => {
unsubscribe();
};
}, [store]);
// Attempt to restore previous session
useEffect(() => {
store.restoreSession();
}, [store]);
// Render children with context
return (
{children}
);
}
```
--------------------------------
### Run Tests
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Command to execute the project's test suite using bun.
```bash
bun test
```
--------------------------------
### createDSportsWallet
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/comprehensive-api-documentation.md
Initializes the main wallet class with configuration options.
```APIDOC
## createDSportsWallet
### Description
Initializes the main wallet class with configuration options.
### Usage
```typescript
import { createDSportsWallet } from '@d-sports/wallet';
const wallet = createDSportsWallet({
appName: 'My App',
chains: [1, 137], // Ethereum, Polygon
socialProviders: ['google', 'twitter']
});
```
### Parameters
- `appName` (string): The name of your application.
- `chains` (number[]): An array of chain IDs to support.
- `socialProviders` (string[]): An array of social login providers to enable.
```
--------------------------------
### Create Web Platform Adapter
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/comprehensive-api-documentation.md
Initializes a web platform adapter for the D-Sports wallet. This is a prerequisite for creating a wallet instance.
```typescript
import { createWebPlatformAdapter } from '@d-sports/wallet';
const adapter = createWebPlatformAdapter();
const wallet = createDSportsWallet({
appName: 'My App',
adapter
});
```
--------------------------------
### createCryptoAdapter(platform, options)
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/crypto-adapter.md
Creates a crypto adapter instance tailored for a specific platform. It can optionally force the use of an insecure fallback implementation.
```APIDOC
## createCryptoAdapter(platform, options)
Creates a crypto adapter for the specified platform with optional configuration.
### Parameters
- `platform`: `'web' | 'nextjs' | 'react-native'` - The target platform
- `options`: (optional)
- `useInsecureCrypto`: `boolean` - Force using the insecure fallback implementation
### Returns
`Promise` - A crypto adapter instance
```
--------------------------------
### Using Specific Crypto Implementations
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/crypto-adapter.md
Shows how to directly instantiate either the Web Crypto API adapter or the fallback implementation. The fallback is not secure for production.
```typescript
import {
createWebCryptoAdapter,
createFallbackCryptoAdapter
} from './crypto-adapter';
// Use Web Crypto API directly (if available)
const webCrypto = createWebCryptoAdapter();
// Use fallback implementation (not secure for production)
const fallbackCrypto = createFallbackCryptoAdapter();
```
--------------------------------
### Get Tokens By Network
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Retrieves all tokens associated with a specific network from the cache.
```APIDOC
## getTokensByNetwork
### Description
Retrieves tokens filtered by a specific network from the local cache.
### Parameters
#### Path Parameters
- **network** (string) - Required - The network name to filter by (e.g., "Ethereum")
### Returns
`TokenInfo[]` - An array of token information objects for the specified network.
### Example
```typescript
const ethereumTokens = getTokensByNetwork("Ethereum");
console.log(`Found ${ethereumTokens.length} tokens on Ethereum`);
```
```
--------------------------------
### Get All Token Symbols
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Retrieves a list of all unique token symbols available in the cache.
```APIDOC
## getAllTokenSymbols
### Description
Retrieves all unique token symbols from the local cache.
### Returns
`string[]` - An array of unique token symbols.
### Example
```typescript
const symbols = getAllTokenSymbols();
console.log(`Supported tokens: ${symbols.join(', ')}`);
```
```
--------------------------------
### Network Request with Custom Options
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/README-network-adapter.md
Shows how to create a network adapter with custom options, such as setting a timeout and controlling the use of insecure fallbacks. It also demonstrates making a POST request with custom headers and body.
```typescript
import { createNetworkAdapter } from './network-adapter';
async function fetchWithOptions() {
// Create a network adapter with custom options
const adapter = await createNetworkAdapter('web', {
timeout: 5000, // 5 second timeout
useInsecureFallback: false // Don't use fallback if fetch is not available
});
// Make a POST request with headers
const response = await adapter.fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
});
return response.json();
}
```
--------------------------------
### Get All Token Data
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Retrieves all token data currently stored in the local cache.
```APIDOC
## getTokenData
### Description
Retrieves all token data from the local cache.
### Returns
`TokenInfo[]` - An array of token information objects.
### Example
```typescript
const tokens = getTokenData();
console.log(`Found ${tokens.length} tokens`);
```
```
--------------------------------
### Basic Crypto Adapter Usage
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/crypto-adapter.md
Demonstrates creating a crypto adapter and performing basic operations like generating random bytes and calculating SHA-256 hashes. Specify the target platform when creating the adapter.
```typescript
import { createCryptoAdapter } from './crypto-adapter';
async function example() {
// Create a crypto adapter for the current platform
const crypto = await createCryptoAdapter('web'); // or 'nextjs', 'react-native'
// Generate random bytes
const randomBytes = crypto.generateRandomBytes(32);
console.log('Random bytes:', randomBytes);
// Calculate SHA-256 hash
const data = new TextEncoder().encode('Hello, world!');
const hash = await crypto.sha256(data);
console.log('SHA-256 hash:', hash);
}
```
--------------------------------
### Run Platform Adapter Factory Tests
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/__tests__/README.md
Execute tests for the platform adapter factory pattern to ensure correct operation across diverse environments and feature sets.
```bash
npm run test:platform-adapters
```
--------------------------------
### Get Last Updated Timestamp
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Retrieves the timestamp indicating when the token data was last updated.
```APIDOC
## getLastUpdated
### Description
Retrieves the timestamp of the last token data update.
### Returns
`Date | null` - The timestamp of the last update or null if the data has never been updated.
### Example
```typescript
const lastUpdated = getLastUpdated();
if (lastUpdated) {
console.log(`Last updated: ${lastUpdated.toLocaleString()}`);
}
```
```
--------------------------------
### Network Request with Custom Fetch Implementation
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/README-network-adapter.md
Illustrates how to create a network adapter and provide a custom fetch function to be used instead of the default implementation.
```typescript
import { createNetworkAdapter } from './network-adapter';
async function fetchWithCustomImplementation() {
// Create a network adapter with a custom fetch implementation
const adapter = await createNetworkAdapter('web', {
customFetch: myCustomFetchFunction
});
// Use the adapter with the custom implementation
const response = await adapter.fetch('https://api.example.com/data');
return response.json();
}
```
--------------------------------
### Get Token By Symbol
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Retrieves a specific token's information from the cache using its symbol.
```APIDOC
## getTokenBySymbol
### Description
Retrieves a specific token by its symbol from the local cache.
### Parameters
#### Path Parameters
- **symbol** (string) - Required - The token symbol to search for (e.g., "BTC")
### Returns
`TokenInfo | undefined` - The matching token information object or undefined if not found.
### Example
```typescript
const bitcoin = getTokenBySymbol("BTC");
if (bitcoin) {
console.log(`Bitcoin price: ${bitcoin.price}`);
}
```
```
--------------------------------
### Run All Tests
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/__tests__/README.md
Execute all defined test suites for the D-Sports wallet package.
```bash
npm test
```
--------------------------------
### Build Core Package with Bun
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Specifically builds the core wallet functionality package. Useful when only the core logic needs to be compiled.
```sh
bun run build:core
```
--------------------------------
### Build and Validate Browser Bundles
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/__tests__/README.md
Initiate the build process for all packages, which includes automatically running the bundle validation script to confirm browser compatibility.
```bash
npm run build
```
--------------------------------
### Create DSportsWallet Instance
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/comprehensive-api-documentation.md
Initialize the main wallet class with application name, supported chains, and social providers. This instance manages core wallet operations.
```typescript
import { createDSportsWallet } from '@d-sports/wallet';
const wallet = createDSportsWallet({
appName: 'My App',
chains: [1, 137], // Ethereum, Polygon
socialProviders: ['google', 'twitter']
});
```
--------------------------------
### D-Sports OAuth Service
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Utilize the D-Sports OAuth Service to get managed credentials for development or validate production configurations.
```APIDOC
## D-Sports OAuth Service
### Description
Utilize the D-Sports OAuth Service to get managed credentials for development or validate production configurations.
### Methods
#### `DSportsOAuthService.getManagedCredentials`
##### Description
Retrieves managed OAuth credentials for a specified environment.
##### Parameters
- **environment** (string) - Required - The environment for which to get credentials (e.g., 'development').
##### Returns
Managed credentials object.
#### `createQuickStartSocialLogin`
##### Description
Creates a quick start configuration for social login, typically used for development.
##### Parameters
None
##### Returns
Quick start social login configuration object.
#### `validateSocialLoginConfig`
##### Description
Validates a social login configuration against a specified environment.
##### Parameters
- **myConfig** (object) - Required - The social login configuration to validate.
- **environment** (string) - Required - The environment to validate against (e.g., 'production').
##### Returns
Validated social login configuration object.
### Request Example
```typescript
import { DSportsOAuthService, createQuickStartSocialLogin } from '@d-sports/wallet';
// Get managed credentials
const managed = DSportsOAuthService.getManagedCredentials({
environment: 'development'
});
// Quick start config (auto-generated)
const quickStartConfig = createQuickStartSocialLogin();
// Validate production config
const productionConfig = validateSocialLoginConfig(myConfig, 'production');
```
### Response
#### Success Response (200)
- **managed**: Object containing managed credentials.
- **quickStartConfig**: Object containing quick start configuration.
- **productionConfig**: Object containing validated production configuration.
#### Response Example
None
```
--------------------------------
### Get Last Update Time
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-updates.md
Retrieves the timestamp of the last successful token data update. Returns null if the data has never been updated.
```APIDOC
## Get Last Update Time
### Description
Gets the timestamp of the last token data update.
### Method
`getLastUpdateTime(): Date | null`
### Parameters
None
### Request Example
```typescript
// Get the timestamp of the last token data update
const lastUpdate = getLastUpdateTime();
if (lastUpdate) {
console.log(`Last updated: ${lastUpdate.toLocaleString()}`);
} else {
console.log('Never updated');
}
```
### Response
#### Success Response
- **Date | null**: Timestamp of the last update or null if never updated.
#### Response Example
```json
{
"lastUpdateTime": "2023-10-27T10:30:00.000Z"
}
```
```
--------------------------------
### Get Last Updated Timestamp
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
Retrieves the timestamp of the last successful token data update. Returns null if the data has never been updated.
```typescript
export function getLastUpdated(): Date | null;
```
```typescript
// Get last update timestamp
const lastUpdated = getLastUpdated();
if (lastUpdated) {
console.log(`Last updated: ${lastUpdated.toLocaleString()}`);
}
```
--------------------------------
### useToken Hook Example
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
React hook for accessing data for a specific token by its symbol. Provides loading and error states for individual token retrieval.
```tsx
function BitcoinPrice() {
const { token, isLoading, error } = useToken('BTC');
if (isLoading) return
Loading...
;
if (error) return
Error: {error.message}
;
if (!token) return
Token not found
;
return
Bitcoin price: {token.price}
;
}
```
--------------------------------
### Clean Build Artifacts with Bun
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Removes all generated build files and artifacts. Run this to ensure a clean build environment.
```sh
bun run clean
```
--------------------------------
### Set up Wallet Provider
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/wallet-usage-examples.md
Configure the WalletProvider with your application name and supported chains. You can also specify social login providers.
```tsx
import { WalletProvider } from '@d-sports/wallet';
function App() {
return (
);
}
```
--------------------------------
### createFallbackCryptoAdapter()
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/crypto-adapter.md
Creates a fallback crypto adapter designed to function in any environment, though it is not recommended for production due to security limitations.
```APIDOC
## createFallbackCryptoAdapter()
Creates a fallback crypto adapter that works in any environment (not secure for production).
### Returns
`CryptoAdapter` - A crypto adapter instance
```
--------------------------------
### Get Last Token Update Time
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-updates.md
Retrieves the timestamp of the last successful token data update. Returns null if the data has never been updated.
```typescript
/**
* Gets the timestamp of the last token data update
*
* @function getLastUpdateTime
* @returns {Date | null} Timestamp of the last update or null if never updated
*
* @example
* ```typescript
* // Get the timestamp of the last token data update
* const lastUpdate = getLastUpdateTime();
* if (lastUpdate) {
* console.log(`Last updated: ${lastUpdate.toLocaleString()}`);
* } else {
* console.log('Never updated');
* }
* ```
*/
export function getLastUpdateTime(): Date | null;
```
--------------------------------
### useTokens Hook Example
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-fetching.md
React hook for accessing and managing token data within a component. Handles loading states, errors, and provides a refresh function.
```tsx
function TokenList() {
const { tokens, isLoading, error, refresh } = useTokens();
if (isLoading) return
Loading...
;
if (error) return
Error: {error.message}
;
return (
{tokens.map(token => (
{token.name} ({token.symbol}): {token.value}
))}
);
}
```
--------------------------------
### Theme Configuration
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Interface for customizing the wallet's appearance.
```APIDOC
## WalletTheme
### Description
Allows customization of the wallet UI theme.
### Interface
```typescript
interface WalletTheme {
colors?: {
primary?: string;
secondary?: string;
background?: string;
text?: string;
border?: string;
};
borderRadius?: number;
fontFamily?: string;
}
```
```
--------------------------------
### Conditional Rendering of Content
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/components/ui/README.md
Implement conditional rendering to display content only when a specific condition is met. This example returns `null` if `isVisible` is false, effectively hiding the children.
```tsx
function ConditionalContent({ isVisible, children }) {
if (!isVisible) return null;
return
{children}
;
}
```
--------------------------------
### Create Custom Platform Adapter
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/README.md
Create a custom platform adapter for specific use cases, allowing configuration of features like storage and crypto.
```typescript
import { createCustomPlatformAdapter } from './platform-adapter-factory';
async function myFunction() {
// Create a custom adapter for a specific platform
const adapter = await createCustomPlatformAdapter('web', {
useMemoryStorage: true,
useInsecureCrypto: false
});
// Use the adapter
// ...
}
```
--------------------------------
### Conditional Rendering with Ternary Operator
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/rendering-patterns.md
Use conditional rendering to display UI elements based on component state. This example shows toggling between connected and disconnected states.
```tsx
function WalletStatus() {
const { isConnected, account } = useWallet();
return (
{isConnected ? (
Connected: {account}
) : (
Not connected
)}
);
}
```
--------------------------------
### Run Tests with Bun
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/README.md
Executes all defined test suites. This is a standard command for verifying the correctness of the codebase.
```sh
bun run test
```
--------------------------------
### React Native Wallet Provider Setup
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/component-factory-summary.md
Configures the RNWalletProvider for React Native applications. This provider is essential for integrating wallet features within your React Native app.
```tsx
import { RNWalletProvider } from '@d-sports/wallet/react-native';
function App() {
return (
);
}
```
--------------------------------
### Get Token Update Status
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-updates.md
Retrieve the current status of the token update service, including its state, the last update time, and the next scheduled update time.
```typescript
// Get the current update status
const status = updateService.getStatus();
console.log(`Update status: ${status.state}`);
console.log(`Last update: ${status.lastUpdate}`);
console.log(`Next update: ${status.nextUpdate}`);
```
--------------------------------
### Platform-Specific Optimizations
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/components/ui/README.md
Optimize rendering for different platforms (web and React Native) by detecting the platform and conditionally rendering components. This example uses helper functions `getPlatformComponents` and `isReactNative`.
```tsx
function OptimizedComponent({ children }) {
const { View } = getPlatformComponents();
if (isReactNative()) {
return (
{children}
);
}
return (
{children}
);
}
```
--------------------------------
### DSportsWallet Instance Methods
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/comprehensive-api-documentation.md
Methods available on the initialized DSportsWallet instance.
```APIDOC
## DSportsWallet Instance Methods
### Description
Methods available on the initialized DSportsWallet instance for managing wallet connections and signing.
### Methods
#### connect()
- **Description**: Connects the user's wallet.
- **Usage**: `await wallet.connect();`
#### getAccount()
- **Description**: Retrieves the current connected account address.
- **Usage**: `const account = wallet.getAccount();`
#### signMessage(message: string)
- **Description**: Signs a given message with the connected wallet.
- **Parameters**:
- `message` (string) - The message to sign.
- **Usage**: `const signature = await wallet.signMessage('Hello, world!');`
```
--------------------------------
### Derived State Calculation
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/components/ui/README.md
Calculate derived state within a component based on props and context. This example shows how to determine if a tab is selected based on the context's current value.
```tsx
function TabContent({ value, ...props }) {
const context = React.useContext(TabsContext);
const isSelected = context?.value === value;
// Render based on derived state
if (!isSelected) return null;
return ;
}
```
--------------------------------
### Subscribe to Token Update Events
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-updates.md
Register an event handler to receive notifications about token update events such as start, completion, errors, scheduling, or cancellation. Returns a function to unsubscribe the handler.
```typescript
// Subscribe to update events
const unsubscribe = updateService.subscribe((event) => {
console.log(`Update event: ${event.type}`);
if (event.type === 'error') {
console.error('Update error:', event.error);
}
});
// Later, unsubscribe
unsubscribe();
```
--------------------------------
### Run Browser Compatibility Tests
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/__tests__/README.md
Execute tests to verify the package's functionality in browser environments, ensuring no reliance on Node.js globals or modules.
```bash
npm run test:browser-compatibility
```
--------------------------------
### createWebCryptoAdapter()
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/src/utils/crypto-adapter.md
Creates a crypto adapter that exclusively utilizes the Web Crypto API for cryptographic operations.
```APIDOC
## createWebCryptoAdapter()
Creates a crypto adapter that uses the Web Crypto API.
### Returns
`CryptoAdapter` - A crypto adapter instance
```
--------------------------------
### DSportsWallet Core Operations
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/comprehensive-api-documentation.md
Demonstrates connecting a wallet, retrieving account information, and signing messages using the DSportsWallet instance. Ensure the wallet is initialized before calling these methods.
```typescript
import { createDSportsWallet } from '@d-sports/wallet';
const wallet = createDSportsWallet({
appName: 'My App',
chains: [1, 137],
socialProviders: ['google', 'twitter']
});
// Connect wallet
await wallet.connect();
// Get account
const account = wallet.getAccount();
// Sign message
const signature = await wallet.signMessage('Hello, world!');
```
--------------------------------
### TokenUpdateService Class
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/token-updates.md
The TokenUpdateService class provides methods to manage and control automatic token updates. It allows starting, stopping, and manually triggering updates, as well as retrieving the current status and subscribing to update events.
```APIDOC
## TokenUpdateService
### Description
Provides higher-level functionality for managing token updates.
### Methods
#### constructor(options?: TokenUpdateOptions)
Creates a new TokenUpdateService instance.
- **options** (TokenUpdateOptions) - Optional token update options.
### start()
Starts automatic token updates.
### stop()
Stops automatic token updates.
### updateNow()
Updates token data immediately.
- **Returns**: Promise - Promise that resolves when the update is complete.
### getStatus()
Gets the current update status.
- **Returns**: TokenUpdateStatus - Current update status.
### subscribe(handler: TokenUpdateEventHandler)
Subscribes to update events.
- **handler** (TokenUpdateEventHandler) - Event handler function.
- **Returns**: Function - Function to unsubscribe.
```
--------------------------------
### Create and Control Animations with useAnimation Hook
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/animation-system-example.md
Use the `useAnimation` hook to create and control animations. It accepts animation options and returns animation controls. Ensure `autoPlay` is not set to `false` to start animations automatically.
```typescript
/**
* Hook for creating and controlling animations
*
* @function useAnimation
* @param {AnimationOptions} options - Animation options
* @returns {AnimationControls} Animation controls
*
* @example
* ```tsx
* const controls = useAnimation({
* initial: { opacity: 0, y: 20 },
* animate: { opacity: 1, y: 0 },
* exit: { opacity: 0, y: -20 },
* transition: { duration: 0.3 }
* });
*
* // Start the animation
* controls.start();
*
* // Stop the animation
* controls.stop();
* ```
*/
function useAnimation(options: AnimationOptions): AnimationControls {
const controls = useMotionControls();
useEffect(() => {
if (options.autoPlay !== false) {
controls.start(options.animate);
}
}, [controls, options]);
return controls;
}
```
--------------------------------
### Component Mount and Unmount Lifecycle Events
Source: https://github.com/d-sports-ecosystem/wallet/blob/main/docs/component-lifecycle.md
Demonstrates basic component lifecycle management using `useEffect` for initialization and cleanup. The effect runs once on mount and its cleanup function runs on unmount.
```typescript
useEffect(() => {
// Initialize component
console.log('Component mounted');
return () => {
// Clean up resources
console.log('Component unmounted');
};
}, []);
```