JavaScript/TypeScript SDK

このページには、いくつかのJavaScript (JS) クライアントとCasper JS SDKに関連する内容が書かれてあります。

JavaScriptクライアントの使用方法

Casperチームにより実装された、Casperコントラクトとの疎通をサポートする特別なJSクライアントとなっています。

リポジトリとクライアントパッケージ

Casperコントラクト用のクライアント作成に必要なリポジトリを提供しています。 casper-contracts-js-clientsリポジトリには、Casperコントラクト用のクライアント作成についての詳細と、Casper上のスマートコントラクトとの疎通用のクライアントなどの使用例があります。

下記が、このリポジトリ内にある二つの主なクライアントです。

これらのパッケージには、インストールとCasperコントラクトとの疎通において簡単な方法をご用意しています。

JavaScript Casper SDK

TypeScript/JavaScript SDKによって、開発者はTypeScriptやJavaScriptを使ったCasperネットワークとのやり取りができるようになります。この項では、Casper JS SDKを使用する異なるサンプルをご用意しています。

インストレーション

Node.jsを使ってライブラリをインストールするには、下記コマンドを実行してください。

npm install casper-js-sdk@next --save

テスト

このライブラリを使用する上での基本的な例は,testディレクトリにあります。下記コマンドを使って、テストを実行します。

npm run test

サンプルの使い方

このセクションでは、JavaScript SDKで対応可能な必須タスクの概要をお伝えします。

  • アカウント鍵の生成
  • 転送の送信

アカウント鍵(キー)の生成

この例では、SDKを使ったデプロイに署名するアカウントキーの生成方法を紹介します。

const fs = require("fs");
const path = require("path");
const { Keys } = require("casper-js-sdk");

const createAccountKeys = () => {
    // Generating keys
    const edKeyPair = Keys.Ed25519.new();
    const { publicKey, privateKey } = edKeyPair;

    // Create a hexadecimal representation of the public key
    const accountAddress = publicKey.toHex();

    // Get the account hash (Uint8Array) from the public key
    const accountHash = publicKey.toAccountHash();

    // Store keys as PEM files
    const publicKeyInPem = edKeyPair.exportPublicKeyInPem();
    const privateKeyInPem = edKeyPair.exportPrivateKeyInPem();

    const folder = path.join("./", "casper_keys");

    if (!fs.existsSync(folder)) {
        const tempDir = fs.mkdirSync(folder);
    }

    fs.writeFileSync(folder + "/" + accountAddress + "_public.pem", publicKeyInPem);
    fs.writeFileSync(folder + "/" + accountAddress + "_private.pem", privateKeyInPem);

    return accountAddress;
};

const newAccountAddress = createAccountKeys();

コードにて鍵を生成した後は、Casper Wallet Chrome 拡張機能に追加しトランザクションへの署名を行えるようになります。

転送(トランスファー)の送信

このコードブロックを見ていただければ、Casperネットワーク上での転送の定義方法や送信方法が分かります。下記コードにあるsender-public-keyrecipient-public-keyを、以下のコードに置き換えてください。

下記のsendTransfer関数は、transfer-hashを戻り値として返します。これは、https://testnet.cspr.live/でも確認できます。

const fs = require("fs");
const path = require("path");
const axios = require("axios");
const casperClientSDK = require("casper-js-sdk");

const { Keys, CasperClient, CLPublicKey, DeployUtil } = require("casper-js-sdk");

const RPC_API = "http://159.65.203.12:7777/rpc";
const STATUS_API = "http://159.65.203.12:8888";

const sendTransfer = async ({ from, to, amount }) => {
    const casperClient = new CasperClient(RPC_API);

    const folder = path.join("./", "casper_keys");

    // Read keys from the structure created in #Generating keys
    const signKeyPair = Keys.Ed25519.parseKeyFiles(folder + "/" + from + "_public.pem", folder + "/" + from + "_private.pem");

    // networkName can be taken from the status api
    const response = await axios.get(STATUS_API + "/status");

    let networkName = null;

    if (response.status == 200) {
        networkName = response.data.chainspec_name;
    }

    // For native-transfers the payment price is fixed
    const paymentAmount = 100000000;

    // transfer_id field in the request to tag the transaction and to correlate it to your back-end storage
    const id = 187821;

    // gasPrice for native transfers can be set to 1
    const gasPrice = 1;

    // Time that the deploy will remain valid for, in milliseconds
    // The default value is 1800000 ms (30 minutes)
    const ttl = 1800000;

    let deployParams = new DeployUtil.DeployParams(signKeyPair.publicKey, networkName, gasPrice, ttl);

    // We create a hex representation of the public key with an added prefix
    const toPublicKey = CLPublicKey.fromHex(to);

    const session = DeployUtil.ExecutableDeployItem.newTransfer(amount, toPublicKey, null, id);

    const payment = DeployUtil.standardPayment(paymentAmount);
    const deploy = DeployUtil.makeDeploy(deployParams, session, payment);
    const signedDeploy = DeployUtil.signDeploy(deploy, signKeyPair);

    // Here we are sending the signed deploy
    return await casperClient.putDeploy(signedDeploy);
};

sendTransfer({
    // Put here the public key of the sender's main purse. Note that it needs to have a balance greater than 2.5 CSPR
    from: "<sender-public-key>",

    // Put here the public key of the recipient's main purse. This account doesn't need to exist. If the key is correctly formatted, the network will create the account when the deploy is sent
    to: "<recipient-public-key>",

    // Minimal amount is 2.5 CSPR (1 CSPR = 1,000,000,000 motes)
    amount: 25000000000,
});

:如何なる時も、この例にあるデプロイをJSONにシリアライズし、やろうとしていることを実行できます(保存、送信など)。

以下は、デプロイをシリアル化するコードです。

const jsonFromDeploy = DeployUtil.deployToJson(signedDeploy);

そして、この機能を使って、デプロイオブジェクトを再構築することができます。

const deployFromJson = DeployUtil.deployFromJson(jsonFromDeploy);