API
Code Examples

Code Examples

Ready-to-use code samples for integrating Digifi API into your applications.

Complete Examples

Node.js / Express Server

// server.js
require('dotenv').config();
const express = require('express');
const axios = require('axios');
 
const app = express();
app.use(express.json());
 
const DIGIFI_API_KEY = process.env.DIGIFI_API_KEY;
const DIGIFI_API_URL = 'https://api.digifi.fun';
 
// Deploy token endpoint
app.post('/api/deploy', async (req, res) => {
  const { name, symbol } = req.body;
  
  if (!name || !symbol) {
    return res.status(400).json({ error: 'Name and symbol required' });
  }
  
  try {
    const response = await axios.post(
      `${DIGIFI_API_URL}/deployToken`,
      {
        name,
        symbol,
        chain_id: '8453',
        apiKey: DIGIFI_API_KEY
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${DIGIFI_API_KEY}`
        }
      }
    );
    
    res.json(response.data);
  } catch (error) {
    console.error('Deployment error:', error.response?.data || error.message);
    res.status(500).json({
      error: 'Deployment failed',
      details: error.response?.data
    });
  }
});
 
// Check rewards endpoint
app.get('/api/rewards/:tokenAddress', async (req, res) => {
  const { tokenAddress } = req.params;
  
  try {
    const response = await axios.get(`${DIGIFI_API_URL}/checkRewards`, {
      params: {
        tokenAddress,
        apiKey: DIGIFI_API_KEY
      },
      headers: {
        'Authorization': `Bearer ${DIGIFI_API_KEY}`
      }
    });
    
    res.json(response.data);
  } catch (error) {
    console.error('Rewards check error:', error.response?.data || error.message);
    res.status(500).json({
      error: 'Failed to check rewards',
      details: error.response?.data
    });
  }
});
 
// Claim rewards endpoint
app.post('/api/claim/:tokenAddress', async (req, res) => {
  const { tokenAddress } = req.params;
  
  try {
    const response = await axios.post(
      `${DIGIFI_API_URL}/claim`,
      {
        tokenAddress,
        apiKey: DIGIFI_API_KEY
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${DIGIFI_API_KEY}`
        }
      }
    );
    
    res.json(response.data);
  } catch (error) {
    console.error('Claim error:', error.response?.data || error.message);
    res.status(500).json({
      error: 'Failed to claim rewards',
      details: error.response?.data
    });
  }
});
 
app.listen(3000, () => {
  console.log('Server running on port 3000');
});

React Application

// DigifiAPI.ts
import axios, { AxiosInstance } from 'axios';
 
export class DigifiAPI {
  private client: AxiosInstance;
  private apiKey: string;
 
  constructor(apiKey: string) {
    this.apiKey = apiKey;
    this.client = axios.create({
      baseURL: 'https://api.digifi.fun',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      }
    });
  }
 
  async deployToken(name: string, symbol: string) {
    const response = await this.client.post('/deployToken', {
      name,
      symbol,
      chain_id: '8453',
      apiKey: this.apiKey
    });
    return response.data;
  }
 
  async checkRewards(tokenAddress: string) {
    const response = await this.client.get('/checkRewards', {
      params: {
        tokenAddress,
        apiKey: this.apiKey
      }
    });
    return response.data;
  }
 
  async claimRewards(tokenAddress: string) {
    const response = await this.client.post('/claim', {
      tokenAddress,
      apiKey: this.apiKey
    });
    return response.data;
  }
 
  async getUserDeploymentCount() {
    const response = await this.client.get('/user-deployment-count', {
      params: {
        apiKey: this.apiKey
      }
    });
    return response.data;
  }
}
 
// TokenDeployForm.tsx
import React, { useState } from 'react';
import { DigifiAPI } from './DigifiAPI';
 
const api = new DigifiAPI(process.env.REACT_APP_DIGIFI_API_KEY!);
 
export const TokenDeployForm: React.FC = () => {
  const [name, setName] = useState('');
  const [symbol, setSymbol] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResult(null);
 
    try {
      const data = await api.deployToken(name, symbol);
      
      if (data.success) {
        setResult(data);
      } else {
        setError(data.error || 'Deployment failed');
      }
    } catch (err: any) {
      setError(err.response?.data?.error || err.message);
    } finally {
      setLoading(false);
    }
  };
 
  return (
    <div className="token-deploy-form">
      <h2>Deploy Token</h2>
      
      <form onSubmit={handleSubmit}>
        <div>
          <label>Token Name:</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
        </div>
        
        <div>
          <label>Token Symbol:</label>
          <input
            type="text"
            value={symbol}
            onChange={(e) => setSymbol(e.target.value.toUpperCase())}
            maxLength={10}
            required
          />
        </div>
        
        <button type="submit" disabled={loading}>
          {loading ? 'Deploying...' : 'Deploy Token'}
        </button>
      </form>
      
      {error && (
        <div className="error">
          <h3>Error</h3>
          <p>{error}</p>
        </div>
      )}
      
      {result && (
        <div className="success">
          <h3>Token Deployed Successfully!</h3>
          <p><strong>Token Address:</strong> {result.data.tokenAddress}</p>
          <p><strong>Explorer:</strong> <a href={result.data.explorerUrl} target="_blank">View on Basescan</a></p>
        </div>
      )}
    </div>
  );
};
 
