CKB SDK Rust

The Rust SDK for Nervos CKB provides several essential features for developers:

These features allow for seamless interaction with CKB and facilitate the development of decentralized applications on the CKB network.

Install

```toml

Cargo.toml

[dependencies]

ckb-sdk = "2.5.0" ```

Build

Build:

bash cargo build

Run unit tests:

make test

Please refer to the Makefile for more compilation commands.

Quick start

Setup

ckb-sdk-rust provides a convenient client that enables you to easily interact with CKB nodes.

```rust use ckb_sdk::rpc::CkbRpcClient;

let mut ckbclient = CkbRpcClient::new("https://testnet.ckb.dev"); let block = ckbclient.getblockbynumber(0.into()).unwrap(); println!("block: {}", serdejson::tostringpretty(&block).unwrap()); ```

For more details about CKB RPC APIs, please refer to the CKB RPC doc.

Build transaction by manual

The following code example demonstrates how to construct a transfer transaction on CKB. You can use it to transfer a specified amount of CKB from one address to another.

NOTE: The address and key are for demo purposes only and should not be used in a production environment.

```rust use ckbsdk::{ constants::SIGHASHTYPEHASH, rpc::CkbRpcClient, traits::{ DefaultCellCollector, DefaultCellDepResolver, DefaultHeaderDepResolver, DefaultTransactionDependencyProvider, SecpCkbRawKeySigner, }, txbuilder::{transfer::CapacityTransferBuilder, CapacityBalancer, TxBuilder}, unlock::{ScriptUnlocker, SecpSighashUnlocker}, Address, HumanCapacity, ScriptId, }; use ckb_types::{ bytes::Bytes, core::BlockView, h256, packed::{CellOutput, Script, WitnessArgs}, prelude::*, }; use std::{collections::HashMap, str::FromStr};

// Prepare the necessary data for a CKB transaction: // * set the RPC endpoint for the testnet // * define the sender's address and secret key // * define the recipient's address // * specify the capacity to transfer let ckbrpc = "https://testnet.ckb.dev:8114"; let sender = Address::fromstr("ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqf7v2xsyj0p8szesqrwqapvvygpc8hzg9sku954v").unwrap(); let senderkey = secp256k1::SecretKey::fromslice( h256!("0xef4dfe655b3df20838bdd16e20afc70dfc1b9c3e87c54c276820315a570e6555").asbytes(), ) .unwrap(); let receiver = Address::fromstr("ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqvglkprurm00l7hrs3rfqmmzyy3ll7djdsujdm6z").unwrap(); let capacity = HumanCapacity::from_str("100.0").unwrap();

// Build ScriptUnlocker let signer = SecpCkbRawKeySigner::newwithsecretkeys(vec![senderkey]); let sighashunlocker = SecpSighashUnlocker::from(Box::new(signer) as Box<_>); let sighashscriptid = ScriptId::newtype(SIGHASHTYPEHASH.clone()); let mut unlockers = HashMap::default(); unlockers.insert( sighashscriptid, Box::new(sighash_unlocker) as Box, );

// Build CapacityBalancer let placeholderwitness = WitnessArgs::newbuilder() .lock(Some(Bytes::from(vec![0u8; 65])).pack()) .build(); let balancer = CapacityBalancer::newsimple(sender.payload().into(), placeholderwitness, 1000);

// Build: // * CellDepResolver // * HeaderDepResolver // * CellCollector // * TransactionDependencyProvider let mut ckbclient = CkbRpcClient::new(ckbrpc); let celldepresolver = { let genesisblock = ckbclient.getblockbynumber(0.into()).unwrap().unwrap(); DefaultCellDepResolver::fromgenesis(&BlockView::from(genesisblock)).unwrap() }; let headerdepresolver = DefaultHeaderDepResolver::new(ckbrpc); let mut cellcollector = DefaultCellCollector::new(ckbrpc); let txdepprovider = DefaultTransactionDependencyProvider::new(ckb_rpc, 10);

// Build the transaction let output = CellOutput::newbuilder() .lock(Script::from(&receiver)) .capacity(capacity.0.pack()) .build(); let builder = CapacityTransferBuilder::new(vec![(output, Bytes::default())]); let (tx, ) = builder .buildunlocked( &mut cellcollector, &celldepresolver, &headerdepresolver, &txdep_provider, &balancer, &unlockers, ) .unwrap(); ```

Generate a new address

In CKB, a private key can be used to generate a public key, which is then hashed using the Blake2b hashing algorithm to produce a CKB address. The public key is derived from the private key using the secp256k1 elliptic curve cryptography algorithm. This process results in a unique CKB address that can be used to receive or send CKB tokens. It is important to keep the private key secure, as anyone with access to it can potentially access the associated CKB funds.

```rust use ckb_sdk::types::{Address, AddressPayload, NetworkType}; use rand::Rng;

let mut rng = rand::threadrng(); let privkeybytes: [u8; 32] = rng.gen(); let secpsecretkey = secp256k1::SecretKey::fromslice(&privkeybytes).unwrap(); let pubkey = secp256k1::PublicKey::fromsecretkey(&ckbcrypto::secp::SECP256K1, &secpsecretkey); let payload = AddressPayload::frompubkey(&pubkey); let address = Address::new(NetworkType::Mainnet, payload, true); println!("address: {}", address.to_string()); ```

Parse address

In the world of CKB, a lock script can be represented as an address. It is possible to parse an address from an encoded string and then obtain its network and script.

```rust use ckbsdk::types::Address; use ckbtypes::packed::Script; use std::str::FromStr;

let addrstr = "ckb1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqgvf0k9sc40s3azmpfvhyuudhahpsj72tsr8cx3d"; let addr = Address::fromstr(addr_str).unwrap(); let _network = addr.network(); let _script: Script = addr.payload().into(); ```

For more details please about CKB address refer to CKB rfc 0021.

More Examples

You can try compiling them by running the following command in your terminal:

sh cargo build --examples

For more use cases of building transactions with CKB node, please refer to these examples and unit tests.

License

The SDK is available as open source under the terms of the MIT License.

ChangeLog

See CHANGELOG for more details.