Skip to content

Quick Start

Learn how to read a KOIN balance from the Koinos blockchain in just a few lines of code.

Prerequisites

  • Node.js installed
  • Basic JavaScript/TypeScript knowledge

Setup

  1. Create a new project:

    mkdir koinos-quickstart
    cd koinos-quickstart
    npm init -y
    

  2. Install Koilib:

    npm install koilib
    

Read a Balance

Create index.js:

export function balanceUrl(address) {
  const account = encodeURIComponent(address);
  return (
    `${MAINNET_REST_URL}/v1/account/${account}/balance/` +
    KOIN_CONTRACT_ID
  );
}

export async function readKoinBalance(address, fetchImpl = fetch) {
  const response = await fetchImpl(balanceUrl(address), {
    headers: {
      accept: "application/json",
      "user-agent": "koinos-docs-example/1.0",
    },
  });
  if (!response.ok) {
    throw new Error(`Koinos REST API returned HTTP ${response.status}`);
  }

  const payload = await response.json();
  if (typeof payload.value !== "string") {
    throw new Error("Koinos REST API response has no string balance value");
  }
  return payload.value;
}

async function main() {
  const address = process.argv[2] ?? DEFAULT_PUBLIC_ADDRESS;
  const balance = await readKoinBalance(address);
  console.log(`${address}: ${balance} KOIN`);
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  main().catch((error) => {
    console.error(error.message);
    process.exitCode = 1;
  });
}

View complete file · Run example

The script is a read-only Node.js example. It defaults to a public address and accepts another Koinos address as its first command-line argument.

  1. Run the script:
    node index.js
    

Expected Output

Balance: 1234.56789012 KOIN

What's Happening?

  1. The script calls the current Koinos REST API.
  2. The account and KOIN contract IDs form the balance endpoint.
  3. The response contains the human-readable KOIN balance.
  4. Errors are reported with the HTTP status instead of being silently ignored.

Next Steps