コンテンツにスキップ

ルートネームスペースを登録する⚓︎

中級

ネームスペース は、ネイティブの nem:xem モザイクにおける nem プレフィックスのように、関連する モザイク を意味のある名前でまとめるラベルを提供します。

ネームスペースは他のネームスペースの下にネストできます。このチュートリアルでは、1 年間の ルートネームスペース を登録する方法を説明します。

ルートネームスペースではなく サブネームスペース を登録する方法については、サブネームスペースを登録する ガイドを参照してください。

前提条件⚓︎

始める前に、次の準備をしてください。

さらに、トランザクションのアナウンスと承認の方法を理解するため、XEM を送信する チュートリアルを確認してください。

完全なコード⚓︎

import json
import os
import time
import urllib.request

from symbolchain.CryptoTypes import PrivateKey
from symbolchain.facade.NemFacade import NemFacade
from symbolchain.nc import Amount
from symbolchain.nem.FeeCalculator import (
    calculate_namespace_rental_fee,
    calculate_transaction_fee
)
from symbolchain.nem.Network import NetworkTimestamp

NODE_URL = os.getenv('NODE_URL', 'http://libertalia.nemtest.net:7890')
print(f'Using node {NODE_URL}')

SIGNER_PRIVATE_KEY = os.getenv(
    'SIGNER_PRIVATE_KEY',
    '0000000000000000000000000000000000000000000000000000000000000000')
signer_key_pair = NemFacade.KeyPair(PrivateKey(SIGNER_PRIVATE_KEY))

facade = NemFacade('testnet')
signer_address = facade.network.public_key_to_address(
    signer_key_pair.public_key)
print(f'Signer address: {signer_address}')

try:
    # Fetch current network time
    time_path = '/time-sync/network-time'
    print(f'Fetching current network time from {time_path}')
    with urllib.request.urlopen(f'{NODE_URL}{time_path}') as response:
        response_json = json.loads(response.read().decode())
        network_time = response_json['receiveTimeStamp'] // 1000
        print(f'  Network time: {network_time} s since the nemesis block')

    # Derived fields from network time
    timestamp = NetworkTimestamp(network_time)
    deadline = timestamp.add_hours(2)

    # Build the namespace name
    namespace_name = os.getenv('ROOT_NAMESPACE', f'ns_{int(time.time())}')
    print(f'Creating root namespace: {namespace_name}')

    # Build the transaction
    rental_fee = calculate_namespace_rental_fee(True)
    print(f'  Namespace lease fee: {rental_fee / 1_000_000} XEM')

    transaction = facade.transaction_factory.create({
        'type': 'namespace_registration_transaction_v1',
        'signer_public_key': signer_key_pair.public_key,
        'timestamp': timestamp.timestamp,
        'deadline': deadline.timestamp,
        'rental_fee_sink': 'TAMESPACEWH4MKFMBCVFERDPOOP4FK7MTDJEYP35',
        'rental_fee': rental_fee,
        'name': namespace_name
    })

    # Calculate and attach the transaction fee
    fee = calculate_transaction_fee(transaction)
    transaction.fee = Amount(fee)
    print(f'  Transaction fee: {fee / 1_000_000} XEM')

    # Sign transaction and generate final payload
    signature = facade.sign_transaction(signer_key_pair, transaction)
    json_payload = facade.transaction_factory.attach_signature(
        transaction, signature)
    print('Built transaction:')
    print(json.dumps(transaction.to_json(), indent=2))

    # Announce the transaction
    announce_path = '/transaction/announce'
    print(f'Announcing namespace registration to {announce_path}')
    announce_request = urllib.request.Request(
        f'{NODE_URL}{announce_path}',
        data=json_payload.encode(),
        headers={'Content-Type': 'application/json'},
        method='POST'
    )
    with urllib.request.urlopen(announce_request) as response:
        announce_result = json.loads(response.read().decode())
    print(f'  Result: {announce_result['message']}')

    # Wait for confirmation
    if 'SUCCESS' == announce_result['message']:
        status_path = (
            f'/transaction/get?hash={
                facade.hash_transaction(transaction)}')
        print(f'Waiting for confirmation from {status_path}')
        is_confirmed = False
        for attempt in range(120):
            try:
                with urllib.request.urlopen(
                    f'{NODE_URL}{status_path}'
                ) as response:
                    confirmed = json.loads(response.read().decode())
                    height = confirmed['meta']['height']
                    print(f'Transaction confirmed in block {height}')
                    is_confirmed = True
                    break
            except urllib.error.HTTPError:
                print('  Transaction status: pending')
            time.sleep(1)
        if not is_confirmed:
            print('Confirmation took too long.')
    else:
        print(f'Transaction rejected: {announce_result['message']}')

    # Retrieve the namespace
    namespace_path = f'/namespace?namespace={namespace_name}'
    print(f'Fetching namespace information from {namespace_path}')
    with urllib.request.urlopen(
        f'{NODE_URL}{namespace_path}'
    ) as response:
        namespace_info = json.loads(response.read().decode())
        print('Namespace information:')
        print(f'  Name: {namespace_info["fqn"]}')
        print(f'  Owner: {namespace_info["owner"]}')
        print(f'  Registration height: {namespace_info["height"]}')

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