// RewardsMonitor.tsx
import React, { useEffect, useState } from 'react';
import { DigifiAPI } from './DigifiAPI';
 
const api = new DigifiAPI(process.env.REACT_APP_DIGIFI_API_KEY!);
 
interface RewardsMonitorProps {
  tokenAddress: string;
}
 
export const RewardsMonitor: React.FC<RewardsMonitorProps> = ({ tokenAddress }) => {
  const [rewards, setRewards] = useState<any>(null);
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    const fetchRewards = async () => {
      try {
        const data = await api.checkRewards(tokenAddress);
        setRewards(data);
      } catch (error) {
        console.error('Failed to fetch rewards:', error);
      } finally {
        setLoading(false);
      }
    };
 
    fetchRewards();
    
    // Refresh every 30 seconds
    const interval = setInterval(fetchRewards, 30000);
    
    return () => clearInterval(interval);
  }, [tokenAddress]);
 
  if (loading) return <div>Loading rewards...</div>;
  if (!rewards) return <div>Failed to load rewards</div>;
 
  return (
    <div className="rewards-monitor">
      <h3>{rewards.tokenName} ({rewards.tokenSymbol})</h3>
      
      {rewards.lpInitialized ? (
        <div>
          <h4>Pending Rewards</h4>
          <p>Token Fees: {rewards.pendingRewards.tokenRewards} {rewards.tokenSymbol}</p>
          <p>ETH Fees: {rewards.pendingRewards.ethRewards} ETH</p>
          
          <h4>Fee Recipients</h4>
          <p>Creator: {rewards.pendingRewards.feeReceiver}</p>
          <p>Platform: {rewards.pendingRewards.factoryCreator}</p>
        </div>
      ) : (
        <p>LP not yet initialized</p>
      )}
    </div>
  );
};

Python Flask Application

# app.py
from flask import Flask, request, jsonify
import requests
import os
from dotenv import load_dotenv
 
load_dotenv()
 
app = Flask(__name__)
 
DIGIFI_API_KEY = os.getenv('DIGIFI_API_KEY')
DIGIFI_API_URL = 'https://api.digifi.fun'
 
class DigifiAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {api_key}'
        }
    
    def deploy_token(self, name, symbol):
        response = requests.post(
            f'{DIGIFI_API_URL}/deployToken',
            headers=self.headers,
            json={
                'name': name,
                'symbol': symbol,
                'chain_id': '8453',
                'apiKey': self.api_key
            }
        )
        return response.json()
    
    def check_rewards(self, token_address):
        response = requests.get(
            f'{DIGIFI_API_URL}/checkRewards',
            headers=self.headers,
            params={
                'tokenAddress': token_address,
                'apiKey': self.api_key
            }
        )
        return response.json()
    
    def claim_rewards(self, token_address):
        response = requests.post(
            f'{DIGIFI_API_URL}/claim',
            headers=self.headers,
            json={
                'tokenAddress': token_address,
                'apiKey': self.api_key
            }
        )
        return response.json()
    
    def get_deployment_count(self):
        response = requests.get(
            f'{DIGIFI_API_URL}/user-deployment-count',
            headers=self.headers,
            params={'apiKey': self.api_key}
        )
        return response.json()
 
api = DigifiAPI(DIGIFI_API_KEY)
 
@app.route('/api/deploy', methods=['POST'])
def deploy():
    data = request.json
    name = data.get('name')
    symbol = data.get('symbol')
    
    if not name or not symbol:
        return jsonify({'error': 'Name and symbol required'}), 400
    
    try:
        result = api.deploy_token(name, symbol)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500
 
@app.route('/api/rewards/<token_address>', methods=['GET'])
def check_rewards(token_address):
    try:
        result = api.check_rewards(token_address)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500
 
@app.route('/api/claim/<token_address>', methods=['POST'])
def claim_rewards(token_address):
    try:
        result = api.claim_rewards(token_address)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500
 
@app.route('/api/usage', methods=['GET'])
def get_usage():
    try:
        result = api.get_deployment_count()
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500
 
if __name__ == '__main__':
    app.run(debug=True, port=5000)

Next.js API Routes

