/exchange
GET PUT POST DELETE ASYNCList, create, buy, or delete sale listings on the exchange.
Description
The /exchange
endpoint is the primary interface for interacting with the CloudCoin exchange. It allows users to list CloudCoins for sale in exchange for other cryptocurrencies (like BTC or XMR), view existing listings, purchase listings, and remove their own listings. All operations are asynchronous and return a task ID.
GET /exchange (List Sales)
Retrieves a list of all items currently for sale for a given cryptocurrency type.
Query Parameters
Parameter | Type | Required | Description |
---|---|---|---|
cointype | integer | Yes | The type of coin to list sales for (1 for BTC, 2 for XMR). |
Response (in completed task `data`)
An object containing a list of sale items.
PUT /exchange (Create Sale)
Puts a specified amount of CloudCoins up for sale at a given price.
Request Body
Parameter | Type | Required | Description |
---|---|---|---|
cointype | integer | Yes | The target cryptocurrency (1 for BTC, 2 for XMR). |
address | string | Yes | The seller's cryptocurrency address for receiving payment. |
price | number | Yes | The price in the target cryptocurrency (e.g., 0.001 for BTC). |
amount | number | Yes | The amount of CloudCoins to sell. |
name | string | Yes | The name of the source wallet. |
Response (in completed task `data`)
A confirmation object upon success.
POST /exchange (Buy)
Purchases a sale listing by providing proof of payment (a cryptocurrency transaction ID).
Request Body
Parameter | Type | Required | Description |
---|---|---|---|
cointype | integer | Yes | Cryptocurrency used for payment (1 for BTC, 2 for XMR). |
price | number | Yes | The price of the sale listing. |
tx | string | Yes | The transaction ID of the cryptocurrency payment. |
name | string | Yes | The destination wallet for the purchased CloudCoins. |
amount | number | Yes | The amount of CloudCoins being purchased. |
receipt_id | string | Yes | The receipt ID from the /exchange/address call. |
tag | string | No | An optional memo for the transaction. |
Response (in completed task `data`)
A transmit code (string) to retrieve the purchased CloudCoins using the /locker/{code}
endpoint.
DELETE /exchange (Delete Sale)
Deletes one of your own sale listings from the exchange.
Query Parameters
Parameter | Type | Required | Description |
---|---|---|---|
cointype | integer | Yes | The cryptocurrency type of the listing. |
amount | number | Yes | The amount of CloudCoins in the listing. |
name | string | Yes | The name of the wallet that created the listing. |
price | number | Yes | The price of the listing. |
Response (in completed task `data`)
A confirmation object upon success.
Examples
JavaScript: Generic Task Poller
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
}
function startPolling(taskId) {
const pollInterval = setInterval(async () => {
const isDone = await pollTask(taskId);
if (isDone) clearInterval(pollInterval);
}, 2000); // Check every 2 seconds
}
JavaScript: Exchange Functions
// GET /exchange
async function listForSale(coinType) {
const response = await fetch(`${apiHost}/api/v1/exchange?cointype=${coinType}`);
const task = await response.json();
console.log(`ListForSale task created: ${task.payload.id}`);
startPolling(task.payload.id);
}
// PUT /exchange
async function putForSale(data) {
const response = await fetch(`${apiHost}/api/v1/exchange`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const task = await response.json();
console.log(`PutForSale task created: ${task.payload.id}`);
startPolling(task.payload.id);
}
// POST /exchange
async function buy(data) {
const response = await fetch(`${apiHost}/api/v1/exchange`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const task = await response.json();
console.log(`Buy task created: ${task.payload.id}`);
startPolling(task.payload.id);
}
// DELETE /exchange
async function deleteSale(params) {
const query = new URLSearchParams(params).toString();
const response = await fetch(`${apiHost}/api/v1/exchange?${query}`, { method: 'DELETE' });
const task = await response.json();
console.log(`DeleteSale task created: ${task.payload.id}`);
startPolling(task.payload.id);
}
cURL: List Sales (GET)
# Step 1: Initiate the list sales task
TASK_ID=$(curl -s -X GET "http://localhost:8006/api/v1/exchange?cointype=1" | jq -r '.payload.id')
echo "List sales 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')
echo "Polling task.. Status: $STATUS"
if [[ "$STATUS" == "completed" ]] || [[ "$STATUS" == "error" ]]; then
echo "Final Response:"; echo $RESPONSE | jq; break
fi; sleep 2
done
cURL: Create Sale (PUT)
# Step 1: Initiate the create sale task
TASK_ID=$(curl -s -X PUT "http://localhost:8006/api/v1/exchange" \
-H "Content-Type: application/json" \
-d '{"cointype":1, "address":"YOUR_BTC_ADDRESS", "price":0.001, "amount":100, "name":"Default"}' | jq -r '.payload.id')
echo "Create sale task started with ID: $TASK_ID"
# Step 2: Poll the task endpoint
while true; do
RESPONSE=$(curl -s "http://localhost:8006/api/v1/tasks/$TASK_ID")
STATUS=$(echo $RESPONSE | jq -r '.payload.status')
echo "Polling task.. Status: $STATUS"
if [[ "$STATUS" == "completed" ]] || [[ "$STATUS" == "error" ]]; then
echo "Final Response:"; echo $RESPONSE | jq; break
fi; sleep 2
done
cURL: Buy (POST)
# Step 1: Initiate the buy task
TASK_ID=$(curl -s -X POST "http://localhost:8006/api/v1/exchange" \
-H "Content-Type: application/json" \
-d '{"cointype":1, "price":0.001, "tx":"CRYPTO_TX_ID", "name":"MyWallet", "amount":100, "receipt_id":"RECEIPT_ID_FROM_ADDRESS_ENDPOINT"}' | jq -r '.payload.id')
echo "Buy task started with ID: $TASK_ID"
# Step 2: Poll the task endpoint
while true; do
RESPONSE=$(curl -s "http://localhost:8006/api/v1/tasks/$TASK_ID")
STATUS=$(echo $RESPONSE | jq -r '.payload.status')
echo "Polling task.. Status: $STATUS"
if [[ "$STATUS" == "completed" ]] || [[ "$STATUS" == "error" ]]; then
echo "Final Response:"; echo $RESPONSE | jq; break
fi; sleep 2
done
cURL: Delete Sale (DELETE)
# Step 1: Initiate the delete sale task
TASK_ID=$(curl -s -X DELETE "http://localhost:8006/api/v1/exchange?cointype=1&amount=100&name=Default&price=0.001" | jq -r '.payload.id')
echo "Delete sale task started with ID: $TASK_ID"
# Step 2: Poll the task endpoint
while true; do
RESPONSE=$(curl -s "http://localhost:8006/api/v1/tasks/$TASK_ID")
STATUS=$(echo $RESPONSE | jq -r '.payload.status')
echo "Polling task.. Status: $STATUS"
if [[ "$STATUS" == "completed" ]] || [[ "$STATUS" == "error" ]]; then
echo "Final Response:"; echo $RESPONSE | jq; break
fi; sleep 2
done
Go: Polling Logic and Main Functions
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
const apiHost = "http://localhost:8006/api/v1"
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"`
}
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
}
defer resp.Body.Close()
var taskResp TaskResponse
if err := json.NewDecoder(resp.Body).Decode(&taskResp); err != nil {
log.Printf("Error decoding task response: %v\n", err)
return
}
fmt.Printf("Polling... Status: %s, Progress: %d%%\n", taskResp.Payload.Status, taskResp.Payload.Progress)
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)
}
}
func startTask(req *http.Request) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Failed to start task: %v", err)
}
defer resp.Body.Close()
var taskResp TaskResponse
if err := json.NewDecoder(resp.Body).Decode(&taskResp); err != nil {
log.Fatalf("Failed to decode initial task response: %v", err)
}
fmt.Printf("Task created with ID: %s\n", taskResp.Payload.ID)
pollTask(taskResp.Payload.ID)
}
Go: Exchange Functions
func listForSale(coinType int) {
req, _ := http.NewRequest("GET", fmt.Sprintf("%s/exchange?cointype=%d", apiHost, coinType), nil)
startTask(req)
}
func putForSale(data map[string]interface{}) {
body, _ := json.Marshal(data)
req, _ := http.NewRequest("PUT", fmt.Sprintf("%s/exchange", apiHost), bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
startTask(req)
}
func buy(data map[string]interface{}) {
body, _ := json.Marshal(data)
req, _ := http.NewRequest("POST", fmt.Sprintf("%s/exchange", apiHost), bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
startTask(req)
}
func deleteSale(params map[string]string) {
baseURL := fmt.Sprintf("%s/exchange", apiHost)
queryParams := url.Values{}
for key, val := range params {
queryParams.Add(key, val)
}
req, _ := http.NewRequest("DELETE", fmt.Sprintf("%s?%s", baseURL, queryParams.Encode()), nil)
startTask(req)
}