@d-sports/wallet

中文文档
1.1.1发布于 2025/07/22MITTypeScriptESM + CJS近 30 天下载 2088

[IN PROGRESS] A comprehensive wallet package with Rainbow Kit and Wagmi connectors, supporting both Next.js and React Native with social login functionality

原始使用文档
文档目录37 节
  1. ✨ Features
  2. 🚀 Installation
  3. Platform-specific Dependencies
  4. 🏃‍♂️ Quick Start
  5. 🚀 Super Quick Start (5 minutes)
  6. Production Setup
  7. Next.js
  8. React Native
  9. 📚 Usage Examples
  10. Basic Wallet Connection
  11. Custom Social Login
  12. Rainbow Kit Integration
  13. Wagmi Integration
  14. 🔧 API Reference
  15. DSportsWallet
  16. React Hooks
  17. ⚙️ Configuration
  18. Custom Social Login Configuration
  19. Supported Social Providers
  20. Setting Up OAuth Applications
  21. Theme Configuration
  22. OAuth Callback Page
  23. Deep Linking (React Native)
  24. 💰 Cost Comparison
  25. 🛠️ Development
  26. Setup
  27. Build
  28. Test
  29. Development Scripts
  30. 📦 Package Structure
  31. 🔒 Security Features
  32. 🤝 Contributing
  33. 📄 License
  34. 🙏 Acknowledgments
  35. 🔄 Quick Start → Production Migration
  36. Development to Production Path
  37. D-Sports OAuth Service

@d-sports/wallet

⚠️ IMPORTANT: IN PROGRESS - This package is currently being updated to fix build issues. Please use with caution.

A powerful, multi-platform wallet SDK for React, Next.js, and React Native applications with free, custom social login and support for Rainbow Kit and Wagmi. 100% D-Sports branded with no vendor dependencies.

✨ Features

  • 🌐 Multi-platform support: Works with React, Next.js, and React Native
  • 🔐 Custom social login: FREE OAuth integration with Google, Facebook, Twitter, Discord, GitHub, and Apple
  • 🏆 D-Sports branded: Fully customizable, no vendor lock-in
  • 🌈 Rainbow Kit compatible: Easy integration with Rainbow Kit's wallet connection UI
  • ⚡ Wagmi compatible: Full support for Wagmi v1 and v2
  • 🎨 Customizable UI: Flexible theming and styling options
  • 🔒 Secure storage: Platform-specific secure storage solutions
  • 📱 Mobile-first: Deep linking and mobile-optimized experience
  • 🔄 Auto-reconnection: Persistent wallet connections across sessions
  • 💰 Zero cost: No per-user fees or external dependencies
  • 🎯 TypeScript: Full TypeScript support with comprehensive type definitions

🚀 Installation

npm install @d-sports/wallet
# or
yarn add @d-sports/wallet
# or
bun add @d-sports/wallet

Platform-specific Dependencies

For Next.js/React:

# No additional dependencies required!

For React Native:

npm install react-native-keychain react-native-url-polyfill

🏃‍♂️ Quick Start

🚀 Super Quick Start (5 minutes)

Get started immediately with D-Sports managed OAuth credentials - no OAuth setup required!

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!');

Perfect for:

  • 🧪 Prototyping and proof of concepts
  • 👨‍💻 Development and testing
  • 🎓 Learning and tutorials
  • 🏁 Getting started quickly

Production Setup

For production apps, set up your own OAuth applications:

Next.js

import { createDSportsWallet } from '@d-sports/wallet/nextjs';

// Create wallet instance
const wallet = createDSportsWallet({
  projectId: 'your-project-id',
  chains: [/* your chains */],
  environment: 'production', // Validates production config
  socialLogin: {
    appSecret: 'your-app-secret', // For deterministic key generation
    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',
      },
    },
  },
});

// Connect wallet
await wallet.connect();

React Native

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();

📚 Usage Examples

Basic Wallet Connection

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'] }
      }
    }
  ]
});

// Connect to wallet
const account = await wallet.connect();
console.log('Connected account:', account);

// Get wallet state
const state = wallet.getState();
console.log('Wallet state:', state);

// Switch chain
await wallet.switchChain(137); // Polygon

// Disconnect
await wallet.disconnect();

Custom Social Login

import { createDSportsWallet, CustomSocialLoginProvider } from '@d-sports/wallet';

