Rust区块链开发库near-primitives-core的使用,NEAR协议核心基础模块与智能合约底层功能实现

Rust区块链开发库near-primitives-core的使用,NEAR协议核心基础模块与智能合约底层功能实现

安装

在项目目录中运行以下Cargo命令:

cargo add near-primitives-core

或者在Cargo.toml中添加以下行:

near-primitives-core = "0.31.0"

基本使用示例

以下是使用near-primitives-core库的基本示例代码:

use near_primitives_core::{
    types::{AccountId, Balance},
    hash::CryptoHash,
    version::PROTOCOL_VERSION,
};

fn main() {
    // 创建账户ID
    let account_id: AccountId = "example.near".parse().unwrap();
    println!("Account ID: {}", account_id);
    
    // 创建余额
    let balance: Balance = 100_000_000_000_000_000_000_000; // 100 NEAR (1 NEAR = 1e24 yoctoNEAR)
    println!("Balance: {}", balance);
    
    // 生成加密哈希
    let hash = CryptoHash::default();
    println!("Default hash: {:?}", hash);
    
    // 获取协议版本
    println!("Protocol version: {}", PROTOCOL_VERSION);
}

高级功能示例

以下是一个更完整的示例,展示如何使用near-primitives-core进行交易构造和签名:

use near_primitives_core::{
    account::AccessKey,
    types::{AccountId, Balance, Gas},
    transaction::{Action, FunctionCallAction, Transaction},
    hash::CryptoHash,
};

fn construct_transaction(
    signer_id: AccountId,
    receiver_id: AccountId,
    public_key: Vec<u8>,
    nonce: u64,
    block_hash: CryptoHash,
) -> Transaction {
    // 创建函数调用动作
    let function_call = FunctionCallAction {
        method_name: "transfer".to_string(),
        args: b"{}".to_vec(),
        gas: Gas(100_000_000_000_000), // 100 TGas
        deposit: 1_000_000_000_000_000_000_000, // 1 NEAR
    };
    
    // 创建交易
    Transaction {
        signer_id,
        public_key,
        nonce,
        receiver_id,
        block_hash,
        actions: vec![Action::FunctionCall(function_call)],
    }
}

fn main() {
    let signer_id: AccountId = "sender.near".parse().unwrap();
    let receiver_id: AccountId = "receiver.near".parse().unwrap();
    let public_key = vec![1, 2, 3, 4]; // 实际应用中应使用真实的公钥
    let nonce = 1;
    let block_hash = CryptoHash::default();
    
    let transaction = construct_transaction(
        signer_id,
        receiver_id,
        public_key,
        nonce,
        block_hash,
    );
    
    println!("Constructed transaction: {:?}", transaction);
}

核心模块功能

near-primitives-core库提供了NEAR协议的核心基础模块,包括:

  1. 账户系统:AccountId、AccessKey等类型
  2. 交易处理:Transaction、Action等类型
  3. 加密功能:CryptoHash、签名验证等
  4. 协议版本:PROTOCOL_VERSION常量
  5. 经济模型:Balance、Gas等类型

智能合约开发

以下是一个使用near-primitives-core与智能合约交互的示例:

use near_primitives_core::{
    types::{AccountId, Balance},
    contract::ContractCode,
    hash::CryptoHash,
};

fn deploy_contract(
    contract_account: AccountId,
    wasm_code: Vec<u8>,
    initial_balance: Balance,
) -> (AccountId, ContractCode, Balance) {
    let contract_code = ContractCode::new(wasm_code);
    (contract_account, contract_code, initial_balance)
}

fn main() {
    let contract_account: AccountId = "contract.near".parse().unwrap();
    let wasm_code = include_bytes!("../res/hello_near.wasm").to_vec();
    let initial_balance = 10_000_000_000_000_000_000_000; // 10 NEAR
    
    let (account, code, balance) = deploy_contract(
        contract_account,
        wasm_code,
        initial_balance,
    );
    
    println!(
        "Deployed contract {} with {} yoctoNEAR and {} bytes WASM code",
        account,
        balance,
        code.code().len()
    );
}

许可证

该项目采用双重许可:

  • MIT许可证
  • Apache-2.0许可证

