Docs

suix_getReferenceGasPrice - Get Current...

Get the current reference gas price on Sui blockchain. Essential for transaction cost estimation and gas optimization with Dwellir's high-performance Sui RPC infrastructure.

Returns the current reference gas price on the Sui network in MIST units.

Overview

The suix_getReferenceGasPrice method provides the current reference gas price used for transaction fee calculations on the Sui network. This price is set by the validator consensus and represents the minimum gas price that validators are willing to accept for transaction processing. Understanding the reference gas price is crucial for transaction cost estimation, gas optimization, and building cost-effective applications on Sui.

Code Examples

Common Use Cases

Gas Price Monitoring System

JavaScript
class GasPriceMonitoringSystem {
  constructor(client) {
    this.client = client;
    this.priceHistory = [];
    this.subscribers = [];
    this.thresholds = {
      lowPrice: 800,
      highPrice: 1500,
      priceChangePercent: 15
    };
  }
  
  async startMonitoring(interval = 60000) { // 1 minute default
    setInterval(async () => {
      try {
        const gasPrice = await this.client.getReferenceGasPrice();
        const priceData = {
          price: Number(gasPrice),
          timestamp: Date.now(),
          date: new Date().toISOString()
        };
        
        this.priceHistory.push(priceData);
        
        // Keep only last 24 hours
        const dayAgo = Date.now() - (24 * 60 * 60 * 1000);
        this.priceHistory = this.priceHistory.filter(p => p.timestamp > dayAgo);
        
        // Check for alerts
        this.checkAlerts(priceData);
        
        // Notify subscribers
        this.notifySubscribers('PRICE_UPDATE', priceData);
        
      } catch (error) {
        console.error('Error monitoring gas price:', error);
      }
    }, interval);
  }
  
  checkAlerts(currentPrice) {
    const alerts = [];
    
    // Check absolute price thresholds
    if (currentPrice.price <= this.thresholds.lowPrice) {
      alerts.push({
        type: 'LOW_PRICE',
        message: `Gas price is unusually low: ${currentPrice.price} MIST`,
        recommendation: 'Good time for non-urgent transactions'
      });
    }
    
    if (currentPrice.price >= this.thresholds.highPrice) {
      alerts.push({
        type: 'HIGH_PRICE',
        message: `Gas price is high: ${currentPrice.price} MIST`,
        recommendation: 'Consider delaying non-urgent transactions'
      });
    }
    
    // Check price change alerts
    if (this.priceHistory.length >= 2) {
      const previousPrice = this.priceHistory[this.priceHistory.length - 2];
      const changePercent = ((currentPrice.price - previousPrice.price) / previousPrice.price) * 100;
      
      if (Math.abs(changePercent) >= this.thresholds.priceChangePercent) {
        alerts.push({
          type: changePercent > 0 ? 'PRICE_SPIKE' : 'PRICE_DROP',
          message: `Gas price ${changePercent > 0 ? 'increased' : 'decreased'} by ${Math.abs(changePercent).toFixed(1)}%`,
          changePercent: changePercent,
          previousPrice: previousPrice.price,
          currentPrice: currentPrice.price
        });
      }
    }
    
    // Notify subscribers about alerts
    alerts.forEach(alert => {
      this.notifySubscribers('ALERT', alert);
    });
  }
  
  subscribe(callback) {
    this.subscribers.push(callback);
    return () => {
      const index = this.subscribers.indexOf(callback);
      if (index > -1) {
        this.subscribers.splice(index, 1);
      }
    };
  }
  
  notifySubscribers(type, data) {
    this.subscribers.forEach(callback => {
      try {
        callback(type, data);
      } catch (error) {
        console.error('Error notifying subscriber:', error);
      }
    });
  }
}

Dynamic Gas Price Strategy

JavaScript
class DynamicGasPriceStrategy {
  constructor(client) {
    this.client = client;
    this.priceCache = new Map();
    this.strategyConfig = {
      conservative: { multiplier: 1.0, maxPrice: 1200 },
      normal: { multiplier: 1.1, maxPrice: 1500 },
      aggressive: { multiplier: 1.3, maxPrice: 2000 },
      urgent: { multiplier: 1.5, maxPrice: 3000 }
    };
  }
  
  async getOptimalGasPrice(strategy = 'normal', transactionType = 'general') {
    const basePrice = await this.client.getReferenceGasPrice();
    const basePriceMIST = Number(basePrice);
    
    const config = this.strategyConfig[strategy] || this.strategyConfig.normal;
    let optimalPrice = Math.ceil(basePriceMIST * config.multiplier);
    
    // Apply transaction-specific adjustments
    const typeMultiplier = this.getTypeMultiplier(transactionType);
    optimalPrice = Math.ceil(optimalPrice * typeMultiplier);
    
    // Cap at maximum price
    optimalPrice = Math.min(optimalPrice, config.maxPrice);
    
    // Ensure minimum viable price
    optimalPrice = Math.max(optimalPrice, basePriceMIST);
    
    return {
      basePrice: basePriceMIST,
      optimalPrice: optimalPrice,
      strategy: strategy,
      transactionType: transactionType,
      multiplier: optimalPrice / basePriceMIST,
      premiumPercent: ((optimalPrice - basePriceMIST) / basePriceMIST * 100).toFixed(1)
    };
  }
  
