跳到主要内容

构建与发送交易

TransactionBuilder 提供了一套流式 API,用于构建、签名并向 Savitri Network 提交交易。

简单转账

use savitri_sdk::{Wallet, TransactionBuilder, RpcClient};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
let client = RpcClient::from_url("http://localhost:8545")?;
let wallet = Wallet::from_private_key_hex("your_private_key_hex")?;

// 获取当前 nonce
let nonce = client.get_nonce(wallet.address()).await?;

// 构建并签名
let signed_tx = TransactionBuilder::new()
.to("recipient_address_64hex")
.value(1_000_000_000_000_000_000) // 1 SAVT (18 decimals)
.nonce(nonce)
.fee(1_000_000_000_000_000) // 0.001 SAVT fee
.build_and_sign(&wallet)?;

// 提交
let result = client.send_raw_transaction(&serialize_tx(&signed_tx)).await?;
println!("TX hash: {}", result.tx_hash);

Ok(())
}

构建器 API

必填字段

方法类型描述
.from(address)String发送方地址(省略时自动从钱包填充)
.to(address)String接收方地址
.value(amount)u128最小单位转账金额

可选字段

方法类型默认值描述
.nonce(n)u640交易 nonce(通过 get_nonce() 获取)
.fee(f)u128交易手续费
.data(bytes)Vec<u8>合约调用的载荷数据

仅构建(不签名)

let unsigned = TransactionBuilder::new()
.from("sender_address")
.to("recipient_address")
.value(1000)
.nonce(5)
.build()?;

// unsigned.from, unsigned.to, unsigned.value, unsigned.nonce, unsigned.fee, unsigned.data

构建并签名

let signed = TransactionBuilder::new()
.to("recipient_address")
.value(1000)
.nonce(5)
.fee(100)
.build_and_sign(&wallet)?;

// signed.transaction -- the UnsignedTransaction
// signed.public_key -- 32-byte ed25519 public key
// signed.signature -- 64-byte ed25519 signature

如果未调用 .from(),则自动使用钱包的地址。

预言机调用

let signed = TransactionBuilder::new()
.oracle_call(
"oracle_contract_address",
"request_data",
b"temperature_sensor_01",
)
.value(0)
.nonce(nonce)
.build_and_sign(&wallet)?;

治理调用

对提案投票

use savitri_sdk::GovernanceAction;

let signed = TransactionBuilder::new()
.governance_call(
"governance_contract_address",
proposal_id, // u64
GovernanceAction::Vote(true), // true = support, false = oppose
)
.nonce(nonce)
.build_and_sign(&wallet)?;

执行已批准的提案

let signed = TransactionBuilder::new()
.governance_call(
"governance_contract_address",
proposal_id,
GovernanceAction::Execute,
)
.nonce(nonce)
.build_and_sign(&wallet)?;

创建联邦学习提案

let signed = TransactionBuilder::new()
.create_fl_proposal(
"governance_contract_address",
"Upgrade model v2", // title
"Replace BERT with GPT-4", // description
604800, // voting period in seconds (7 days)
)
.nonce(nonce)
.build_and_sign(&wallet)?;

交易签名格式

签名消息的构建方式如下:

from_hex_bytes || to_hex_bytes || amount_le_u64 || nonce_le_u64 || fee_le_u128

然后进行 SHA-256 哈希,再用 Ed25519 对哈希值进行签名。

此格式与 savitri-rpc 中的服务端验证逻辑匹配。

金额与精度

所有金额使用 18 位精度:

用户可读金额原始值
1 SAVT1_000_000_000_000_000_000
0.1 SAVT100_000_000_000_000_000
0.001 SAVT1_000_000_000_000_000
0.00001 SAVT10_000_000_000_000

手续费参考

交易类型手续费(SAVT)原始值
普通转账0.0011_000_000_000_000_000
合约调用0.0055_000_000_000_000_000
IoT 数据0.0000550_000_000_000_000