Skip to main content

SDK Client Library Usage

Installing the SDKs

Use npm or yarn to install the casper-js-sdk package:

npm install casper-js-sdk
yarn install casper-js-sdk

Creating Accounts

You may use the SDKs to interact with accounts on a Casper network. Accounts can use either an Ed25519 or Secp256k1 digital signature scheme. See the Accounts and Cryptographic Keys page for more details.

Creating new account keys

const { Keys } = require("casper-js-sdk");
const keypair = Keys.Ed25519.new();
const { publicKey, privateKey } = keypair;

Replace Ed25519 with Secp256K1 if you wish.

Exporting the public key and account hash

The keypair variable contains the private and public key pair for the account. You can use, read, or export the public key. You may also want access to the account hash, often used within smart contracts on a Casper network. The following methods show how to extract the public key and account hash.

// Create a hexadecimal representation of the public key and account hash.
const publicKeyHex = publicKey.toHex();
const accountHashHex = publicKey.toAccountHashStr();

Note that accountHashHex will be prefixed with the text "account-hash-".

Uploading the secret key from a file

To use a specific account, you should not include the private key in the source code; instead, upload the account's secret key from a local file. Update the path to the file in the example below.

const { Keys } = require("casper-js-sdk");
const keypair = Keys.Ed25519.loadKeyPairFromPrivateFile("./secret_key.pem");

Replace Ed25519 with Secp256K1 if you wish.


Transferring CSPR

Using the keypair created above, you can sign a deploy that transfers CSPR.

Replace the NODE_ADDRESS and corresponding RPC port with an active node on the network. You can find active online peers for Mainnet on cspr.live and for Testnet on testnet.cspr.live. The RPC port is usually 7777, but it depends on the network's configuration settings.

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

const casperClient = new CasperClient("http://NODE_ADDRESS:7777/rpc");
const receipientPublicKeyHex = "01e8c84f4fbb58d37991ef373c08043a45c44cd7f499453fa2bd3e141cc0113b3c";

const amount = 2.5e9; // Minimum transfer: 2.5 CSPR
let deployParams = new DeployUtil.DeployParams(
keypair.publicKey,
"casper", // or "casper-test" for Testnet
);

const session = DeployUtil.ExecutableDeployItem.newTransferWithOptionalTransferId(amount, recipientPublicKeyHex);

const payment = DeployUtil.standardPayment(0.1e9); // Gas payment in motes: 0.1 CSPR
const deploy = DeployUtil.makeDeploy(deployParams, session, payment);
const signedDeploy = DeployUtil.signDeploy(deploy, keypair);

console.log(await casperClient.putDeploy(signedDeploy));

Once submitted, the above snippet will print the deploy hash in the console.


Installing Contracts

To install a contract on the network, you need to sign and send a deploy containing the compiled Wasm.

Replace the NODE_ADDRESS and corresponding RPC port with an active node on the network. You can find active online peers for Mainnet on cspr.live and for Testnet on testnet.cspr.live. The RPC port is usually 7777, but it depends on the network's configuration settings.

const { CasperClient, Contracts, RuntimeArgs, CLValueBuilder } = require("casper-js-sdk");
const fs = require("fs");

const casperClient = new CasperClient("http://NODE_ADDRESS:7777/rpc");
const contract = new Contracts.Contract(casperClient);

const contractWasm = new Uint8Array(fs.readFileSync("/path/to/contract.wasm").buffer);

const runtimeArguments = RuntimeArgs.fromMap({
argument: CLValueBuilder.string("Hello world!"),
});

const deploy = contract.install(
contractWasm,
runtimeArguments,
"10000000000", // Gas payment (10 CSPR)
keypair.publicKey,
"casper", // or "casper-test" for Testnet
[keypair],
);

console.log(await casperClient.putDeploy(deploy));

Once submitted, the above snippet will print the deploy hash in the console.

Staking

Token staking is a fundamental aspect of the Casper Network, whereby users lock up tokens as collateral in exchange for the ability to participate in the blockchain's consensus mechanism and earn rewards. This delegated Proof-of-Stake consensus mechanism is crucial for the network's effective operation. With the aid of any of the Casper SDKs, you can delegate your tokens to validators and participate in staking on the network.

The delegation functionality is available as a smart contract, which can be found in the casper-node repository. To delegate tokens, first clone the repository:

git clone https://github.com/casper-network/casper-node.git
cd casper-node/

Then compile the delegate contract:

make setup-rs
make build-contract-rs/delegate

Now, assuming that you cloned casper-node from your project's root directory, cd back into it:

cd ../

Now in your dApp's backend (or standalone script), load the delegate.wasm file into memory and deploy it with the arguments "amount", "delegator", and "validator" included.

const { CasperClient, Contracts, RuntimeArgs, CLValueBuilder, CLPublicKey } = require("casper-js-sdk");
const fs = require("fs");

const casperClient = new CasperClient("http://NODE_ADDRESS:7777/rpc");
const contract = new Contracts.Contract(casperClient);

const contractWasm = new Uint8Array(fs.readFileSync("./casper-node/target/wasm32-unknown-unknown/release/delegate.wasm").buffer);

const runtimeArguments = RuntimeArgs.fromMap({
amount: CLValueBuilder.u512(500e9), // Minimum delegation amount: 500 CSPR
delegator: keypair.publicKey,
validator: CLPublicKey.fromHex("01e8c84f4fbb58d37991ef373c08043a45c44cd7f499453fa2bd3e141cc0113b3c"),
});

const deploy = contract.install(
contractWasm,
runtimeArguments,
"5000000000", // Gas payment (5 CSPR)
keypair.publicKey,
"casper", // or "casper-test" for testnet
[keypair],
);

(async () => {
console.log(await casperClient.putDeploy(deploy));
})();

Once submitted, the above snippet will print the deploy hash in the console.


Calling Contracts

Smart contracts on a Casper network are invoked by calling entry points. See below how to use Casper's SDKs to interact with these entry points and update the global state from a dApp:

const casperClient = new CasperClient("http://NODE_ADDRESS:7777/rpc");
const contract = new Contracts.Contract(casperClient);
contract.setContractHash("hash-a3cac24aec9de1bbdb87083587b14d8aeffba5dfed27686512b7bb5dee60445d");
const runtimeArguments = RuntimeArgs.fromMap({
message: CLValueBuilder.string("Hello world!"),
});
const deploy = contract.callEntrypoint(
"update_msg",
runtimeArguments,
keypair.publicKey,
"casper", // or "casper-test" for Testnet
"1000000000", // 1 CSPR (10^9 Motes)
[keypair],
);
(async () => {
console.log(await casperClient.putDeploy(deploy));
})();

Once submitted, the above snippet will print the deploy hash in the console.


Staking

Token staking is a fundamental aspect of a Casper network, whereby users lock up tokens as collateral in exchange for the ability to participate in the blockchain's consensus mechanism and earn rewards. This delegated Proof-of-Stake consensus mechanism is crucial for the network's effective operation. With the aid of any of the Casper SDKs, you can delegate your tokens to validators and participate in staking on the network.

The delegation functionality is available as a smart contract, which can be found in the casper-node repository. To delegate tokens, first clone the repository:

git clone https://github.com/casper-network/casper-node.git
cd casper-node/

Then compile the delegate contract:

make setup-rs
make build-contract-rs/delegate

Now, navigate back to your project's root directory. In your dApp's backend (or standalone script), load the delegate.wasm file into memory and deploy it with the arguments "amount", "delegator", and "validator" included.

const { CasperClient, Contracts, RuntimeArgs, CLValueBuilder, CLPublicKey } = require("casper-js-sdk");
const fs = require("fs");

const casperClient = new CasperClient("http://NODE_ADDRESS:7777/rpc");
const contract = new Contracts.Contract(casperClient);

const contractWasm = new Uint8Array(fs.readFileSync("./casper-node/target/wasm32-unknown-unknown/release/delegate.wasm").buffer);

const runtimeArguments = RuntimeArgs.fromMap({
amount: CLValueBuilder.u512(500e9), // Minimum delegation amount: 500 CSPR
delegator: keypair.publicKey,
validator: CLPublicKey.fromHex("01e8c84f4fbb58d37991ef373c08043a45c44cd7f499453fa2bd3e141cc0113b3c"),
});

const deploy = contract.install(
contractWasm,
runtimeArguments,
"5000000000", // Gas payment (5 CSPR)
keypair.publicKey,
"casper", // or "casper-test" for testnet
[keypair],
);

(async () => {
console.log(await casperClient.putDeploy(deploy));
})();

Once submitted, the above snippet will print the deploy hash in the console.