Download source

import { PrivateKey } from 'symbol-sdk';
import {
    NemFacade,
    NetworkTimestamp,
    calculateNamespaceRentalFee,
    calculateTransactionFee,
    models
} from 'symbol-sdk/nem';

const NODE_URL = process.env.NODE_URL ||
    'http://libertalia.nemtest.net:7890';
console.log('Using node', NODE_URL);

const SIGNER_PRIVATE_KEY = process.env.SIGNER_PRIVATE_KEY ||
    '0000000000000000000000000000000000000000000000000000000000000000';
const signerKeyPair = new NemFacade.KeyPair(
    new PrivateKey(SIGNER_PRIVATE_KEY));

const facade = new NemFacade('testnet');
const signerAddress = facade.network.publicKeyToAddress(
    signerKeyPair.publicKey);
console.log('Signer address:', signerAddress.toString());

try {
    // Fetch current network time
    const timePath = '/time-sync/network-time';
    console.log('Fetching current network time from', timePath);
    const timeResponse = await fetch(`${NODE_URL}${timePath}`);
    const timeJSON = await timeResponse.json();
    const networkTime = Math.floor(timeJSON.receiveTimeStamp / 1000);
    console.log('  Network time:', networkTime,
        's since the nemesis block');

    // Derived fields from network time
    const timestamp = new NetworkTimestamp(networkTime);
    const deadline = timestamp.addHours(2);

    // Build the namespace name
    const namespaceName = process.env.ROOT_NAMESPACE ||
        `ns_${Math.floor(Date.now() / 1000)}`;
    console.log('Creating root namespace:', namespaceName);

    // Build the transaction
    const rentalFee = calculateNamespaceRentalFee(true);
    console.log('  Namespace lease fee:',
        `${Number(rentalFee) / 1_000_000} XEM`);

    const transaction = facade.transactionFactory.create({
        type: 'namespace_registration_transaction_v1',
        signerPublicKey: signerKeyPair.publicKey.toString(),
        timestamp: timestamp.timestamp,
        deadline: deadline.timestamp,
        rentalFeeSink: 'TAMESPACEWH4MKFMBCVFERDPOOP4FK7MTDJEYP35',
        rentalFee,
        name: namespaceName
    });


    // Calculate and attach the transaction fee
    const fee = calculateTransactionFee(transaction);
    transaction.fee = new models.Amount(fee);
    console.log(`  Transaction fee: ${Number(fee) / 1_000_000} XEM`);

    // Sign transaction and generate final payload
    const signature = facade.signTransaction(signerKeyPair, transaction);
    const jsonPayload = facade.transactionFactory.static.attachSignature(
        transaction, signature);
    console.log('Built transaction:');
    console.dir(transaction.toJson(), { colors: true });

    // Announce the transaction
    const announcePath = '/transaction/announce';
    console.log('Announcing namespace registration to', announcePath);
    const announceResponse = await fetch(`${NODE_URL}${announcePath}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: jsonPayload
    });
    const announceResult = await announceResponse.json();
    console.log('  Result:', announceResult.message);

    // Wait for confirmation
    if ('SUCCESS' === announceResult.message) {
        const transactionHash = facade.hashTransaction(transaction)
            .toString();
        const statusPath = `/transaction/get?hash=${transactionHash}`;
        console.log('Waiting for confirmation from', statusPath);

        let isConfirmed = false;
        for (let attempt = 1; 120 >= attempt; ++attempt) {
            const response = await fetch(`${NODE_URL}${statusPath}`);

            if (response.ok) {
                const confirmed = await response.json();
                console.log('Transaction confirmed in block',
                    confirmed.meta.height);
                isConfirmed = true;
                break;
            }
            console.log('  Transaction status: pending');
            await new Promise(resolve => { setTimeout(resolve, 1000); });
        }
        if (!isConfirmed)
            console.warn('Confirmation took too long.');
    } else {
        console.log('Transaction rejected:', announceResult.message);
    }

    // Retrieve the namespace
    const namespacePath = `/namespace?namespace=${namespaceName}`;
    console.log('Fetching namespace information from', namespacePath);
    const namespaceResponse = await fetch(`${NODE_URL}${namespacePath}`);
    const namespaceInfo = await namespaceResponse.json();
    console.log('Namespace information:');
    console.log('  Name:', namespaceInfo.fqn);
    console.log('  Owner:', namespaceInfo.owner);
    console.log('  Registration height:', namespaceInfo.height);

} catch (e) {
    console.error(e.message, '| Cause:', e.cause?.code ?? 'unknown');
}

Download source

コードの説明⚓︎

アカウントをセットアップする⚓︎

SIGNER_PRIVATE_KEY = os.getenv(
    'SIGNER_PRIVATE_KEY',
    '0000000000000000000000000000000000000000000000000000000000000000')
signer_key_pair = NemFacade.KeyPair(PrivateKey(SIGNER_PRIVATE_KEY))

facade = NemFacade('testnet')
signer_address = facade.network.public_key_to_address(
    signer_key_pair.public_key)
print(f'Signer address: {signer_address}')
const SIGNER_PRIVATE_KEY = process.env.SIGNER_PRIVATE_KEY ||
    '0000000000000000000000000000000000000000000000000000000000000000';
const signerKeyPair = new NemFacade.KeyPair(
    new PrivateKey(SIGNER_PRIVATE_KEY));

const facade = new NemFacade('testnet');
const signerAddress = facade.network.publicKeyToAddress(
    signerKeyPair.publicKey);
console.log('Signer address:', signerAddress.toString());

スニペットは、署名者の秘密鍵を SIGNER_PRIVATE_KEY 環境変数から読み込みます。 設定されていない場合は、テスト用のデフォルトキーを使用します。 署名者のアドレスは公開鍵から導出されます。 このアカウントが登録したネームスペースを所有します。

ネットワーク時刻を取得する⚓︎

    # Fetch current network time
    time_path = '/time-sync/network-time'
    print(f'Fetching current network time from {time_path}')
    with urllib.request.urlopen(f'{NODE_URL}{time_path}') as response:
        response_json = json.loads(response.read().decode())
        network_time = response_json['receiveTimeStamp'] // 1000
        print(f'  Network time: {network_time} s since the nemesis block')

    # Derived fields from network time
    timestamp = NetworkTimestamp(network_time)
    deadline = timestamp.add_hours(2)
    // Fetch current network time
    const timePath = '/time-sync/network-time';
    console.log('Fetching current network time from', timePath);
    const timeResponse = await fetch(`${NODE_URL}${timePath}`);
    const timeJSON = await timeResponse.json();
    const networkTime = Math.floor(timeJSON.receiveTimeStamp / 1000);
    console.log('  Network time:', networkTime,
        's since the nemesis block');

    // Derived fields from network time
    const timestamp = new NetworkTimestamp(networkTime);
    const deadline = timestamp.addHours(2);

ネットワーク時刻は /time-sync/network-time GET から取得し、XEM を送信する チュートリアルで説明されている手順に従って、トランザクションの timestampdeadline フィールドを導出します。

ネームスペース名を設定する⚓︎

    # Build the namespace name
    namespace_name = os.getenv('ROOT_NAMESPACE', f'ns_{int(time.time())}')
    print(f'Creating root namespace: {namespace_name}')
    // Build the namespace name
    const namespaceName = process.env.ROOT_NAMESPACE ||
        `ns_${Math.floor(Date.now() / 1000)}`;
    console.log('Creating root namespace:', namespaceName);

ネームスペースは名前で識別され、その名前をトランザクションによってネットワーク上で 1 年間予約します。 命名規則については、テキストブックの 名前 を参照してください。

チュートリアルを複数回実行したときの衝突を避けるため、名前にタイムスタンプを追加します。 ただし、実際のプログラムでは、ネームスペースに固定名を使用します。 ROOT_NAMESPACE 環境変数を使うと、チュートリアルで固定名を使用できます。

トランザクションを構築する⚓︎

    # Build the transaction
    rental_fee = calculate_namespace_rental_fee(True)
    print(f'  Namespace lease fee: {rental_fee / 1_000_000} XEM')

    transaction = facade.transaction_factory.create({
        'type': 'namespace_registration_transaction_v1',
        'signer_public_key': signer_key_pair.public_key,
        'timestamp': timestamp.timestamp,
        'deadline': deadline.timestamp,
        'rental_fee_sink': 'TAMESPACEWH4MKFMBCVFERDPOOP4FK7MTDJEYP35',
        'rental_fee': rental_fee,
        'name': namespace_name
    })
    // Build the transaction
    const rentalFee = calculateNamespaceRentalFee(true);
    console.log('  Namespace lease fee:',
        `${Number(rentalFee) / 1_000_000} XEM`);

    const transaction = facade.transactionFactory.create({
        type: 'namespace_registration_transaction_v1',
        signerPublicKey: signerKeyPair.publicKey.toString(),
        timestamp: timestamp.timestamp,
        deadline: deadline.timestamp,
        rentalFeeSink: 'TAMESPACEWH4MKFMBCVFERDPOOP4FK7MTDJEYP35',
        rentalFee,
        name: namespaceName
    });

ネームスペース登録トランザクションでは、次の項目を指定してネットワークにネームスペースを登録します。

  • : ネームスペース登録トランザクションでは、タイプ NamespaceRegistrationTransactionV1 を使用します。

  • : トランザクションに署名して手数料を支払うアカウント。 登録したネームスペースの所有者になります。

  • : ネットワーク時刻の手順で計算した値。

  • : ネームスペースの レンタル手数料 を集める特別なアカウント。 各ネットワークには固定されたシンクアドレスがあります。

    ネットワークは、レンタル手数料を他のアドレスへ送るトランザクションを拒否します。

  • : ルートネームスペースのレンタル手数料である 100 XEM。 SDK の ヘルパーは、必要な金額を返します。 引数は、ルートネームスペースの手数料を要求します。

    ネットワークは、この手数料を下回る金額を支払うトランザクションを拒否します。 より大きい金額は受け付けられますが、全額がシンクアカウントへ送られます。

  • : ルートネームスペースの名前。

    # Calculate and attach the transaction fee
    fee = calculate_transaction_fee(transaction)
    transaction.fee = Amount(fee)
    print(f'  Transaction fee: {fee / 1_000_000} XEM')
    // Calculate and attach the transaction fee
    const fee = calculateTransactionFee(transaction);
    transaction.fee = new models.Amount(fee);
    console.log(`  Transaction fee: ${Number(fee) / 1_000_000} XEM`);

最後に、 でトランザクション手数料を計算し、トランザクションに付加します。 レンタル手数料とは異なり、トランザクション手数料は ハーベスターアカウント に支払われます。 ネームスペース登録トランザクションの固定手数料は 0.15 XEM で、手数料表 に示されています。

トランザクションを送信する⚓︎

    # Sign transaction and generate final payload
    signature = facade.sign_transaction(signer_key_pair, transaction)
    json_payload = facade.transaction_factory.attach_signature(
        transaction, signature)
    print('Built transaction:')
    print(json.dumps(transaction.to_json(), indent=2))

    # Announce the transaction
    announce_path = '/transaction/announce'
    print(f'Announcing namespace registration to {announce_path}')
    announce_request = urllib.request.Request(
        f'{NODE_URL}{announce_path}',
        data=json_payload.encode(),
        headers={'Content-Type': 'application/json'},
        method='POST'
    )
    with urllib.request.urlopen(announce_request) as response:
        announce_result = json.loads(response.read().decode())
    print(f'  Result: {announce_result['message']}')
    // Sign transaction and generate final payload
    const signature = facade.signTransaction(signerKeyPair, transaction);
    const jsonPayload = facade.transactionFactory.static.attachSignature(
        transaction, signature);
    console.log('Built transaction:');
    console.dir(transaction.toJson(), { colors: true });

    // Announce the transaction
    const announcePath = '/transaction/announce';
    console.log('Announcing namespace registration to', announcePath);
    const announceResponse = await fetch(`${NODE_URL}${announcePath}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: jsonPayload
    });
    const announceResult = await announceResponse.json();
    console.log('  Result:', announceResult.message);

