Code Examples

Real-world examples for common use cases.

Complete Wallet App

javascript
import { MemenChain } from '@memenchain/sdk';

class WalletApp {
  constructor(jwtToken) {
    this.client = new MemenChain({ jwtToken });
  }

  async getBalance(userId) {
    return await this.client.balance.get(userId);
  }

  async sendGems(from, to, amount) {
    const tx = await this.client.transactions.submit({
      from, to, amount, token: 'MGEM'
    });
    return tx;
  }

  async getTransactionHistory(userId) {
    return await this.client.transactions.list({ user: userId });
  }
}

// Usage
const wallet = new WalletApp(jwtToken);
const balance = await wallet.getBalance('user123');
const tx = await wallet.sendGems('user123', 'user456', 100);

Reward System

javascript
class RewardSystem {
  constructor(client) {
    this.client = client;
  }

  async rewardUser(userId, action, amount = 50) {
    const tx = await this.client.transactions.submit({
      from: 'system',
      to: userId,
      amount,
      token: 'MGEM',
      type: 'reward',
      metadata: { action }
    });
    return tx;
  }

  async rewardMultiple(userIds, action, amount = 50) {
    return Promise.all(
      userIds.map(id => this.rewardUser(id, action, amount))
    );
  }
}

// Usage
const rewards = new RewardSystem(client);
await rewards.rewardUser('user123', 'post_created', 100);
await rewards.rewardMultiple(['u1', 'u2', 'u3'], 'daily_login', 10);

Trading Bot

javascript
class TradingBot {
  constructor(client) {
    this.client = client;
  }

  async buyMGEM(userId, usdgAmount) {
    const mgem = Math.floor(usdgAmount / 0.015);
    return await this.client.transactions.submit({
      from: userId,
      to: 'treasury',
      amount: usdgAmount,
      token: 'USDG',
      type: 'buy',
      metadata: { mgem_amount: mgem }
    });
  }

  async sellMGEM(userId, mgemAmount) {
    const usdg = (mgemAmount * 0.015).toFixed(2);
    return await this.client.transactions.submit({
      from: userId,
      to: 'treasury',
      amount: mgemAmount,
      token: 'MGEM',
      type: 'sell',
      metadata: { usdg_amount: usdg }
    });
  }
}

// Usage
const bot = new TradingBot(client);
await bot.buyMGEM('user123', 10); // Buy with $10 USDG
await bot.sellMGEM('user123', 667); // Sell 667 MGEM

Analytics Dashboard

javascript
class Analytics {
  constructor(client) {
    this.client = client;
  }

  async getNetworkStats() {
    return await this.client.stats.get();
  }

  async getUserStats(userId) {
    const [balance, txs] = await Promise.all([
      this.client.balance.get(userId),
      this.client.transactions.list({ user: userId })
    ]);
    return {
      balance,
      transactionCount: txs.length,
      totalVolume: txs.reduce((sum, tx) => sum + tx.amount, 0)
    };
  }

  async getTopUsers(limit = 10) {
    const stats = await this.client.stats.get();
    return stats.topUsers.slice(0, limit);
  }
}

// Usage
const analytics = new Analytics(client);
const stats = await analytics.getNetworkStats();
const userStats = await analytics.getUserStats('user123');

Error Handling

javascript
async function safeTransaction(from, to, amount) {
  try {
    const tx = await client.transactions.submit({
      from, to, amount, token: 'MGEM'
    });
    console.log('Transaction successful:', tx.tx_hash);
    return tx;
  } catch (error) {
    switch (error.code) {
      case 'INSUFFICIENT_BALANCE':
        console.error('Insufficient balance');
        break;
      case 'INVALID_USER':
        console.error('Invalid recipient');
        break;
      case 'RATE_LIMIT':
        console.error('Rate limited, retry in 60s');
        await new Promise(r => setTimeout(r, 60000));
        return safeTransaction(from, to, amount);
      default:
        console.error('Unknown error:', error.message);
    }
    throw error;
  }
}