  getTypeMultiplier(transactionType) {
    const typeMultipliers = {
      'transfer': 1.0,
      'defi_swap': 1.2,
      'nft_mint': 1.1,
      'staking': 1.05,
      'governance': 1.15,
      'contract_deployment': 1.3,
      'batch_operation': 1.25
    };
    
    return typeMultipliers[transactionType] || 1.0;
  }
}

Gas Cost Budgeting Tool

JavaScript
class GasCostBudgeter {
  constructor(client) {
    this.client = client;
    this.monthlyBudget = 0;
    this.currentSpending = 0;
    this.plannedTransactions = [];
  }
  
  setMonthlyBudget(budgetSUI) {
    this.monthlyBudget = budgetSUI * 1_000_000_000; // Convert to MIST
    console.log(`Monthly gas budget set to ${budgetSUI} SUI`);
  }
  
  async planTransaction(type, gasUnits, urgency = 'normal') {
    const gasPrice = await this.client.getReferenceGasPrice();
    const strategy = new DynamicGasPriceStrategy(this.client);
    const optimalPricing = await strategy.getOptimalGasPrice(urgency, type);
    
    const estimatedCost = gasUnits * optimalPricing.optimalPrice;
    
    const transaction = {
      id: Date.now() + Math.random(),
      type: type,
      gasUnits: gasUnits,
      urgency: urgency,
      estimatedCost: estimatedCost,
      estimatedCostSUI: estimatedCost / 1_000_000_000,
      optimalGasPrice: optimalPricing.optimalPrice,
      plannedAt: Date.now()
    };
    
    this.plannedTransactions.push(transaction);
    return transaction;
  }
  
  getBudgetStatus() {
    const totalPlanned = this.plannedTransactions.reduce(
      (sum, tx) => sum + tx.estimatedCost, 0
    );
    
    const remaining = this.monthlyBudget - this.currentSpending - totalPlanned;
    const utilizationPercent = ((this.currentSpending + totalPlanned) / this.monthlyBudget) * 100;
    
    return {
      monthlyBudgetSUI: this.monthlyBudget / 1_000_000_000,
      currentSpendingSUI: this.currentSpending / 1_000_000_000,
      plannedSpendingSUI: totalPlanned / 1_000_000_000,
      remainingBudgetSUI: remaining / 1_000_000_000,
      utilizationPercent: utilizationPercent,
      plannedTransactions: this.plannedTransactions.length,
      budgetStatus: utilizationPercent > 100 ? 'OVER_BUDGET' : 
                   utilizationPercent > 80 ? 'BUDGET_WARNING' : 'BUDGET_OK'
    };
  }
  
  async optimizePlannedTransactions() {
    const optimizations = [];
    
    for (const tx of this.plannedTransactions) {
      const currentGasPrice = await this.client.getReferenceGasPrice();
      const newEstimatedCost = tx.gasUnits * Number(currentGasPrice);
      
      if (newEstimatedCost < tx.estimatedCost * 0.9) { // 10% savings
        optimizations.push({
          transactionId: tx.id,
          type: tx.type,
          currentEstimate: tx.estimatedCost,
          newEstimate: newEstimatedCost,
          savings: tx.estimatedCost - newEstimatedCost,
          savingsPercent: ((tx.estimatedCost - newEstimatedCost) / tx.estimatedCost * 100).toFixed(1)
        });
      }
    }
    
    return optimizations;
  }
}

Performance Optimization

Gas Price Caching Strategy

JavaScript
class GasPriceCacheManager {
  constructor(client) {
    this.client = client;
    this.cache = new Map();
    this.defaultTTL = 30000; // 30 seconds
    this.maxCacheSize = 100;
  }
  
  async getGasPrice(useCache = true, ttl = this.defaultTTL) {
    const cacheKey = 'reference_gas_price';
    
    if (useCache) {
      const cached = this.cache.get(cacheKey);
      if (cached && (Date.now() - cached.timestamp) < ttl) {
        return cached.value;
      }
    }
    
    const gasPrice = await this.client.getReferenceGasPrice();
    
    if (gasPrice) {
      this.cache.set(cacheKey, {
        value: gasPrice,
        timestamp: Date.now()
      });
      
      // Clean cache if too large
      if (this.cache.size > this.maxCacheSize) {
        const oldest = Math.min(...Array.from(this.cache.values()).map(v => v.timestamp));
        for (const [key, value] of this.cache.entries()) {
          if (value.timestamp === oldest) {
            this.cache.delete(key);
            break;
          }
        }
      }
    }
    
    return gasPrice;
  }
  
  clearCache() {
    this.cache.clear();
  }
  
  getCacheStats() {
    return {
      size: this.cache.size,
      maxSize: this.maxCacheSize,
      entries: Array.from(this.cache.entries()).map(([key, value]) => ({
        key,
        age: Date.now() - value.timestamp,
        value: value.value
      }))
    };
  }
}

Best Practices

  1. Cache Gas Prices: Cache gas price for short periods to reduce RPC calls
  2. Monitor Price Changes: Set up alerts for significant gas price changes
  3. Use Appropriate Urgency: Don't overpay for gas unless transaction is urgent
  4. Budget Management: Track gas spending to avoid unexpected costs
  5. Batch Operations: Combine multiple operations to reduce per-transaction overhead
  6. Timing Optimization: Execute non-urgent transactions during low-price periods

Need help? Contact our support team or check the Sui documentation.