XEM を送信する チュートリアルと同じ手順で、トランザクションに署名してアナウンスします。

    # Wait for confirmation
    if 'SUCCESS' == announce_result['message']:
        status_path = (
            f'/transaction/get?hash={
                facade.hash_transaction(transaction)}')
        print(f'Waiting for confirmation from {status_path}')
        is_confirmed = False
        for attempt in range(120):
            try:
                with urllib.request.urlopen(
                    f'{NODE_URL}{status_path}'
                ) as response:
                    confirmed = json.loads(response.read().decode())
                    height = confirmed['meta']['height']
                    print(f'Transaction confirmed in block {height}')
                    is_confirmed = True
                    break
            except urllib.error.HTTPError:
                print('  Transaction status: pending')
            time.sleep(1)
        if not is_confirmed:
            print('Confirmation took too long.')
    else:
        print(f'Transaction rejected: {announce_result['message']}')
    // Wait for confirmation
    if ('SUCCESS' === announceResult.message) {
        const transactionHash = facade.hashTransaction(transaction)
            .toString();
        const statusPath = `/transaction/get?hash=${transactionHash}`;
        console.log('Waiting for confirmation from', statusPath);

        let isConfirmed = false;
        for (let attempt = 1; 120 >= attempt; ++attempt) {
            const response = await fetch(`${NODE_URL}${statusPath}`);

            if (response.ok) {
                const confirmed = await response.json();
                console.log('Transaction confirmed in block',
                    confirmed.meta.height);
                isConfirmed = true;
                break;
            }
            console.log('  Transaction status: pending');
            await new Promise(resolve => { setTimeout(resolve, 1000); });
        }
        if (!isConfirmed)
            console.warn('Confirmation took too long.');
    } else {
        console.log('Transaction rejected:', announceResult.message);
    }

