📝

Node.js+TypeScriptではじめるSymbol-SDK

に公開

Node.js まわりのバージョン

  • Yarn v4.9.1
  • Node.js v22.15.0

プロジェクトフォルダの作成と初期化

適当な場所に作成します。

bash
mkdir test-project
cd test-project

プロジェクトフォルダを初期化します。

bash
yarn init

yarn が node_modules フォルダを作成するようファイルを作成します。

bash
yarn config set nodeLinker node-modules && yarn config set cacheFolder .yarn/cache

念のため Node.js などのバージョンのピン留めもしておきます。

bash
volta pin node
volta pin npm
volta pin yarn

開発用パッケージのインストールと設定

開発時に使用するパッケージをインストールします。

bash
yarn add -D typescript @types/node tsx eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-config-prettier

ESLint の設定

eslint.config.js を作成&編集。

eslint.config.js
import js from '@eslint/js'
import tsPlugin from '@typescript-eslint/eslint-plugin'
import tsParser from '@typescript-eslint/parser'

export default [
  js.configs.recommended,
  {
    files: ['**/*.ts'],
    languageOptions: {
      parser: tsParser,
      parserOptions: {
        project: './tsconfig.json',
      },
      globals: {
        console: 'readonly',
      },
    },
    plugins: {
      '@typescript-eslint': tsPlugin,
    },
    rules: {},
  },
]

Prettier の設定

.prettierrc.json を作成&編集。

.prettierrc.json
{
  "tabWidth": 2,
  "printWidth": 80,
  "trailingComma": "all",
  "semi": false,
  "singleQuote": true
}

tsconfig.json の作成

tsconfig.json を作成&編集。
TypeScript ソースがなくて includeexclude 付近でエラー出るかもしれませんが、無視してください。

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "nodenext",
    "outDir": "dist",
    "rootDir": "src",
    "declaration": true,
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

package.json の編集

package.json"type": "module" を追加します。これにより、ES モジュールとして扱われるようになります。ついでに使いそうな script も追加しておくと良いと思います。

package.json
{
  "name": "test-project",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "yarn tsx src/index.ts",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "format": "prettier --write \"src/**/*.ts\""
  },
  ...

ESLint がうまく設定ファイルが読み込めない場合があるので、この辺りで「ウィンドウの再読み込み」をしておくと良いと思います。

メニューのコマンドパレットにあります。
表示 → コマンドパレット >reload window

パッケージのインストール

symbol-sdk をインストールします。

bash
yarn add symbol-sdk

動作確認

確認のため簡単なコードを動かしてみます。
src ディレクトリを作成して、その中に index.ts ファイルを作成します。

src/index.ts
import { Bip32 } from 'symbol-sdk'
import { Address, Network, SymbolFacade } from 'symbol-sdk/symbol'

// ニーモニック生成
const bip32 = new Bip32()
const mnemonic = bip32.random()
console.log(`mnemonic: ${mnemonic}`)

// faced生成
const facade = new SymbolFacade(Network.TESTNET)

// ニーモニックから10件アカウントを生成する
const bip32Node = bip32.fromMnemonic(mnemonic, '')
for (let i = 0; i < 10; i++) {
  // Bip32Path生成
  const bip32Path = facade.bip32Path(i)
  // Bip32Pathから子孫Bip32Path生成
  const childBip32Node = bip32Node.derivePath(bip32Path)
  // 子孫Bip32Pathからキーペア生成
  const keyPair = SymbolFacade.bip32NodeToKeyPair(childBip32Node)
  // 公開鍵からアドレス生成
  const address = new Address(
    facade.network.publicKeyToAddress(keyPair.publicKey),
  )
  // 表示
  console.log(
    `[${i}]`,
    `Addr:${address.toString()}`,
    `PubK:${keyPair.publicKey.toString()}`,
    `PriK:${keyPair.privateKey.toString()}`,
  )
}

実行します。

bash
yarn start

ニーモニックと 10 件のアカウントが表示されれば OK です。

さいごに

これでサーバーサイドで動く Symbol アプリ開発ができるようになりました。

Electron や React、Next.js で Symbol-SDK を使用する場合は、別途パッケージをインストールして Wasm を読み込ませる必要があります。方法はまた今度…きっと……

Discussion