【问题标题】:How do I use the functionality of a Rust crate that has CLAP without using the command line?如何在不使用命令行的情况下使用具有 CLAP 的 Rust crate 的功能?
【发布时间】:2021-05-24 12:15:51
【问题描述】:

这里是新手,如果这是一个愚蠢的问题,请道歉。

我想在我的代码中使用wagyu crate 的功能。这个 crate 具有命令行功能,所以我可以从命令行运行代码,但我似乎无法从我自己的代码中引用它。

我尝试了 2 个选项:

  1. 在调用 crate(带参数的结构)时复制预期的输入“clap”
  2. 从 crate 中调用特定函数

对于第 2 项我已经尝试过:

use wagyu::cli::ethereum;

fn main() {

    let m: String = String::from("sunny story shrimp absent valid today film floor month measure fatigue pet");
    
    // Returns the address of the corresponding mnemonic.
    let passphrase = "";
    let pathway = "m/44'/60'/0'/0";
    let address = ethereum::from_mnemonic(m, passphrase, pathway);
        
    println!("phrase: {:?}", address);

当我尝试构建此代码时,出现以下编译错误:

error[E0425]: cannot find function `from_mnemonic` in module `ethereum`
  --> src\main.rs:37:29
   |
37 |     let address = ethereum::from_mnemonic::<>(s, passphrase, pathway);
   |                             ^^^^^^^^^^^^^ not found in `ethereum`

但我通过检查 ethereum.rs 文件中的代码知道有一个名为“from_mnemonic”的公共函数(在第 88 行定义)。

有人知道为什么我不能调用这个函数吗?或者,有没有一种简单的方法可以在不使用命令行界面的情况下使用具有 clap 依赖项的 crate?

非常感谢。

【问题讨论】:

  • 该函数在impl EthereumWallet 中,因此您首先需要创建该结构的一个实例,但您不能这样做,因为该结构是私有的。
  • 我想知道将私有类型的关联函数声明为公共是否有任何区别。我目前想不出。
  • 谢谢斯文,这正是我所担心的。那么有没有办法模仿命令行界面的输入呢?例如,从命令行运行 crate:cargo run ethereum import-hd "sunny story shrimp absent valid today film floor month measure fatigue pet" 将返回正确的输出。是否可以用我自己的代码参数来模仿 clap 的输入结构?
  • 我能想到的最简单的解决方案是简单地构建二进制文件并将其称为子进程。
  • 参见std::process:Command 示例。

标签: function import rust crate clap


【解决方案1】:

from_mnemonic 函数应该这样调用:

use wagyu::cli::ethereum::EthereumWallet;
use wagyu_ethereum::network::Mainnet; 
use wagyu_ethereum::wordlist::English;

fn main() {
    let mnemonic: String = String::from(
        "sunny story shrimp absent valid today. film floor month measure fatigue pet"
    );
    let passphrase = "";
    let path = "m/44'/60'/0'/0";

    let wallet = EthereumWallet::from_mnemonic::<Mainnet, English>(
        mnemonic,
        Some(passphrase),
        path
    ).unwrap()
}

但是wagyu::cli::ethereum::EthereumWallet 不是 pub,所以你不能简单地这样做。您必须从 github 下载 wagyu 的源并对其进行编辑,以便 wagyu::cli::ethereum::EthereumWallet 将被公开。

我认为你必须做的唯一改变就是替换这个(在ethereum.rs):

struct EthereumWallet {

有了这个:

pub struct EthereumWallet {

【讨论】:

  • 非常感谢 Hadus 花时间提供您的扩展答案。我实际上已经开始放弃使用Wagyu crate 功能,因为我不确定它是否给了我正确的地址。当我在 Ian Coleman 的精彩 website 上使用相同的助记符时,我得到了一个不同的地址(以及可以通过 MetaMask 验证的正确地址)。我将发布一个与使用 keccak-256 函数相关的单独问题,我正在努力解决这个问题。再次感谢。
  • 新查询使用keccak-256算法here
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 2015-04-06
  • 2013-09-30
相关资源
最近更新 更多