コンテンツにスキップ

Hello World⚓︎

初級

このチュートリアルでは、最小限のプログラムを作成して Symbol SDK が正しく動作することを確認します。 プログラムは次の処理を行います。

  • SDK を使ってネットワーク名と起動日を取得する。
  • ノード に接続し、現在のチェーン高を表示する。

必要なのは基本的な SDK 呼び出しと REST リクエストだけで、アカウント、キー、トランザクションは必要ありません。

前提条件⚓︎

まだ準備できていない場合は、まず 開発環境のセットアップ を行ってください。

完全なコード⚓︎

import json
import urllib.request

from symbolchain.facade.NemFacade import NemFacade
from symbolchain.nem.Network import NetworkTimestamp


facade = NemFacade('testnet')
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 = 'http://libertalia.nemtest.net:7890'
print(f'Using node {NODE_URL}')
try:
    # Fetch current chain height
    height_path = '/chain/height'
    print(f'Fetching chain height from {height_path}')
    with urllib.request.urlopen(
        f'{NODE_URL}{height_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 {
    NemFacade,
    NetworkTimestamp
} from 'symbol-sdk/nem';

const facade = new NemFacade('testnet');
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 = 'http://libertalia.nemtest.net:7890';
console.log(`Using node ${NODE_URL}`);
try {
    // Fetch current chain height
    const heightPath = '/chain/height';
    console.log(`Fetching chain height from ${heightPath}`);
    const response = await fetch(`${NODE_URL}${heightPath}`,
        { 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 = NemFacade('testnet')
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 NemFacade('testnet');
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()}`);

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

ファサードを作成するには、mainnet または testnet のいずれかの、使用するネットワーク名を指定します。

この例では、ネットワークの起動日も取得します。 メソッドは、ネットワークタイムスタンプを UTC の日時に変換します。 ジェネシスタイムスタンプである 0 を渡すと、ジェネシスブロックが生成された時点、つまりネットワークの起動日を取得できます。

ノードから情報を取得する⚓︎

NODE_URL = 'http://libertalia.nemtest.net:7890'
print(f'Using node {NODE_URL}')
try:
    # Fetch current chain height
    height_path = '/chain/height'
    print(f'Fetching chain height from {height_path}')
    with urllib.request.urlopen(
        f'{NODE_URL}{height_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 = 'http://libertalia.nemtest.net:7890';
console.log(`Using node ${NODE_URL}`);
try {
    // Fetch current chain height
    const heightPath = '/chain/height';
    console.log(`Fetching chain height from ${heightPath}`);
    const response = await fetch(`${NODE_URL}${heightPath}`,
        { 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');
}

NEM ブロックチェーンとのやりとりは、ノード を通じて行われます。このノードは、ネットワークの状態を照会したり、トランザクションを送信するための REST インターフェースを提供しています。

この例では、テストネットのノードに接続し、/chain/height GET エンドポイントから現在のチェーン高を取得します。

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

出力⚓︎

以下は、プログラムの実行時の出力例です。

Network name: testnet
Network launch date: 2015-03-29 00:06:25+00:00
Using node http://libertalia.nemtest.net:7890
Fetching chain height from /chain/height
  Blockchain height: 625,079 blocks

まとめ⚓︎

上記の出力が表示されたら、準備は完了です。 Symbol SDK にアクセスでき、NEM ノードへの接続にも成功しています。

これで NEM の冒険を始めるための準備は万端です。

次は アカウントを作成 してみてはいかがでしょうか。