/mint

POST ASYNC

Creates new coins of specified denominations and adds them to a local wallet.

POST /api/v1/mint
Alias: /mint-coins-to-wallet

Description

This endpoint allows you to mint new CloudCoins. You specify a destination wallet and provide a list of denominations and the quantity of each to create. The new coins will be generated by the RAIDA and deposited into the specified wallet's Bank folder.

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.


Request Body

ParameterTypeRequiredDescription
namestringYesThe name of the destination wallet for the newly minted coins.
itemsarrayYesAn array of objects, each specifying a coin denomination and count.

Item Object Properties

ParameterTypeRequiredDescription
denintegerYesThe denomination of the coins to mint.
countintegerYesThe number of coins of this denomination to mint (valid range: 0-255).

Response (in completed task `data`)

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

total_mintednumber
Total value of all coins successfully minted.
receipt_idstring
A unique identifier for this minting transaction.

Examples

JavaScript: Mint Coins

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 mintCoins(walletName, itemsToMint) {
    try {
        const response = await fetch(`${apiHost}/api/v1/mint`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name: walletName,
                items: itemsToMint
            })
        });
        const taskInfo = await response.json();
        const taskId = taskInfo.payload.id;
        console.log(`Mint task created with ID: ${taskId}`);

        const pollInterval = setInterval(async () => {
            const isDone = await pollTask(taskId);
            if (isDone) clearInterval(pollInterval);
        }, 2000); // Check every 2 seconds
    } catch (error) {
        console.error('Failed to start mint task:', error);
    }
}

// Example: Mint 10x 1-CC and 5x 5-CC coins into the 'Default' wallet
const items = [
    { den: 1, count: 10 },
    { den: 5, count: 5 }
];
mintCoins('Default', items);

cURL: Mint Coins

# Step 1: Initiate the mint task
TASK_ID=$(curl -s -X POST "http://localhost:8006/api/v1/mint" \
-H "Content-Type: application/json" \
-d '{"name":"Default", "items": [{"den":1, "count":10}, {"den":5, "count":5}]}' | jq -r '.payload.id')
echo "Mint 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

Go: Mint Coins

package main

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

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

// Types for the request
type MintItem struct {
	Denomination uint8 `json:"den"`
	Count        int   `json:"count"`
}

type MintRequest struct {
	Name  string     `json:"name"`
	Items []MintItem `json:"items"`
}

// 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, 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)
	}
}

// mintCoins initiates a mint operation and then polls for the result.
func mintCoins(walletName string, itemsToMint []MintItem) {
	requestBody, _ := json.Marshal(MintRequest{
		Name:  walletName,
		Items: itemsToMint,
	})

	resp, err := http.Post(fmt.Sprintf("%s/mint", apiHost), "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		log.Fatalf("Failed to start mint task: %v", err)
	}
	defer resp.Body.Close()

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

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

func main() {
	items := []MintItem{
		{Denomination: 1, Count: 10},
		{Denomination: 5, Count: 5},
	}
	mintCoins("Default", items)
}