/crossover/rate/{ticker}

GET ASYNC

Fetches the current exchange rate for converting a cryptocurrency to/from CloudCoins.

GET /api/v1/crossover/rate/{ticker}
Alias: /get-exchange-rate/{ticker}

Description

This endpoint retrieves the latest exchange rate and conversion cost for a given cryptocurrency ticker, such as "BTC". This information is essential for calculating the amounts involved in a crossover transaction before initiating a `send` or `withdraw` operation.

Asynchronous Operation

This operation is asynchronous. It returns a task ID immediately, and the final result must be retrieved by polling the /tasks/{id} endpoint.


Path Parameters

ParameterTypeRequiredDescription
tickerstringYesThe ticker symbol of the cryptocurrency for which to fetch the rate (e.g., "BTC").

Response (in completed task `data`)

Once the task is complete, its `data` field will contain the rate information.

tickerstring
The ticker symbol for the requested rate.
ratenumber
The exchange rate, representing CloudCoins per unit of the crypto.
conversion_costnumber
The associated fee for performing the conversion.
timestampinteger
The Unix timestamp when the rate was fetched.

Examples

JavaScript: Get Crossover Rate

const apiHost = 'http://localhost:8006';

// Generic function to poll any task
async function pollTask(taskId) {
    const taskResponse = await fetch(`${apiHost}/api/v1/tasks/${taskId}`);
    const taskData = await taskResponse.json();
    const task = taskData.payload;

    console.log(`Task ${taskId} progress: ${task.progress}% - ${task.message}`);

    if (task.status === 'completed') {
        console.log(`Task finished successfully!`, task.data);
        return true; // Stop polling
    } else if (task.status === 'error') {
        console.error(`Task failed:`, task.message);
        return true; // Stop polling
    }
    return false; // Continue polling
}

async function getCrossoverRate(ticker) {
    try {
        const response = await fetch(`${apiHost}/api/v1/crossover/rate/${ticker}`);
        const taskInfo = await response.json();
        const taskId = taskInfo.payload.id;
        console.log(`Get rate task created with ID: ${taskId}`);

        const pollInterval = setInterval(async () => {
            const isDone = await pollTask(taskId);
            if (isDone) clearInterval(pollInterval);
        }, 2000); 
    } catch (error) {
        console.error('Failed to start get rate task:', error);
    }
}

// Example: Get the current rate for Bitcoin
getCrossoverRate("BTC");

cURL: Get Crossover Rate

# Step 1: Initiate the get rate task
TICKER="BTC"
TASK_ID=$(curl -s -X GET "http://localhost:8006/api/v1/crossover/rate/$TICKER" | jq -r '.payload.id')
echo "Get rate task started with ID: $TASK_ID"

# Step 2: Poll the task endpoint until finished
while true; do
  RESPONSE=$(curl -s "http://localhost:8006/api/v1/tasks/$TASK_ID")
  STATUS=$(echo $RESPONSE | jq -r '.payload.status')
  MESSAGE=$(echo $RESPONSE | jq -r '.payload.message')
  echo "Polling task.. Status: $STATUS - $MESSAGE"
  
  if [[ "$STATUS" == "completed" ]] || [[ "$STATUS" == "error" ]]; then
    echo "Final Response:"
    echo $RESPONSE | jq
    break
  fi
  
  sleep 2
done

Go: Get Crossover Rate

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

const apiHost = "http://localhost:8006/api/v1"

// Type for the task response
type TaskResponse struct {
	Payload struct {
		ID       string      `json:"id"`
		Status   string      `json:"status"`
		Progress int         `json:"progress"`
		Message  string      `json:"message"`
		Data     interface{} `json:"data"`
	} `json:"payload"`
}

// pollTask polls a task until it is complete or fails.
func pollTask(taskId string) {
	for {
		resp, err := http.Get(fmt.Sprintf("%s/tasks/%s", apiHost, taskId))
		if err != nil {
			log.Printf("Error polling task: %v\n", err)
			return
		}

		var taskResp TaskResponse
		json.NewDecoder(resp.Body).Decode(&taskResp)
		resp.Body.Close()

		fmt.Printf("Polling... Status: %s, Message: %s\n", taskResp.Payload.Status, taskResp.Payload.Message)

		if taskResp.Payload.Status == "completed" {
			fmt.Printf("Task completed successfully. Result: %+v\n", taskResp.Payload.Data)
			return
		} else if taskResp.Payload.Status == "error" {
			fmt.Printf("Task failed: %s\n", taskResp.Payload.Message)
			return
		}
		time.Sleep(2 * time.Second)
	}
}

// getCrossoverRate initiates a get-rate operation and polls for the result.
func getCrossoverRate(ticker string) {
	resp, err := http.Get(fmt.Sprintf("%s/crossover/rate/%s", apiHost, ticker))
	if err != nil {
		log.Fatalf("Failed to start get-rate task: %v", err)
	}
	defer resp.Body.Close()

	var taskResp TaskResponse
	json.NewDecoder(resp.Body).Decode(&taskResp)

	fmt.Printf("Get rate task created with ID: %s\n", taskResp.Payload.ID)
	pollTask(taskResp.Payload.ID)
}

func main() {
	getCrossoverRate("BTC")
}