const wallet = createDSportsWallet({
  projectId: 'your-project-id',
  chains: [/* your chains */],
  socialLogin: {
    appSecret: 'your-unique-app-secret', // Used for deterministic key generation
    redirectUri: 'https://your-app.com/auth/callback',
    providers: {
      google: {
        clientId: 'your-google-oauth-client-id',
      },
      facebook: {
        clientId: 'your-facebook-app-id',
      },
      twitter: {
        clientId: 'your-twitter-oauth-client-id',
      },
      discord: {
        clientId: 'your-discord-oauth-client-id',
      },
      github: {
        clientId: 'your-github-oauth-client-id',
      },
    },
  },
});

// Connect with social login
await wallet.connect({ socialLogin: true });

// Get social login provider
const socialProvider = wallet.getConnector('dsports-wallet').customSocialLoginProvider;

// Login with specific provider
const result = await socialProvider.login('google');
console.log('Social login result:', result);

// Get wallet from social login
const ethersWallet = await socialProvider.getWalletFromSocial(result);
console.log('Generated wallet address:', ethersWallet.address);

Rainbow Kit Integration

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',
      },
    },
  },
});

// Use with Rainbow Kit
const connectors = [
  connector,
  // ... other connectors
];

Wagmi Integration

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',
      },
    },
  },
});

// Use with Wagmi
const connectors = [
  connector,
  // ... other connectors
];

🔧 API Reference

DSportsWallet

Constructor Options

interface DSportsWalletOptions {
  projectId: string;
  chains: Chain[];
  socialLogin?: CustomSocialLoginConfig;
  theme?: WalletTheme;
  metadata?: {
    name: string;
    description: string;
    url: string;
    icons: string[];
  };
}

Methods

  • connect(config?: { socialLogin?: boolean }): Promise<WalletAccount>
  • disconnect(): Promise<void>
  • switchChain(chainId: number): Promise<void>
  • getState(): WalletState
  • isConnected(): boolean
  • getConnector(id: string): WalletConnector | undefined
  • addConnector(connector: WalletConnector): void
  • removeConnector(id: string): void

Events

  • connect: Emitted when wallet connects
  • disconnect: Emitted when wallet disconnects
  • accountsChanged: Emitted when accounts change
  • chainChanged: Emitted when chain changes
  • error: Emitted when an error occurs

React Hooks

useDSportsWallet

const {
  account,
  isConnecting,
  isReconnecting,
  isDisconnected,
  error,
  connect,
  disconnect,
  switchChain,
  isConnected
} = useDSportsWallet(wallet);

useSocialLogin

const {
  user,
  isLoading,
  error,
  login,
  logout
} = useSocialLogin(customSocialLoginProvider);

⚙️ Configuration

Custom Social Login Configuration

interface CustomSocialLoginConfig {
  appSecret?: string; // Used for deterministic wallet generation
  redirectUri?: string; // OAuth callback URL
  providers: {
    [key in SocialProvider]?: {
      clientId: string;
      clientSecret?: string; // For backend token exchange
    };
  };
}

Supported Social Providers

  • Google (google): OAuth 2.0
  • Facebook (facebook): Facebook Login
  • Twitter (twitter): OAuth 2.0
  • Discord (discord): OAuth 2.0
  • GitHub (github): OAuth 2.0
  • Apple (apple): Sign in with Apple

Setting Up OAuth Applications

Google OAuth Setup

  1. Go to Google Cloud Console
  2. Create a new project or select existing
  3. Enable Google+ API
  4. Create OAuth 2.0 credentials
  5. Add your domain to authorized origins
  6. Copy the Client ID

Facebook OAuth Setup

  1. Go to Facebook Developers
  2. Create a new app
  3. Set up Facebook Login
  4. Add your domain to valid OAuth redirect URIs
  5. Copy the App ID

Twitter OAuth Setup

  1. Go to Twitter Developer Portal
  2. Create a new app
  3. Set up OAuth 2.0
  4. Configure callback URLs
  5. Copy the Client ID

Theme Configuration

interface WalletTheme {
  colors?: {
    primary?: string;
    secondary?: string;
    background?: string;
    text?: string;
    border?: string;
  };
  borderRadius?: number;
  fontFamily?: string;
}

OAuth Callback Page

Create a callback page at your redirectUri to handle OAuth responses:

