rust 如何从ethers库的U256结构体打印十六进制字符串?

bhmjp9jg  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(231)

我正在使用Rust和crate ethers通过从EVM链阅读日志,我正在处理事务散列和地址,它们被表示为U256H160对象,请考虑下面的示例代码:

use ethers::prelude::{Log};
use ethers::types::{Address, H160, H256, U256};

async fn print_log_details(&self, log: &Log) {
    let block_number = log.block_number.unwrap();
    let from: H160 = Address::from(log.topics[1]);
    let to: H160 = Address::from(log.topics[2]);
    let token_id: U256 = U256::decode(log.topics[3]).unwrap();
    let transaction_hash: H256 = log.transaction_hash.unwrap();

    dbg!(log.clone());
    println!(
        "block_number = {}, from = {}, to = {}, tokenId = {}, transactionHash = {}",
        block_number, from, to, token_id, transaction_hash
    );
}

产生如下输出:

[src/main.rs:54] log.clone() = Log {
address: 0x7ea3cca10668b8346aec0bf1844a49e995527c8b,
topics: [
    0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef,
    0x000000000000000000000000603503a11a37acb6e9d8ff2423c29d135255df49,
    0x0000000000000000000000004a6ead6446265533b6b5257bbfb450e1cdfae5ec,
    0x0000000000000000000000000000000000000000000000000000000000000bf5,
],
data: Bytes(0x),
block_hash: Some(
    0xd6da518349a24d4414163bd4b51678c7b8629bd8e0fa9b59e57fcbe2a8e93a98,
),
block_number: Some(
    13032069,
),
transaction_hash: Some(
    0xa520f3d255140abeb8cec33764a3a1c0ccbcf9496a934e25f1bbf004667cbddf,
),
transaction_index: Some(
    383,
),
log_index: Some(
    321,
),
transaction_log_index: None,
log_type: None,
removed: Some(
    false,
),
}

block_number = 13032069, from = 0x6035…df49, to = 0x4a6e…e5ec, tokenId = 3061, transactionHash = 0xa520…bddf

我想在println中看到完整的十六进制形式的fromtotransaction,而不是截断的形式。我该怎么做呢?看起来这些结构体上的Display特性截断了输出。

58wvjzkj

58wvjzkj1#

U256H160类型都支持UpperHexLowerHex。在此处阅读有关Rust格式设置的更多信息:https://doc.rust-lang.org/std/fmt/index.html#formatting-parameters。您可以在格式化字符串中使用Xx(加上填充和0x作为前缀),以实现开箱即用的完整类型打印:

/*
[dependencies]
ethers = "*"
*/
use ethers::types::{U256, H160};

fn main() {
    let u256 = U256::MAX;
    let h160 = H160::repeat_byte(0x0F);

    println!("{u256:#032X}");
    println!("{u256:#032x}");

    println!("{h160:#020X}");
    println!("{h160:#020x}");
}

标准输出:

0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F
0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f

拉斯探险家。

相关问题