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 Exception as error:
print(error)
|
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
| //JAVA 21+
//DEPS org.symbol:symbol-sdk:3.3.3
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.NemFacade;
import org.symbol.sdk.nem.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 NemFacade facade = new NemFacade("testnet");
System.out.println("Network name: " + facade.network.name);
// NetworkTimestamp(0) is the genesis block timestamp
// (network launch)
final Instant launchDate = facade.network.toDatetime(
new NetworkTimestamp(0));
System.out.println(
"Network launch date: " + launchDate);
final String nodeUrl = "http://libertalia.nemtest.net:7890";
System.out.println("Using node " + nodeUrl);
// Fetch current chain height
final String heightPath = "/chain/height";
System.out.println("Fetching chain height from " + heightPath);
final HttpRequest request = HttpRequest
.newBuilder(URI.create(nodeUrl + heightPath))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
final HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, BodyHandlers.ofString());
if (200 != response.statusCode())
throw new IOException("HTTP error! status: "
+ response.statusCode());
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 の呼び出し
クラスは、NEM ブロックチェーンで Symbol SDK を使用する際の主なエントリーポイントです。
トランザクションの構築と署名からネットワーク関連情報の取得まで、必要になるほとんどのメソッドを提供します。
ファサードを作成するには、mainnet または testnet のいずれかの、使用するネットワーク名を指定します。
この例では、ネットワークの起動日も取得します。
メソッドは、ネットワークタイムスタンプを UTC の日時に変換します。
ジェネシスタイムスタンプである 0 を渡すと、ジェネシスブロックが生成された時点、つまりネットワークの起動日を取得できます。
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 の冒険を始めるための準備は万端です。
次は アカウントを作成 してみてはいかがでしょうか。