Skip to content

casper-ecosystem/cep-95-js-client

Repository files navigation

@casper-ecosystem/cep-95-js-client

npm version casper-js-sdk peer TypeScript CEP-95 ERC-721 compatible license changelog

JavaScript/TypeScript client for CEP-95 (ERC-721 equivalent) NFT contracts on the Casper Network.

CEP-95 is the Casper NFT standard - each token is unique, indivisible, and identified by a U256 token ID. This library provides a clean, typed interface for all read and write operations defined by the standard.

Built on top of casper-js-sdk.


Installation

npm install @casper-ecosystem/cep-95-js-client casper-js-sdk

Quick start

import { Cep95Client } from '@casper-ecosystem/cep-95-js-client';
import { PublicKey, PrivateKey, KeyAlgorithm } from 'casper-js-sdk';

const client = new Cep95Client('http://<Node Address>:7777/rpc', 'casper-test');

client.setContractHash(
  'contract-hash-834d3e29...', // versioned contract hash (for reads)
  'contract-package-712bf529...' // contract package hash (for writes)
);

// Read collection info
const name = await client.name(); // "NAME"
const symbol = await client.symbol(); // "SYM"
const totalSupply = await client.totalSupply(); // "10000"

// Query per-account / per-token state
const alice = PublicKey.fromHex('01aabbcc...');
const balance = await client.balanceOf(alice);
const owner = await client.ownerOf('42');
const meta = await client.tokenMetadata('42');

// Submit a transfer
const privateKey = await PrivateKey.generate(KeyAlgorithm.ED25519);
const recipient = PublicKey.fromHex('01ddeeff...');

const result = await client.transferFrom({
  args: { from: privateKey.publicKey, to: recipient, tokenId: '42' },
  params: { sender: privateKey.publicKey, paymentAmount: '2500000000', signingKeys: [privateKey] }
});

console.log('TX hash:', result.transactionInfo.transactionHash.toHex());

Awaiting on-chain execution (SSE)

By default write methods return as soon as the node accepts the transaction. Pass sseUrl and waitForTransactionProcessed: true to block until the node confirms execution and receive the executionResult:

const client = new Cep95Client(
  'http://<Node Address>:7777/rpc',
  'casper-test',
  'http://<Node Address>:9999/events/main' // SSE stream URL
);

// or set it later:
client.sseUrl = 'http://<Node Address>:9999/events/main';

const result = await client.mint({
  args: { to: recipient, tokenId: '100' },
  params: { sender: privateKey.publicKey, paymentAmount: '5000000000', signingKeys: [privateKey] },
  waitForTransactionProcessed: true
});

console.log('TX hash:', result.transactionInfo.transactionHash.toHex());
console.log('Error (if any):', result.executionResult?.errorMessage ?? 'none');

waitForTransactionProcessed is silently ignored when sseUrl is not set, so it is safe to always pass it and configure the URL only when needed. The SSE subscription times out after 60 seconds and rejects with an error.


API

Cep95Client

Constructor

