or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

i18n.mdindex.mdreact-provider.mdtypes.mdutilities.mdweb3-provider.md
tile.json

react-provider.mddocs/

React Configuration Provider

React context provider for managing Web3 configuration and state across your application. The Web3ConfigProvider component creates a React context that makes Web3 state and functionality available to child components throughout the component tree.

Capabilities

Web3 Configuration Provider Component

The main React component that provides Web3 context to child components.

/**
 * React context provider for Web3 configuration and state management
 */
const Web3ConfigProvider: React.FC<Web3ConfigProviderProps>;

/**
 * Props interface for Web3ConfigProvider component
 */
interface Web3ConfigProviderProps extends UniversalWeb3ProviderInterface {
  /** Child React components that will have access to Web3 context */
  children?: React.ReactNode;
  /** Optional locale configuration for internationalization */
  locale?: Locale;
}

Configuration Context

React context for accessing Web3 configuration from child components.

/**
 * React context for Web3 configuration
 * Provides access to Web3 state and locale information
 */
const ConfigContext: React.Context<ConfigConsumerProps>;

/**
 * Context consumer props interface
 */
interface ConfigConsumerProps extends UniversalWeb3ProviderInterface {
  /** Optional locale overrides */
  locale?: Locale;
  /** Default locale configuration */
  defaultLocale: RequiredLocale;
}

Usage Examples

Basic Provider Setup

import React from 'react';
import { Web3ConfigProvider, ChainIds, type Chain } from '@ant-design/web3-common';

// Define your Web3 configuration
const ethereumChain: Chain = {
  id: ChainIds.Mainnet,
  name: "Ethereum Mainnet",
  nativeCurrency: {
    name: "Ether",
    symbol: "ETH",
    decimals: 18
  }
};

function App() {
  return (
    <Web3ConfigProvider
      chain={ethereumChain}
      availableChains={[
        ethereumChain,
        {
          id: ChainIds.Polygon,
          name: "Polygon",
          nativeCurrency: {
            name: "MATIC",
            symbol: "MATIC",
            decimals: 18
          }
        }
      ]}
    >
      <MainContent />
    </Web3ConfigProvider>
  );
}

Provider with Wallet Integration

import React, { useState } from 'react';
import { 
  Web3ConfigProvider, 
  type Account, 
  type Chain, 
  type Wallet 
} from '@ant-design/web3-common';

function Web3App() {
  const [account, setAccount] = useState<Account | undefined>();
  const [currentChain, setCurrentChain] = useState<Chain | undefined>();
  const [balance, setBalance] = useState<Balance | undefined>();

  const availableWallets: Wallet[] = [
    {
      name: "MetaMask",
      remark: "Connect using MetaMask",
      key: "metamask",
      hasWalletReady: async () => {
        return typeof window !== 'undefined' && 'ethereum' in window;
      }
    }
  ];

  const handleConnect = async (wallet?: Wallet) => {
    try {
      // Your wallet connection logic
      console.log('Connecting to wallet:', wallet?.name);
      
      // Update state after successful connection
      setAccount({
        address: "0x742d35cc6634c0532925a3b8d6ac013bbce29cd4",
        name: "My Wallet"
      });
    } catch (error) {
      console.error('Connection failed:', error);
    }
  };

  const handleDisconnect = async () => {
    setAccount(undefined);
    setCurrentChain(undefined);
    setBalance(undefined);
  };

  const handleSwitchChain = async (chain: Chain) => {
    try {
      // Your chain switching logic
      console.log('Switching to chain:', chain.name);
      setCurrentChain(chain);
      setBalance(undefined); // Reset balance for new chain
    } catch (error) {
      console.error('Chain switch failed:', error);
    }
  };

  return (
    <Web3ConfigProvider
      account={account}
      chain={currentChain}
      balance={balance}
      availableWallets={availableWallets}
      connect={handleConnect}
      disconnect={handleDisconnect}
      switchChain={handleSwitchChain}
    >
      <WalletInterface />
      <ChainSelector />
      <UserBalance />
    </Web3ConfigProvider>
  );
}

Provider with Internationalization

import React from 'react';
import { 
  Web3ConfigProvider, 
  zh_CN, 
  type Locale 
} from '@ant-design/web3-common';

// Custom locale overrides
const customLocale: Locale = {
  ConnectButton: {
    connect: "连接我的钱包",
    disconnect: "断开连接"
  }
};

function LocalizedApp() {
  return (
    <Web3ConfigProvider
      locale={customLocale}
      // ... other props
    >
      <LocalizedComponents />
    </Web3ConfigProvider>
  );
}

// Component that uses the context
function LocalizedComponents() {
  const { locale, defaultLocale } = useContext(ConfigContext);
  
  const connectText = locale?.ConnectButton?.connect || 
                     defaultLocale.ConnectButton.connect;
  
  return <button>{connectText}</button>;
}

Consuming Context in Child Components

import React, { useContext } from 'react';
import { ConfigContext } from '@ant-design/web3-common';

function WalletStatus() {
  const { 
    account, 
    chain, 
    balance, 
    connect, 
    disconnect, 
    availableChains,
    defaultLocale 
  } = useContext(ConfigContext);

  if (!account) {
    return (
      <button onClick={() => connect?.()}>
        {defaultLocale.ConnectButton.connect}
      </button>
    );
  }

  return (
    <div>
      <h3>Wallet Connected</h3>
      <p>Address: {account.address}</p>
      {account.name && <p>Name: {account.name}</p>}
      {chain && <p>Chain: {chain.name}</p>}
      {balance && (
        <p>
          Balance: {balance.value?.toString()} {balance.symbol}
        </p>
      )}
      
      <button onClick={() => disconnect?.()}>
        {defaultLocale.ConnectButton.disconnect}
      </button>
      
      {availableChains && availableChains.length > 1 && (
        <ChainSwitcher chains={availableChains} />
      )}
    </div>
  );
}

function ChainSwitcher({ chains }: { chains: Chain[] }) {
  const { switchChain, chain } = useContext(ConfigContext);

  return (
    <select
      value={chain?.id || ''}
      onChange={(e) => {
        const selectedChain = chains.find(c => c.id.toString() === e.target.value);
        if (selectedChain) {
          switchChain?.(selectedChain);
        }
      }}
    >
      <option value="">Select Chain</option>
      {chains.map((chainOption) => (
        <option key={chainOption.id} value={chainOption.id}>
          {chainOption.name}
        </option>
      ))}
    </select>
  );
}

Custom Hook for Context Access

import { useContext } from 'react';
import { ConfigContext } from '@ant-design/web3-common';

/**
 * Custom hook for accessing Web3 configuration context
 */
function useWeb3Config() {
  const context = useContext(ConfigContext);
  
  if (!context) {
    throw new Error('useWeb3Config must be used within a Web3ConfigProvider');
  }
  
  return context;
}

// Usage in components
function MyComponent() {
  const { account, connect, disconnect, defaultLocale } = useWeb3Config();
  
  return (
    <div>
      {account ? (
        <div>
          <span>Connected: {account.address}</span>
          <button onClick={() => disconnect?.()}>
            {defaultLocale.ConnectButton.disconnect}
          </button>
        </div>
      ) : (
        <button onClick={() => connect?.()}>
          {defaultLocale.ConnectButton.connect}
        </button>
      )}
    </div>
  );
}

Provider with NFT Support

import React, { useState } from 'react';
import { 
  Web3ConfigProvider, 
  type NFTMetadata 
} from '@ant-design/web3-common';

function NFTApp() {
  const [nftMetadata, setNftMetadata] = useState<NFTMetadata | null>(null);

  const handleGetNFTMetadata = async (params: { 
    address: string; 
    tokenId: bigint 
  }) => {
    try {
      // Your NFT metadata fetching logic
      const response = await fetch(
        `/api/nft/${params.address}/${params.tokenId}`
      );
      const metadata = await response.json();
      setNftMetadata(metadata);
      return metadata;
    } catch (error) {
      console.error('Failed to fetch NFT metadata:', error);
      throw error;
    }
  };

  return (
    <Web3ConfigProvider
      getNFTMetadata={handleGetNFTMetadata}
      // ... other props
    >
      <NFTViewer />
    </Web3ConfigProvider>
  );
}

function NFTViewer() {
  const { getNFTMetadata } = useContext(ConfigContext);
  const [metadata, setMetadata] = useState<NFTMetadata | null>(null);

  const loadNFT = async () => {
    if (getNFTMetadata) {
      try {
        const nftData = await getNFTMetadata({
          address: "0x...",
          tokenId: 123n
        });
        setMetadata(nftData);
      } catch (error) {
        console.error('Error loading NFT:', error);
      }
    }
  };

  return (
    <div>
      <button onClick={loadNFT}>Load NFT</button>
      {metadata && (
        <div>
          <h3>{metadata.name}</h3>
          <p>{metadata.description}</p>
          {metadata.image && <img src={metadata.image} alt={metadata.name} />}
        </div>
      )}
    </div>
  );
}

The Web3ConfigProvider component serves as the central hub for Web3 state management in React applications, providing a clean and consistent way to access wallet connections, chain information, and localization throughout your component tree.