// pages/api/deploy.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import axios from 'axios';
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }
 
  const { name, symbol } = req.body;
 
  if (!name || !symbol) {
    return res.status(400).json({ error: 'Name and symbol required' });
  }
 
  try {
    const response = await axios.post(
      'https://api.digifi.fun/deployToken',
      {
        name,
        symbol,
        chain_id: '8453',
        apiKey: process.env.DIGIFI_API_KEY
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.DIGIFI_API_KEY}`
        }
      }
    );
 
    res.status(200).json(response.data);
  } catch (error: any) {
    res.status(500).json({
      error: 'Deployment failed',
      details: error.response?.data
    });
  }
}
 
// pages/api/rewards/[tokenAddress].ts
import type { NextApiRequest, NextApiResponse } from 'next';
import axios from 'axios';
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }
 
  const { tokenAddress } = req.query;
 
  if (!tokenAddress || typeof tokenAddress !== 'string') {
    return res.status(400).json({ error: 'Token address required' });
  }
 
  try {
    const response = await axios.get(
      'https://api.digifi.fun/checkRewards',
      {
        params: {
          tokenAddress,
          apiKey: process.env.DIGIFI_API_KEY
        },
        headers: {
          'Authorization': `Bearer ${process.env.DIGIFI_API_KEY}`
        }
      }
    );
 
    res.status(200).json(response.data);
  } catch (error: any) {
    res.status(500).json({
      error: 'Failed to check rewards',
      details: error.response?.data
    });
  }
}

Utility Functions

Rate Limiter

class RateLimiter {
  constructor(requestsPerMinute = 60) {
    this.requestsPerMinute = requestsPerMinute;
    this.requests = [];
  }
 
  async wait() {
    const now = Date.now();
    this.requests = this.requests.filter(time => now - time < 60000);
 
    if (this.requests.length >= this.requestsPerMinute) {
      const oldestRequest = Math.min(...this.requests);
      const waitTime = 60000 - (now - oldestRequest);
      
      if (waitTime > 0) {
        await new Promise(resolve => setTimeout(resolve, waitTime));
        return this.wait();
      }
    }
 
    this.requests.push(now);
  }
}
 
// Usage
const rateLimiter = new RateLimiter(60);
 
const deployToken = async (name, symbol) => {
  await rateLimiter.wait();
  // Make API call
};

Retry with Exponential Backoff

async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      const waitTime = Math.pow(2, i) * 1000;
      console.log(`Retry ${i + 1} after ${waitTime}ms`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
}
 
// Usage
const result = await retryWithBackoff(() => 
  deployToken('MyToken', 'MTK')
);

Batch Deployment

async function batchDeploy(tokens, concurrency = 5) {
  const results = [];
  
  for (let i = 0; i < tokens.length; i += concurrency) {
    const batch = tokens.slice(i, i + concurrency);
    
    const batchResults = await Promise.allSettled(
      batch.map(token => deployToken(token.name, token.symbol))
    );
    
    results.push(...batchResults);
    
    // Wait between batches to respect rate limits
    if (i + concurrency < tokens.length) {
      await new Promise(resolve => setTimeout(resolve, 60000));
    }
  }
  
  return results;
}
 
// Usage
const tokens = [
  { name: 'Token 1', symbol: 'TK1' },
  { name: 'Token 2', symbol: 'TK2' },
  // ... more tokens
];
 
const results = await batchDeploy(tokens);

Testing Examples

Jest Test Suite

// digifi-api.test.js
const axios = require('axios');
const { DigifiAPI } = require('./digifi-api');
 
jest.mock('axios');
 
describe('DigifiAPI', () => {
  let api;
 
  beforeEach(() => {
    api = new DigifiAPI('test_api_key');
  });
 
  describe('deployToken', () => {
    it('should deploy token successfully', async () => {
      const mockResponse = {
        data: {
          success: true,
          data: {
            tokenAddress: '0x123',
            poolAddress: '0x456'
          }
        }
      };
 
      axios.post.mockResolvedValue(mockResponse);
 
      const result = await api.deployToken('TestToken', 'TEST');
 
      expect(result.success).toBe(true);
      expect(result.data.tokenAddress).toBe('0x123');
    });
 
    it('should handle deployment errors', async () => {
      axios.post.mockRejectedValue(new Error('Deployment failed'));
 
      await expect(api.deployToken('TestToken', 'TEST')).rejects.toThrow();
    });
  });
 
  describe('checkRewards', () => {
    it('should check rewards successfully', async () => {
      const mockResponse = {
        data: {
          success: true,
          lpInitialized: true,
          pendingRewards: {
            tokenRewards: '10.5',
            ethRewards: '0.001'
          }
        }
      };
 
      axios.get.mockResolvedValue(mockResponse);
 
      const result = await api.checkRewards('0x123');
 
      expect(result.success).toBe(true);
      expect(result.lpInitialized).toBe(true);
    });
  });
});

Environment Configuration

.env.example

# Digifi API Configuration
DIGIFI_API_KEY=dg_YOUR_API_KEY_HERE
DIGIFI_API_URL=https://api.digifi.fun
 
# Optional: Custom timeout (milliseconds)
API_TIMEOUT=120000
 
# Optional: Enable debug logging
DEBUG=false

More Examples

For additional examples and integration patterns:


Need help with integration? Contact us at digifievm999@gmail.com