次にコードは、トランザクションがブロックに含まれるまで /transaction/get GET エンドポイントをポーリングし、承認を待ちます。

ネームスペースを取得する⚓︎

    # Retrieve the namespace
    namespace_path = f'/namespace?namespace={namespace_name}'
    print(f'Fetching namespace information from {namespace_path}')
    with urllib.request.urlopen(
        f'{NODE_URL}{namespace_path}'
    ) as response:
        namespace_info = json.loads(response.read().decode())
        print('Namespace information:')
        print(f'  Name: {namespace_info["fqn"]}')
        print(f'  Owner: {namespace_info["owner"]}')
        print(f'  Registration height: {namespace_info["height"]}')
    // Retrieve the namespace
    const namespacePath = `/namespace?namespace=${namespaceName}`;
    console.log('Fetching namespace information from', namespacePath);
    const namespaceResponse = await fetch(`${NODE_URL}${namespacePath}`);
    const namespaceInfo = await namespaceResponse.json();
    console.log('Namespace information:');
    console.log('  Name:', namespaceInfo.fqn);
    console.log('  Owner:', namespaceInfo.owner);
    console.log('  Registration height:', namespaceInfo.height);

ネームスペースが登録されたことを確認するため、コードは /namespace GET エンドポイントを使ってネットワークから取得し、そのプロパティを表示します。

