Back to Reference
Code Examples

SDK Integration Examples

Real-world use cases for token creation

1. DAO Governance Token

Create governance tokens for a DAO platform where members vote on proposals.

Component: DAOTokenCreator.tsx

import { useState } from 'react';
import { useCurrentAccount } from '@mysten/dapp-kit';
import { SuiLabTokenCreatorSDK } from '@suilab/token-creator-sdk';

const sdk = new SuiLabTokenCreatorSDK(
  process.env.NEXT_PUBLIC_SUILAB_API_KEY!,
  {
    developerWallet: process.env.NEXT_PUBLIC_DEV_WALLET!,
    developerFee: 2,
    network: 'mainnet'
  }
);

export function DAOTokenCreator() {
  const account = useCurrentAccount();
  const [daoName, setDaoName] = useState('');
  const [supply, setSupply] = useState(1000000);
  const [isCreating, setIsCreating] = useState(false);

  const handleCreate = async () => {
    if (!account) return;
    
    setIsCreating(true);
    try {
      const result = await sdk.createNativeToken({
        name: `${daoName} Governance Token`,
        symbol: daoName.substring(0, 6).toUpperCase(),
        decimals: 9,
        totalSupply: supply,
        description: `Governance token for ${daoName} DAO. Holders can vote on proposals.`,
        userAddress: account.address,
        metadata: {
          type: 'governance',
          daoName: daoName
        }
      });

      alert(`Token created! ID: ${result.tokenId}`);
    } catch (error: any) {
      alert('Error: ' + error.message);
    } finally {
      setIsCreating(false);
    }
  };

  return (
    <div className="space-y-4">
      <input
        placeholder="DAO Name"
        value={daoName}
        onChange={(e) => setDaoName(e.target.value)}
        className="w-full px-4 py-2 border rounded"
      />
      <input
        type="number"
        placeholder="Total Supply"
        value={supply}
        onChange={(e) => setSupply(Number(e.target.value))}
        className="w-full px-4 py-2 border rounded"
      />
      <button
        onClick={handleCreate}
        disabled={!account || !daoName || isCreating}
        className="w-full px-4 py-3 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
      >
        {isCreating ? 'Creating...' : 'Create Governance Token'}
      </button>
    </div>
  );
}

2. Gaming Platform Currency

Create in-game currencies or reward tokens for a gaming platform.

Component: GameCurrencyCreator.tsx

import { SuiLabTokenCreatorSDK } from '@suilab/token-creator-sdk';
import { useCurrentAccount } from '@mysten/dapp-kit';

const sdk = new SuiLabTokenCreatorSDK(API_KEY, {
  developerWallet: DEV_WALLET,
  developerFee: 5,
  network: 'mainnet'
});

export function GameCurrencyCreator({ gameName }: { gameName: string }) {
  const account = useCurrentAccount();

  const createGameCurrency = async () => {
    if (!account) return;

    try {
      // First, check fees
      const fees = sdk.estimateFees();
      const confirmed = confirm(
        `Create game currency for ${fees.total} SUI?\n\n` +
        `Platform: ${fees.platformFee} SUI\n` +
        `Developer: ${fees.developerFee} SUI\n` +
        `Network: ${fees.networkFee} SUI`
      );

      if (!confirmed) return;

      const result = await sdk.createNativeToken({
        name: `${gameName} Coins`,
        symbol: 'GC',
        decimals: 6, // Gaming tokens often use fewer decimals
        totalSupply: 100_000_000, // 100M coins
        description: `In-game currency for ${gameName}. Earn by playing!`,
        userAddress: account.address,
        icon: 'https://game.example.com/coin-icon.png',
        metadata: {
          type: 'gaming',
          game: gameName,
          transferable: true
        }
      });

      console.log('Game currency created:', result);
      return result;
      
    } catch (error: any) {
      console.error('Creation failed:', error);
      throw error;
    }
  };

  return (
    <button onClick={createGameCurrency}>
      Create {gameName} Currency
    </button>
  );
}

3. NFT Marketplace Rewards

Create reward tokens for an NFT marketplace loyalty program.

Component: RewardTokenCreator.tsx

import { SuiLabTokenCreatorSDK, ValidationResult } from '@suilab/token-creator-sdk';

const sdk = new SuiLabTokenCreatorSDK(API_KEY, {
  developerWallet: MARKETPLACE_WALLET,
  developerFee: 1,
  network: 'mainnet'
});

