Перейти к основному содержанию

Параметры

mint
string
обязательно
Открытый ключ монетного двора токена (в кодировке base-58)
config
object
Объект конфигурации, содержащий:
commitment
string
Уровень подтверждения (processed, confirmed, finalized)

Ответ

result
object
Объект, содержащий:
context
object
slot
number
Слот, в котором был обработан запрос
value
object
amount
string
Необработанное количество токенов в виде строки
decimals
number
Количество десятичных знаков, настроенных для монетного двора токена
uiAmount
number
Количество токенов в виде числа с плавающей точкой с учётом десятичных знаков
uiAmountString
string
Количество токенов в виде строки с учётом десятичных знаков

Примеры кода

Базовый запрос

curl https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY -X POST -H "Content-Type: application/json" -d '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getTokenSupply",
  "params": [
    "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
  ]
}'

Использование web3.js

import { Connection, PublicKey } from '@solana/web3.js';

const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY');

// Get token supply
const mint = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');
const supply = await connection.getTokenSupply(mint);
console.log('Token supply:', supply);

// Get token supply with analysis
async function getTokenSupplyWithAnalysis(
  mint: PublicKey,
  config: { commitment?: string }
) {
  const supply = await connection.getTokenSupply(mint, config);
  
  return {
    supply,
    analysis: {
      rawAmount: BigInt(supply.value.amount),
      formattedAmount: supply.value.uiAmountString,
      decimals: supply.value.decimals,
      metadata: {
        timestamp: Date.now(),
        commitment: config.commitment
      }
    }
  };
}

Примечания

  1. Возвращает общее предложение токенов монетного двора
  2. Предложение включает все токены в обращении
  3. Ответ приходит немедленно, так как читается из текущего состояния
  4. Предложение может изменяться при чеканке и сжигании токенов
  5. Монетный двор должен быть действительным токеновым монетным двором

Рекомендации

  1. Используйте подходящий уровень подтверждения в зависимости от ваших потребностей
  2. Кэшируйте результаты там, где это уместно, для снижения нагрузки на RPC
  3. Отслеживайте изменения в предложении токенов
  4. Рассмотрите использование подписки на websocket для обновлений в реальном времени
  5. Обрабатывайте сетевые ошибки и выполняйте повторные попытки при необходимости

Распространённые ошибки

КодСообщениеРешение
-32601Method not foundУбедитесь, что вы подключены к узлу Solana RPC
-32602Invalid paramsПроверьте открытый ключ монетного двора и конфигурацию
-32007Mint not foundУбедитесь, что монетный двор существует

