Skip to content

API Examples & Code Samples

Comprehensive code examples for integrating with the AllowanceGuard API in multiple programming languages and frameworks.

cURL Examples

Command-line examples for testing the API directly.

curl -X GET "https://www.allowanceguard.com/api/allowances?wallet=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045&page=1&pageSize=25" \
  -H "Accept: application/json"

JavaScript/Node.js

Vanilla JavaScript examples for both browser and Node.js environments.

// Fetch allowances for a wallet
async function getAllowances(walletAddress) {
  try {
    const response = await fetch(
      `https://www.allowanceguard.com/api/allowances?wallet=${walletAddress}&page=1&pageSize=25`,
      {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      }
    )
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error fetching allowances:', error)
    throw error
  }
}

// Usage
getAllowances('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
  .then(allowances => {
    console.log('Allowances:', allowances)
    allowances.data.forEach(allowance => {
      console.log(`Token: ${allowance.tokenName}, Spender: ${allowance.spenderName}, Risk: ${allowance.riskLevel}`)
    })
  })
  .catch(error => {
    console.error('Failed to fetch allowances:', error)
  })

Python

Python examples using the requests library for API integration.

import requests
import json

def get_allowances(wallet_address, page=1, page_size=25):
    """
    Fetch token allowances for a given wallet address
    """
    url = "https://www.allowanceguard.com/api/allowances"
    params = {
        'wallet': wallet_address,
        'page': page,
        'pageSize': page_size
    }
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.get(url, params=params, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error fetching allowances: {e}")
        raise

def get_risk_assessment(wallet_address, token_address, spender_address, chain_id=1):
    """
    Get risk assessment for a specific token approval
    """
    url = "https://www.allowanceguard.com/api/risk/assess"
    data = {
        'walletAddress': wallet_address,
        'tokenAddress': token_address,
        'spenderAddress': spender_address,
        'chainId': chain_id
    }
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.post(url, json=data, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error assessing risk: {e}")
        raise

# Usage examples
if __name__ == "__main__":
    wallet = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
    
    # Get all allowances
    allowances = get_allowances(wallet)
    print(f"Found {len(allowances['data'])} allowances")
    
    # Assess risk for a specific approval
    risk = get_risk_assessment(
        wallet,
        "0xA0b86a33E6441b8c4C8C0C8C0C8C0C8C0C8C0C8C",
        "0x1234567890123456789012345678901234567890"
    )
    print(f"Risk level: {risk['riskLevel']}")

React Component

React component example for displaying allowances in a web application.

import React, { useState, useEffect } from 'react'

function AllowanceChecker({ walletAddress }) {
  const [allowances, setAllowances] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  useEffect(() => {
    if (!walletAddress) return

    const fetchAllowances = async () => {
      setLoading(true)
      setError(null)
      
      try {
        const response = await fetch(
          `https://www.allowanceguard.com/api/allowances?wallet=${walletAddress}&page=1&pageSize=25`,
          {
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            }
          }
        )
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        setAllowances(data.data || [])
      } catch (err) {
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }

    fetchAllowances()
  }, [walletAddress])

  if (loading) return <div>Loading allowances...</div>
  if (error) return <div>Error: {error}</div>

  return (
    <div>
      <h3>Token Allowances for {walletAddress}</h3>
      <div className="space-y-4">
        {allowances.map((allowance, index) => (
          <div key={index} className="border p-4 rounded-lg">
            <div className="flex justify-between items-start">
              <div>
                <h4 className="font-semibold">{allowance.tokenName}</h4>
                <p className="text-sm text-gray-600">Spender: {allowance.spenderName}</p>
                <p className="text-sm text-gray-600">Amount: {allowance.allowance}</p>
              </div>
              <span className={`px-2 py-1 rounded text-xs font-medium ${
                allowance.riskLevel >= 3 ? 'bg-red-100 text-red-800' :
                allowance.riskLevel >= 2 ? 'bg-yellow-100 text-yellow-800' :
                'bg-green-100 text-green-800'
              }`}>
                Risk Level {allowance.riskLevel}
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default AllowanceChecker

Node.js SDK Class

Complete Node.js SDK class for easy integration into backend services.

const axios = require('axios')

class AllowanceGuardAPI {
  constructor(apiKey = null) {
    this.baseURL = 'https://www.allowanceguard.com/api'
    this.headers = {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
    
    if (apiKey) {
      this.headers['Authorization'] = `Bearer ${apiKey}`
    }
  }

  async getAllowances(walletAddress, options = {}) {
    const params = {
      wallet: walletAddress,
      page: options.page || 1,
      pageSize: options.pageSize || 25,
      ...options
    }

    try {
      const response = await axios.get(`${this.baseURL}/allowances`, {
        params,
        headers: this.headers
      })
      return response.data
    } catch (error) {
      throw new Error(`Failed to fetch allowances: ${error.message}`)
    }
  }

  async assessRisk(walletAddress, tokenAddress, spenderAddress, chainId = 1) {
    const data = {
      walletAddress,
      tokenAddress,
      spenderAddress,
      chainId
    }

    try {
      const response = await axios.post(`${this.baseURL}/risk/assess`, data, {
        headers: this.headers
      })
      return response.data
    } catch (error) {
      throw new Error(`Failed to assess risk: ${error.message}`)
    }
  }

  async getNetworks() {
    try {
      const response = await axios.get(`${this.baseURL}/networks/roadmap`, {
        headers: this.headers
      })
      return response.data
    } catch (error) {
      throw new Error(`Failed to fetch networks: ${error.message}`)
    }
  }
}

// Usage
const api = new AllowanceGuardAPI()

async function main() {
  try {
    // Get allowances
    const allowances = await api.getAllowances('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
    console.log('Allowances:', allowances)

    // Assess risk
    const risk = await api.assessRisk(
      '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
      '0xA0b86a33E6441b8c4C8C0C8C0C8C0C8C0C8C0C8C',
      '0x1234567890123456789012345678901234567890'
    )
    console.log('Risk assessment:', risk)

    // Get supported networks
    const networks = await api.getNetworks()
    console.log('Supported networks:', networks)
  } catch (error) {
    console.error('Error:', error.message)
  }
}

main()

Integration Tips

Error Handling

Always implement proper error handling for network requests and API responses.

  • • Check HTTP status codes
  • • Handle rate limiting (429 status)
  • • Implement retry logic for transient failures
  • • Validate response data structure

Performance

Optimize your API usage for better performance and user experience.

  • • Use pagination for large datasets
  • • Implement client-side caching
  • • Batch requests when possible
  • • Use appropriate page sizes

Rate Limiting

Respect rate limits to ensure reliable API access.

  • • 5 requests per minute for public access
  • • Higher limits available with API key
  • • Implement exponential backoff
  • • Monitor rate limit headers

Security

Follow security best practices when integrating the API.

  • • Validate wallet addresses client-side
  • • Sanitize user inputs
  • • Use HTTPS for all requests
  • • Store API keys securely
Allowance Guard