成功したレスポンスは、ネームスペースが登録されてアクティブになったことを確認します。

レスポンスには登録時の高さも表示されます。これはネームスペースが登録されたブロックで、1 年間のリースの開始を示します。

出力⚓︎

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

Using node http://libertalia.nemtest.net:7890
Signer address: TBONKWCOWBZYZB2I5JD3LSDBQVBYHB757VN3SKPP
Fetching current network time from /time-sync/network-time
  Network time: 355503793 s since the nemesis block
Creating root namespace: ns_1783091378
  Namespace lease fee: 100.0 XEM
  Transaction fee: 0.15 XEM
Built transaction:
{
  "type": 8193,
  "version": 1,
  "network": 152,
  "timestamp": 355503793,
  "signer_public_key": "462EE976890916E54FA825D26BDD0235F5EB5B6A143C199AB0AE5EE9328E08CE",
  "signature": "D15220D1888AC85CE205D4D2B1AF3540CA415716DD266A29646FE0DEFAFBED924F0B698C4F6EEAA706AA836FA82516552D54B5BCE91D841D6F1C865633EED50D",
  "fee": "150000",
  "deadline": 355510993,
  "rental_fee_sink": "54414D4553504143455748344D4B464D42435646455244504F4F5034464B374D54444A4559503335",
  "rental_fee": "100000000",
  "name": "6e735f31373833303931333738"
}
Announcing namespace registration to /transaction/announce
  Result: SUCCESS
