Get SOL Price

Endpoint: GET /api/v1/coin/sol-price

Description

This endpoint retrieves the current price of SOL in USD from CoinGecko's API. The response is cached for 60 seconds to minimize API calls and improve performance.

Authentication

Required: No

Type: None

Request

Headers

Content-Type: application/json

No parameters required.

Response

Success Response

Status Code: 200 OK

Content-Type: application/json

interface SolPriceResponse {

price: number; // SOL price in USD

}

Example Response:

{

"price": 102.45

}

Error Response

Status Code: 500 Internal Server Error

{

"error": "An internal error occurred. Please try again later."

}

Example Usage

// Basic fetch

async function getSOLPrice() {

try {

const response = await fetch('https://api.cybers.app/api/v1/coin/sol-price');

if (!response.ok) {

throw new Error(`HTTP error! status: ${response.status}`);

}

const { price } = await response.json();

return price;

} catch (error) {

console.error('Error fetching SOL price:', error);

throw error;

}

}

// With client-side caching

class SOLPriceManager {

private cache: {

price: number;

timestamp: number;

} | null = null;

private readonly CACHE_DURATION = 60000; // 60 seconds

async getPrice(): Promise<number> {

// Check cache

if (this.cache &&

Date.now() - this.cache.timestamp < this.CACHE_DURATION) {

return this.cache.price;

}

// Fetch new price

const response = await fetch('https://api.cybers.app/api/v1/coin/sol-price');

const { price } = await response.json();

// Update cache

this.cache = {

price,

timestamp: Date.now()

};

return price;

}

clearCache() {

this.cache = null;

}

}

Implementation Notes

1. Caching

The endpoint uses server-side caching with a 60-second expiration

If CoinGecko API fails, returns 0 as a fallback value

Cache is automatically invalidated after expiration

Error Handling

// Example of robust error handling

async function getSOLPriceWithRetry(

maxRetries = 3,

retryDelay = 1000

): Promise<number> {

let attempts = 0;

while (attempts < maxRetries) {

try {

const response = await fetch(

'https://api.cybers.app/api/v1/coin/sol-price'

);

if (!response.ok) {

throw new Error(`HTTP error! status: ${response.status}`);

}

const { price } = await response.json();

if (typeof price !== 'number' || isNaN(price)) {

throw new Error('Invalid price received');

}

return price;

} catch (error) {

attempts++;

if (attempts === maxRetries) {

throw error;

}

await new Promise(resolve =>

setTimeout(resolve, retryDelay * attempts)

);

}

}

throw new Error('Failed to fetch SOL price');

}

3. Price Monitoring

class SOLPriceMonitor {

private price: number = 0;

private listeners: ((price: number) => void)[] = [];

private intervalId: NodeJS.Timeout | null = null;

constructor(private pollInterval: number = 60000) {}

addListener(callback: (price: number) => void) {

this.listeners.push(callback);

}

async start() {

await this.updatePrice();

this.intervalId = setInterval(

() => this.updatePrice(),

this.pollInterval

);

}

stop() {

if (this.intervalId) {

clearInterval(this.intervalId);

this.intervalId = null;

}

}

private async updatePrice() {

try {

const response = await fetch(

'https://api.cybers.app/api/v1/coin/sol-price'

);

const { price } = await response.json();

if (price !== this.price) {

this.price = price;

this.notifyListeners();

}

} catch (error) {

console.error('Error updating SOL price:', error);

}

}

private notifyListeners() {

this.listeners.forEach(listener => listener(this.price));

}

}

Best Practices

1. Price Display

function formatSOLPrice(price: number): string {

return new Intl.NumberFormat('en-US', {

style: 'currency',

currency: 'USD',

minimumFractionDigits: 2,

maximumFractionDigits: 2

}).format(price);

}

Price Change Tracking

interface PricePoint {

price: number;

timestamp: number;

}

class PriceTracker {

private history: PricePoint[] = [];

private readonly MAX_HISTORY = 100;

addPrice(price: number) {

this.history.push({

price,

timestamp: Date.now()

});

if (this.history.length > this.MAX_HISTORY) {

this.history.shift();

}

}

getPercentageChange(timeframeMs: number): number {

const now = Date.now();

const compareTime = now - timeframeMs;

const oldPrice = this.history.find(

point => point.timestamp <= compareTime

);

if (!oldPrice) return 0;

const currentPrice = this.history[this.history.length - 1].price;

return ((currentPrice - oldPrice.price) / oldPrice.price) * 100;

}

}

Price Alert System

Ask

Copy

Apply to kingOfTheHil...

interface PriceAlert {

threshold: number;

isAbove: boolean;

callback: (price: number) => void;

}

class SOLPriceAlerts {

private alerts: PriceAlert[] = [];

private currentPrice: number = 0;

addAlert(alert: PriceAlert) {

this.alerts.push(alert);

this.checkAlert(alert);

}

updatePrice(newPrice: number) {

this.currentPrice = newPrice;

this.checkAlerts();

}

private checkAlerts() {

this.alerts.forEach(alert => this.checkAlert(alert));

}

private checkAlert(alert: PriceAlert) {

const triggered = alert.isAbove

? this.currentPrice > alert.threshold

: this.currentPrice < alert.threshold;

if (triggered) {

alert.callback(this.currentPrice);

}

}

}

Last updated