コンテンツにスキップ
初級

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://reference.symboltest.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 {
    SymbolFacade,
    NetworkTimestamp
} 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://reference.symboltest.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 = parseInt(responseJson.height, 10);
    console.log(`  Blockchain height: ${height.toLocaleString()} blocks`);
} catch (e) {
    console.error(e.message, '| Cause:', e.cause?.code ?? 'unknown');
}

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()}`);

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

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

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

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

NODE_URL = 'https://reference.symboltest.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://reference.symboltest.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 = parseInt(responseJson.height, 10);
    console.log(`  Blockchain height: ${height.toLocaleString()} blocks`);
} catch (e) {
    console.error(e.message, '| Cause:', e.cause?.code ?? 'unknown');
}

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://reference.symboltest.net:3001
Fetching chain information from /chain/info
  Blockchain height: 2,367,414 blocks

結論⚓︎

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

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

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