new Cep95Client(rpcUrl: string, chainName?: string, sseUrl?: string)
Parameter Description
rpcUrl Full URL of the Casper node RPC endpoint (e.g. http://node:7777/rpc).
chainName Chain name for write transactions - "casper" (mainnet) or "casper-test" (testnet).
sseUrl Optional SSE event-stream URL (e.g. http://node:9999/events/main). Required for waitForTransactionProcessed.

Properties

Property Type Description
chainName string | undefined Chain name used in write transactions.
sseUrl string | undefined SSE stream URL for awaiting on-chain execution.

Methods

Method Description
setContractHash(hash, packageHash?) Configure target contract. Accepts bare hex or prefixed strings. Returns this.
name() Returns the NFT collection name (String).
symbol() Returns the NFT collection symbol (String).
totalSupply() Returns the total number of minted tokens (U256 as decimal string).
balanceOf(owner) Returns the token balance of owner. Returns "0" if no entry exists.
ownerOf(tokenId) Returns the owner of a token as a prefixed string. Throws if token does not exist.
getApproved(tokenId) Returns the approved spender for a token, or null.
isApprovedForAll(owner, operator) Returns true if operator has blanket approval over owner's tokens.
tokenMetadata(tokenId) Returns on-chain metadata as Record<string, string>. Returns {} if absent.
transferFrom(params) Transfers a token from one account to another.
approve(params) Approves a spender for a specific token.
revokeApproval(params) Revokes a single-token approval.
approveForAll(params) Grants an operator blanket permission over all caller's tokens.
revokeApprovalForAll(params) Revokes blanket operator permission.
mint(params) Mints a new token (requires minting to be enabled on the contract).
burn(params) Burns (destroys) a token.

Storage layout

Understanding the on-chain layout is helpful when debugging or reading state directly.

Named keys (scalar fields)

Named key CL type Description
name String NFT collection name
symbol String NFT collection symbol
total_supply U256 Total number of minted tokens

Dictionaries (mappings)

Dictionary Key encoding Value type Description
balances Base64(CLValue(Key).bytes()) U256 Token count per owner
owners Base64(CLValue(U256 tokenId).bytes()) Key Owner of each token
approvals Base64(CLValue(U256 tokenId).bytes()) Key Approved spender per token
operators hex(blake2b‑256(ownerKeyBytes || operatorKeyBytes)) Bool Blanket operator approvals
token_metadata Base64(CLValue(U256 tokenId).bytes()) BTreeMap<String, String> Per-token metadata key-value pairs

Write operations

All write methods accept a params object:

type Cep95TransactionParams = {
  sender: PublicKey; // account paying for the transaction
  paymentAmount: string; // gas in motes ("2500000000" = 2.5 CSPR)
  signingKeys?: PrivateKey[]; // signs the transaction before submission
  chainName?: string; // overrides the client-level chain name
};

And return:

type Cep95TransactionResult = {
  transactionInfo: PutTransactionResult; // always present
  executionResult?: ExecutionResult; // populated when waitForTransactionProcessed: true
};

All write methods also accept an optional waitForTransactionProcessed flag:

type TransferFromParams = {
  args: TransferFromArgs;
  params: Cep95TransactionParams;
  waitForTransactionProcessed?: boolean; // set sseUrl on the client to enable
};

When waitForTransactionProcessed: true and client.sseUrl is set, the method subscribes to the SSE stream and resolves only after the node emits a TransactionProcessed event for the submitted hash. executionResult.errorMessage is non-null when the transaction was reverted on-chain.


Finding contract hashes

  • Contract hash - used for all reads. Open the contract package on cspr.live or testnet.cspr.live, go to Contract Versions, and copy the hash of the latest version.
  • Contract package hash - used for all writes. It is the hash in the URL: cspr.live/contract-package/{packageHash}.

Both accept bare hex, "contract-hash-...", "hash-...", or "contract-package-..." prefixed strings.


Cep95Entity - accepted identity types

All methods that take an owner, operator, from, to, or spender accept any of:

  • PublicKey - resolved to its account-hash
  • AccountHash
  • ContractHash
  • ContractPackageHash
  • AddressableEntityHash

Playground

An interactive playground for exploring and testing CEP-95 contracts is available at:

https://casper-ecosystem.github.io/cep-95-js-client/

It lets you connect any deployed CEP-95 contract and run all read and write operations directly from the browser - no local setup required.

Features

  • Read operations - query collection info, token ownership, approvals, balances, and metadata
  • Write operations - transfer, approve, mint, burn, and operator management via cspr.click wallet integration
  • Custom RPC - point at any Casper node (mainnet or testnet) without an App ID
  • cspr.click proxy - use the cloud-hosted RPC proxy by supplying a CSPR.build App ID
  • SSE - enter an SSE URL (http://node:9999/events/main) to see on-chain execution results (success/failure) directly in the activity log
  • Explorer links - transaction hashes in the activity log link directly to cspr.live

Running locally

# from the repo root
npm install

cd playground
npm install
npm run dev    # http://localhost:3000

Development

npm install
npm test       # run unit tests
npm run build  # compile to dist/

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors