コンテンツにスキップ

Hello World⚓︎

初級

このチュートリアルでは、以下を行う最小限のプログラムを記述することで、Symbol SDK のインストールが正しく機能しているかを確認する方法を説明します。

  • SDK を使用してネットワーク名と開始日を取得します。
  • ノードに接続し、現在のブロックチェーン高を表示します。

アカウント、鍵、 トランザクションは必要ありません。基本的な SDK 呼び出しと REST リクエストのみを使用します。

前提条件⚓︎

まだ完了していない場合は、開発環境のセットアップ から始めてください。

完全なコード⚓︎

このチュートリアルの完全なコード一覧を以下に示します。 詳細な手順ごとの説明は次のセクションで行います。

import json
import urllib.request

from symbolchain.facade.SymbolFacade import SymbolFacade
from symbolchain.symbol.Network import NetworkTimestamp


facade = SymbolFacade('mainnet')
print(f"Network name: {facade.network.name}")
# NetworkTimestamp(0) is the genesis block timestamp
launch_date = facade.network.to_datetime(NetworkTimestamp(0))
print(f"Network launch date: {launch_date}")

NODE_URL = 'https://whydah.symbolmain.net:3001'
print(f'Using node {NODE_URL}')
try:
    # Fetch current chain information
    info_path = '/chain/info'
    print(f'Fetching chain information from {info_path}')
    with urllib.request.urlopen(
        f'{NODE_URL}{info_path}', timeout=10
    ) as response:
        response_json = json.loads(response.read().decode())
        height = int(response_json['height'])
        print(f"  Blockchain height: {height:,} blocks")

except urllib.error.URLError as e:
    print(e.reason)

Download source

import {
    NetworkTimestamp,
    SymbolFacade
} from 'symbol-sdk/symbol';

const facade = new SymbolFacade('mainnet');
console.log(`Network name: ${facade.network.name}`);
// NetworkTimestamp(0) is the genesis block timestamp (network launch)
const launchDate = facade.network.toDatetime(new NetworkTimestamp(0));
console.log(`Network launch date: ${launchDate.toISOString()}`);

const NODE_URL = 'https://whydah.symbolmain.net:3001';
console.log(`Using node ${NODE_URL}`);
try {
    // Fetch current chain information
    const infoPath = '/chain/info';
    console.log(`Fetching chain information from ${infoPath}`);
    const response = await fetch(`${NODE_URL}${infoPath}`,
        { timeout: 10000 });
    if (!response.ok)
        throw new Error(`HTTP error! status: ${response.status}`);
    const responseJson = await response.json();
    const height = BigInt(responseJson.height);
    console.log(
        `  Blockchain height: ${height.toLocaleString()} blocks`);
} catch (e) {
    console.error(e.message, '| Cause:', e.cause?.code ?? 'unknown');
}

Download source

//JAVA 21+
//DEPS org.symbol:symbol-sdk:3.3.1

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.time.Instant;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.symbol.sdk.facade.SymbolFacade;
import org.symbol.sdk.symbol.NetworkTimestamp;

public final class HelloWorld {
    public static void main(final String[] args) {
        try {
            new HelloWorld().run();
        } catch (final Exception ex) {
            System.out.println(null == ex.getMessage()
                ? ex.toString()
                : ex.getMessage());
        }
    }

    private void run() throws IOException, InterruptedException {

        final SymbolFacade facade = new SymbolFacade("mainnet");
        System.out.println(
            "Network name: " + facade.network.name);
        // NetworkTimestamp(0) is the genesis block timestamp
        final Instant launchDate = facade.network.toDatetime(
            new NetworkTimestamp(0));
        System.out.println(
            "Network launch date: " + launchDate);

        final String nodeUrl = "https://whydah.symbolmain.net:3001";
        System.out.println("Using node " + nodeUrl);
        // Fetch current chain information
        final String infoPath = "/chain/info";
        System.out.println(
            "Fetching chain information from " + infoPath);
        final HttpClient client = HttpClient.newHttpClient();
        final HttpRequest request = HttpRequest
            .newBuilder(URI.create(nodeUrl + infoPath))
            .timeout(Duration.ofSeconds(10))
            .GET()
            .build();
        final HttpResponse<String> response = client.send(
            request, BodyHandlers.ofString());
        final JsonNode responseJson = new ObjectMapper()
            .readTree(response.body());
        final long height = responseJson.get("height").asLong();
        System.out.printf(
            "  Blockchain height: %,d blocks%n", height);
    }
}

Download source

SDK の呼び出し⚓︎

facade = SymbolFacade('mainnet')
print(f"Network name: {facade.network.name}")
# NetworkTimestamp(0) is the genesis block timestamp
launch_date = facade.network.to_datetime(NetworkTimestamp(0))
print(f"Network launch date: {launch_date}")
const facade = new SymbolFacade('mainnet');
console.log(`Network name: ${facade.network.name}`);
// NetworkTimestamp(0) is the genesis block timestamp (network launch)
const launchDate = facade.network.toDatetime(new NetworkTimestamp(0));
console.log(`Network launch date: ${launchDate.toISOString()}`);
        final SymbolFacade facade = new SymbolFacade("mainnet");
        System.out.println(
            "Network name: " + facade.network.name);
        // NetworkTimestamp(0) is the genesis block timestamp
        final Instant launchDate = facade.network.toDatetime(
            new NetworkTimestamp(0));
        System.out.println(
            "Network launch date: " + launchDate);

クラスは、Symbol SDK への主要なエントリポイントです。 トランザクションの構築や署名から、ネットワーク関連情報の取得まで、Symbol を操作する際に必要となるほとんどのメソッドを提供します。

ファサードを作成するには、操作したいネットワーク名( mainnet または testnet )を指定するだけです。

この例では、ネットワークの開始日を取得する方法を実演しています。 メソッドは、ネットワークタイムスタンプを UTC の日時に変換します。 0 (ジェネシスタイムスタンプ)を渡すことで、ジェネシスブロックが生成された瞬間、つまりネットワークの開始日を取得できます。

ノードからの情報取得⚓︎

NODE_URL = 'https://whydah.symbolmain.net:3001'
print(f'Using node {NODE_URL}')
try:
    # Fetch current chain information
    info_path = '/chain/info'
    print(f'Fetching chain information from {info_path}')
    with urllib.request.urlopen(
        f'{NODE_URL}{info_path}', timeout=10
    ) as response:
        response_json = json.loads(response.read().decode())
        height = int(response_json['height'])
        print(f"  Blockchain height: {height:,} blocks")

except urllib.error.URLError as e:
    print(e.reason)
const NODE_URL = 'https://whydah.symbolmain.net:3001';
console.log(`Using node ${NODE_URL}`);
try {
    // Fetch current chain information
    const infoPath = '/chain/info';
    console.log(`Fetching chain information from ${infoPath}`);
    const response = await fetch(`${NODE_URL}${infoPath}`,
        { timeout: 10000 });
    if (!response.ok)
        throw new Error(`HTTP error! status: ${response.status}`);
    const responseJson = await response.json();
    const height = BigInt(responseJson.height);
    console.log(
        `  Blockchain height: ${height.toLocaleString()} blocks`);
} catch (e) {
    console.error(e.message, '| Cause:', e.cause?.code ?? 'unknown');
}
        final String nodeUrl = "https://whydah.symbolmain.net:3001";
        System.out.println("Using node " + nodeUrl);
        // Fetch current chain information
        final String infoPath = "/chain/info";
        System.out.println(
            "Fetching chain information from " + infoPath);
        final HttpClient client = HttpClient.newHttpClient();
        final HttpRequest request = HttpRequest
            .newBuilder(URI.create(nodeUrl + infoPath))
            .timeout(Duration.ofSeconds(10))
            .GET()
            .build();
        final HttpResponse<String> response = client.send(
            request, BodyHandlers.ofString());
        final JsonNode responseJson = new ObjectMapper()
            .readTree(response.body());
        final long height = responseJson.get("height").asLong();
        System.out.printf(
            "  Blockchain height: %,d blocks%n", height);

Symbolブロックチェーンとの対話は、ネットワーク状態の照会やトランザクションの送信のための REST インターフェースを公開している API ノードを通じて行われます。 すべてのノードがこのインターフェースを提供しているわけではないため、 API Node とラベル付けされたものに接続することが重要です。

この例では、APIノードに接続し、 /chain/info GET エンドポイントから現在のブロックチェーン高を取得します。

このリクエストには秘密鍵や認証は必要ありません。環境が正しくセットアップされ、ネットワークに到達できることを確認するためのシンプルで効果的なテストとなります。

出力⚓︎

以下に示す出力は、プログラムの典型的な実行結果に対応しています。

Network name: mainnet
Network launch date: 2021-03-16 00:06:25+00:00
Using node https://whydah.symbolmain.net:3001
Fetching chain information from /chain/info
  Blockchain height: 5,660,712 blocks

結論⚓︎

上記の出力が得られれば、準備は完了です。 Symbol SDK にアクセスでき、Symbol API ノードへの到達に成功しました。

Symbol の冒険を始めるために必要なものはこれだけです。

次は アカウントを作成 してみませんか?