注意事项

  1. 在使用前请确保了解NEAR协议的基本概念
  2. 实际开发中应使用适当的错误处理
  3. 密钥管理应遵循安全最佳实践
  4. 交易nonce应正确管理以防止重放攻击

1 回复

Rust区块链开发库near-primitives-core的使用

完整示例Demo

以下是基于内容中提供的示例代码整合的完整demo,展示了near-primitives-core库的主要功能:

use near_primitives_core::{
    types::{AccountId, Balance},
    hash::{hash, CryptoHash},
    transaction::{Action, TransferAction},
    config::Gas,
    borsh::{BorshSerialize, BorshDeserialize},
};

// 序列化示例结构体
#[derive(BorshSerialize, BorshDeserialize, Debug)]
struct MyStruct {
    field1: u64,
    field2: String,
}

fn main() {
    // 1. 基础类型使用示例
    println!("=== 基础类型示例 ===");
    let account_id: AccountId = "example.near".parse().unwrap();
    println!("Account ID: {}", account_id);
    
    let balance: Balance = 100_000_000_000_000_000_000; // 100 NEAR (以yoctoNEAR为单位)
    println!("Balance: {}", balance);
    
    // 2. 加密和哈希示例
    println!("\n=== 加密哈希示例 ===");
    let data = b"hello NEAR";
    let hash: CryptoHash = hash(data);
    println!("SHA-256 hash: {}", hash);
    
    // 3. 交易构建示例
    println!("\n=== 交易构建示例 ===");
    let sender: AccountId = "sender.near".parse().unwrap();
    let receiver: AccountId = "receiver.near".parse().unwrap();
    let amount: Balance = 1_000_000_000_000_000_000; // 1 NEAR
    
    let transfer_action = Action::Transfer(TransferAction { deposit: amount });
    println!("Created transfer action: {:?}", transfer_action);
    
    // 4. 序列化示例
    println!("\n=== 序列化示例 ===");
    let my_data = MyStruct {
        field1: 42,
        field2: "NEAR".to_string(),
    };
    
    let encoded = my_data.try_to_vec().unwrap();
    println!("Serialized: {:?}", encoded);
    
    let decoded: MyStruct = MyStruct::try_from_slice(&encoded).unwrap();
    println!("Deserialized: {:?}", decoded);
    
    // 5. 智能合约交互示例
    println!("\n=== 智能合约示例 ===");
    let gas_usage: Gas = 10_000_000_000_000; // 10 TGas
    let contract_id: AccountId = "contract.near".parse().unwrap();
    println!("Interacting with contract: {}, Gas: {}", contract_id, gas_usage);
    
    // 6. 进阶交易构建示例
    println!("\n=== 进阶交易示例 ===");
    let signer_id: AccountId = "signer.near".parse().unwrap();
    let receiver_id: AccountId = "receiver.near".parse().unwrap();
    println!("Building transaction from {} to {}", signer_id, receiver_id);
}

代码说明

  1. 基础类型:展示了AccountId和Balance类型的使用,注意NEAR余额以yoctoNEAR为单位
  2. 加密哈希:使用SHA-256算法计算数据的哈希值
  3. 交易构建:创建了一个转账Action,这是构建完整交易的基础
  4. 序列化:演示了如何使用Borsh序列化格式进行数据编码/解码
  5. 智能合约:展示了与合约交互所需的基本元素:合约账户和Gas费用
  6. 进阶交易:演示了更复杂交易的基础构建模块

运行结果预期

运行上述代码将输出类似以下内容:

=== 基础类型示例 ===
Account ID: example.near
Balance: 100000000000000000000

=== 加密哈希示例 ===
SHA-256 hash: 2cf24dba5fb0a30...

=== 交易构建示例 ===
Created transfer action: Transfer(TransferAction { deposit: 1000000000000000000 })

=== 序列化示例 ===
Serialized: [42, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 78, 69, 65, 82]
Deserialized: MyStruct { field1: 42, field2: "NEAR" }

=== 智能合约示例 ===
Interacting with contract: contract.near, Gas: 10000000000000

=== 进阶交易示例 ===
Building transaction from signer.near to receiver.near

这个完整示例展示了near-primitives-core库的核心功能,适合作为开发NEAR区块链应用的起点。

回到顶部