export async function createMarketplaceRewards(
  userAddress: string,
  marketplaceName: string
) {
  // Validate parameters first
  const params = {
    name: `${marketplaceName} Rewards`,
    symbol: 'MKT',
    decimals: 9,
    totalSupply: 50_000_000,
    description: `Loyalty rewards for ${marketplaceName}. Earn by trading NFTs.`,
    userAddress,
  };

  const validation: ValidationResult = sdk.validateParams(params);
  
  if (!validation.isValid) {
    throw new Error(`Invalid params: ${validation.errors.join(', ')}`);
  }

  try {
    const result = await sdk.createNativeToken(params);
    
    // Log for analytics
    console.log('Marketplace rewards created:', {
      tokenId: result.tokenId,
      marketplace: marketplaceName,
      timestamp: Date.now()
    });

    // Return result for UI update
    return {
      success: true,
      tokenId: result.tokenId,
      txUrl: `https://suiscan.xyz/mainnet/tx/${result.digest}`
    };
    
  } catch (error: any) {
    return {
      success: false,
      error: error.message
    };
  }
}

4. Complete Form with Validation

Full token creation form with client-side validation.

Component: TokenCreationForm.tsx

import { useState } from 'react';
import { SuiLabTokenCreatorSDK } from '@suilab/token-creator-sdk';

const sdk = new SuiLabTokenCreatorSDK(API_KEY, CONFIG);

export function TokenCreationForm() {
  const [formData, setFormData] = useState({
    name: '',
    symbol: '',
    decimals: 9,
    supply: 1000000,
    description: ''
  });
  const [errors, setErrors] = useState<string[]>([]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData(prev => ({
      ...prev,
      [e.target.name]: e.target.value
    }));
  };

  const handleSubmit = async (e: React.FormEvent, userAddress: string) => {
    e.preventDefault();

    // Client-side validation
    const validation = sdk.validateParams({
      ...formData,
      totalSupply: Number(formData.supply),
      userAddress
    });

    if (!validation.isValid) {
      setErrors(validation.errors);
      return;
    }

    setErrors([]);

    try {
      const result = await sdk.createNativeToken({
        name: formData.name,
        symbol: formData.symbol.toUpperCase(),
        decimals: Number(formData.decimals),
        totalSupply: Number(formData.supply),
        description: formData.description,
        userAddress
      });

      alert('Token created successfully!');
      console.log(result);
      
    } catch (error: any) {
      setErrors([error.message]);
    }
  };

  return (
    <form className="space-y-4">
      {errors.length > 0 && (
        <div className="bg-red-50 border border-red-200 p-4 rounded">
          <h4 className="font-semibold text-red-900">Errors:</h4>
          <ul className="list-disc ml-5 text-red-700 text-sm">
            {errors.map((err, i) => <li key={i}>{err}</li>)}
          </ul>
        </div>
      )}

      <input
        name="name"
        placeholder="Token Name"
        value={formData.name}
        onChange={handleChange}
        className="w-full px-4 py-2 border rounded"
      />
      
      <input
        name="symbol"
        placeholder="Symbol (e.g., MTK)"
        value={formData.symbol}
        onChange={handleChange}
        className="w-full px-4 py-2 border rounded"
      />

      <input
        name="decimals"
        type="number"
        value={formData.decimals}
        onChange={handleChange}
        className="w-full px-4 py-2 border rounded"
      />

      <input
        name="supply"
        type="number"
        placeholder="Total Supply"
        value={formData.supply}
        onChange={handleChange}
        className="w-full px-4 py-2 border rounded"
      />

      <textarea
        name="description"
        placeholder="Description"
        value={formData.description}
        onChange={handleChange}
        rows={3}
        className="w-full px-4 py-2 border rounded"
      />

      <button
        type="submit"
        className="w-full px-4 py-3 bg-blue-600 text-white rounded hover:bg-blue-700"
      >
        Create Token
      </button>
    </form>
  );
}

5. Comprehensive Error Handling

async function createTokenWithErrorHandling(params) {
  try {
    // Validate first
    const validation = sdk.validateParams(params);
    if (!validation.isValid) {
      // Show specific validation errors to user
      showErrors(validation.errors);
      return;
    }

    // Show loading state
    setLoading(true);

    // Create token
    const result = await sdk.createNativeToken(params);

    // Success!
    showSuccess(`Token created! View on explorer: ${result.digest}`);
    return result;

  } catch (error: any) {
    // Handle different error types
    if (error.message.includes('Invalid API key')) {
      showError('API key error. Contact support.');
    } else if (error.message.includes('API Error')) {
      showError('Server error. Try again later.');
    } else if (error.message.includes('No response')) {
      showError('Network error. Check your connection.');
    } else {
      showError(`Unexpected error: ${error.message}`);
    }
  } finally {
    setLoading(false);
  }
}

📚 Additional Resources

Need help or found a bug? Contact us at support@suilab.fun