Сценарии использования

  1. Анализ предложения токенов
    interface TokenSupplyAnalysis {
      mint: string;
      supply: {
        rawAmount: string;
        formattedAmount: string;
        decimals: number;
      };
      metrics: {
        maxSupply?: string;
        burnedAmount?: string;
        circulatingSupply?: string;
        inflationRate?: number;
      };
      metadata: {
        timestamp: number;
        commitment?: string;
      };
    }
    
    class TokenSupplyAnalyzer {
      private readonly maxSupply: Record<string, bigint> = {
        'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v': BigInt(1000000000000000) // USDC
      };
      
      async analyzeTokenSupply(
        mint: PublicKey,
        config: { commitment?: string }
      ): Promise<TokenSupplyAnalysis> {
        const supply = await connection.getTokenSupply(mint, config);
        const rawAmount = BigInt(supply.value.amount);
        const maxSupply = this.maxSupply[mint.toBase58()];
        
        return {
          mint: mint.toBase58(),
          supply: {
            rawAmount: supply.value.amount,
            formattedAmount: supply.value.uiAmountString!,
            decimals: supply.value.decimals
          },
          metrics: {
            maxSupply: maxSupply?.toString(),
            burnedAmount: maxSupply ? (maxSupply - rawAmount).toString() : undefined,
            circulatingSupply: supply.value.uiAmountString,
            inflationRate: maxSupply ? Number((rawAmount * BigInt(100)) / maxSupply) : undefined
          },
          metadata: {
            timestamp: Date.now(),
            commitment: config.commitment
          }
        };
      }
    }
    
  2. Мониторинг предложения токенов
    interface TokenSupplyChange {
      mint: string;
      changes: {
        previousAmount: string;
        currentAmount: string;
        difference: string;
        percentageChange: number;
      };
      metadata: {
        timestamp: number;
      };
    }
    
    class TokenSupplyMonitor {
      private previousSupply: Map<string, string> = new Map();
      
      async monitorTokenSupply(
        mint: PublicKey,
        config: { commitment?: string }
      ): Promise<TokenSupplyChange | null> {
        const supply = await connection.getTokenSupply(mint, config);
        const currentAmount = supply.value.amount;
        const previousAmount = this.previousSupply.get(mint.toBase58());
        
        if (previousAmount && previousAmount !== currentAmount) {
          const difference = BigInt(currentAmount) - BigInt(previousAmount);
          const percentageChange = Number((difference * BigInt(100)) / BigInt(previousAmount));
          
          this.previousSupply.set(mint.toBase58(), currentAmount);
          
          return {
            mint: mint.toBase58(),
            changes: {
              previousAmount,
              currentAmount,
              difference: difference.toString(),
              percentageChange
            },
            metadata: {
              timestamp: Date.now()
            }
          };
        }
        
        this.previousSupply.set(mint.toBase58(), currentAmount);
        return null;
      }
    }
    
  3. Планирование предложения токенов
    interface TokenSupplyPlan {
      mint: string;
      currentSupply: {
        rawAmount: string;
        formattedAmount: string;
        decimals: number;
      };
      recommendations: Array<{
        type: 'mint' | 'burn' | 'freeze';
        amount?: string;
        reason: string;
      }>;
      metadata: {
        timestamp: number;
      };
    }
    
    class TokenSupplyPlanner {
      private readonly targetInflationRate = 0.02; // 2% annual inflation
      private readonly maxSupply: Record<string, bigint> = {
        'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v': BigInt(1000000000000000) // USDC
      };
      
      async planTokenSupply(
        mint: PublicKey,
        config: { commitment?: string }
      ): Promise<TokenSupplyPlan> {
        const supply = await connection.getTokenSupply(mint, config);
        const rawAmount = BigInt(supply.value.amount);
        const maxSupply = this.maxSupply[mint.toBase58()];
        
        const recommendations: Array<{
          type: 'mint' | 'burn' | 'freeze';
          amount?: string;
          reason: string;
        }> = [];
        
        if (maxSupply) {
          const currentInflationRate = Number((rawAmount * BigInt(100)) / maxSupply) / 100;
          const targetAmount = maxSupply * BigInt(Math.floor(this.targetInflationRate * 100)) / BigInt(100);
          
          if (currentInflationRate > this.targetInflationRate) {
            const burnAmount = rawAmount - targetAmount;
            recommendations.push({
              type: 'burn',
              amount: burnAmount.toString(),
              reason: `Current inflation rate (${(currentInflationRate * 100).toFixed(2)}%) exceeds target (${(this.targetInflationRate * 100).toFixed(2)}%)`
            });
          } else if (currentInflationRate < this.targetInflationRate) {
            const mintAmount = targetAmount - rawAmount;
            recommendations.push({
              type: 'mint',
              amount: mintAmount.toString(),
              reason: `Current inflation rate (${(currentInflationRate * 100).toFixed(2)}%) below target (${(this.targetInflationRate * 100).toFixed(2)}%)`
            });
          }
        }
        
        return {
          mint: mint.toBase58(),
          currentSupply: {
            rawAmount: supply.value.amount,
            formattedAmount: supply.value.uiAmountString!,
            decimals: supply.value.decimals
          },
          recommendations,
          metadata: {
            timestamp: Date.now()
          }
        };
      }
    }