<!DOCTYPE html>
<html>
<head>
  <title>D-Sports Authentication</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
    .loading { color: #666; }
    .logo { width: 64px; height: 64px; margin: 20px auto; }
  </style>
</head>
<body>
  <div class="logo">🏆</div>
  <h2>D-Sports Authentication</h2>
  <p class="loading">Processing your login...</p>
  <script>
    // Handle OAuth callback
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    const error = urlParams.get('error');
    
    if (error) {
      window.parent.postMessage({
        type: 'OAUTH_ERROR',
        error: error
      }, window.location.origin);
    } else if (code) {
      // Exchange code for user data (implement your backend logic)
      window.parent.postMessage({
        type: 'OAUTH_SUCCESS',
        payload: {
          code,
          user: {
            id: 'user-id-from-your-backend',
            email: '[email protected]',
            name: 'User Name',
            avatar: 'https://example.com/avatar.jpg'
          },
          token: 'access-token-from-your-backend',
          expiresAt: Date.now() + 3600000
        }
      }, window.location.origin);
    }
  </script>
</body>
</html>

Deep Linking (React Native)

import { handleDeepLink } from '@d-sports/wallet/react-native';

// Handle deep link
handleDeepLink('dsports://wallet/connect?connector=dsports-wallet', wallet);

💰 Cost Comparison

ProviderCostLock-inBranding
@d-sports/walletFREE❌ None🏆 Full D-Sports
Web3Auth$0.05/MAU✅ Yes🔒 Limited
Magic$0.02/MAU✅ Yes🔒 Limited
Privy$0.05/MAU✅ Yes🔒 Limited

🛠️ Development

Setup

git clone https://github.com/D-Sports-Ecosystem/wallet.git
cd wallet
bun install

Build

bun run build

Test

bun test

Development Scripts

  • bun run dev: Start development mode
  • bun run build: Build all packages
  • bun run build:core: Build core package
  • bun run build:nextjs: Build Next.js package
  • bun run build:react-native: Build React Native package
  • bun run clean: Clean build artifacts
  • bun run lint: Run ESLint
  • bun run test: Run tests
  • bun run test:watch: Run tests in watch mode

📦 Package Structure

@d-sports/wallet/
├── core              # Core wallet functionality
├── nextjs            # Next.js specific exports
├── react-native      # React Native specific exports
├── custom-social-login # Custom social login provider
└── types             # TypeScript type definitions

🔒 Security Features

  • Deterministic Key Generation: Wallets are generated deterministically from social login data
  • Secure Storage: Platform-specific secure storage (localStorage, AsyncStorage, Keychain)
  • No Private Key Transmission: Keys are generated locally, never sent to servers
  • Custom App Secret: Use your own secret for additional security
  • OAuth Best Practices: Follows OAuth 2.0 security guidelines

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

MIT License - see the LICENSE file for details.

🙏 Acknowledgments


Made with ❤️ by the D-Sports team - A free, open-source alternative to expensive wallet providers.

🔄 Quick Start → Production Migration

Development to Production Path

  1. Start with Quick Start (5 minutes):

    const wallet = createDSportsWalletQuickStart({
      projectId: 'your-project-id',
      chains: [mainnet, polygon]
    });
    
  2. Create Your OAuth Apps (30 minutes):

  3. Switch to Production Config:

    const wallet = createDSportsWallet({
      projectId: 'your-project-id',
      chains: [mainnet, polygon],
      environment: 'production', // Validates config
      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
        }
      }
    });
    

D-Sports OAuth Service

D-Sports provides managed OAuth credentials for instant development:

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');

Managed OAuth includes:

  • ✅ Google - Ready to use
  • ✅ Facebook - Ready to use
  • ✅ Twitter - Ready to use
  • ✅ Discord - Ready to use
  • ✅ GitHub - Ready to use
  • ⚠️ Apple - Requires individual setup

Benefits:

  • 🚀 Instant setup - No OAuth configuration
  • 🛡️ Production warnings - Automatic validation
  • 🔄 Easy migration - Same API, different config
  • 📚 Perfect for demos - Show features immediately

版本与发布记录

@d-sports/wallet 共发布 4 个版本,首次发布于 2025/07/04;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.1.1latest2025/07/221.3 年前
1.1.02025/07/051.4 年前
1.0.42025/07/051.4 年前
1.0.02025/07/041.4 年前

关于 @d-sports/wallet 的常见问题

@d-sports/wallet 是什么?

[IN PROGRESS] A comprehensive wallet package with Rainbow Kit and Wagmi connectors, supporting both Next.js and React Native with social login functionality

如何安装 @d-sports/wallet?

在项目目录运行 npm install @d-sports/wallet,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.0.0)、react-dom(^18.0.0)、tailwindcss(^3.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@d-sports/wallet 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@d-sports/wallet 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@d-sports/wallet 可以商用吗?

@d-sports/wallet 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@d-sports/wallet 的下载量有多少?

根据 npm 官方下载统计,@d-sports/wallet 在 2026/10/11 – 2026/11/09 这 30 天内被下载 2,088 次,日均约 70 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@d-sports/wallet 还在维护吗?

最新版本 1.1.1 发布于 2025/07/22(1.3 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2025/07/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。