Waiting for confirmation from /transaction/get?hash=D56EDC5946F1A41304CDDC2BC322793C558DFB57831EF7D45024DE46D6AD827F
  Transaction status: pending
  Transaction status: pending
  Transaction status: pending
Transaction confirmed in block 685363
Fetching namespace information from /namespace?namespace=ns_1783091378
Namespace information:
  Name: ns_1783091378
  Owner: TBONKWCOWBZYZB2I5JD3LSDBQVBYHB757VN3SKPP
  Registration height: 685363

出力の要点は次のとおりです。

  • ネームスペース名(5 行目): 選択した名前 ns_1783091378 には、一意性を確保するためのタイムスタンプが含まれています。 この名前を NEM テストネットエクスプローラー で検索すると、ネームスペースの詳細を確認できます。

  • レンタル手数料とトランザクション手数料(6~7 行目): ルートネームスペースなのでレンタル手数料は 100 XEM です(サブネームスペース は代わりに 10 XEM を支払います)。トランザクション手数料は 0.15 XEM です。

  • ネームスペース情報(31~33 行目): 登録されたネームスペース、その所有者(署名者のアドレス)、登録時の高さ。リースが開始したブロックの高さです。

まとめ⚓︎

このチュートリアルでは、次の方法を説明しました。

手順 関連ドキュメント
ネームスペース登録トランザクションを構築する NamespaceRegistrationTransactionV1
レンタル手数料を計算する
ネームスペースを取得する /namespace GET

次のステップ⚓︎

ルートネームスペースを取得できたので、次のことを行えます。