【问题标题】:Web3j - How to read the contract without credentials?Web3j - 如何在没有凭据的情况下阅读合同?
【发布时间】:2021-10-20 19:17:35
【问题描述】:

我正在使用 Web3j 与我部署的智能合约进行交互。

我已将我的合约部署到测试网上并可以与之交互,但是使用生成的包装器代码,它需要我的钱包。

Web3j web3 = Web3j.build(new HttpService("https://testnet-endpoint-rpc.com"));
            Credentials credentials = WalletUtils.loadCredentials(
                    "coolpassword1", "src\\main\\resources\\path-to-key-store.keystore"
            );

            FastRawTransactionManager txMananger = new FastRawTransactionManager(web3, credentials, 365);
            MySmartContract contract = MySmartContract.load(
                    "0x73292b80f99ffdc4e9a908865ce1d35fde7b736f", //Address for smartcontract
                    web3,
                    txMananger,
                    new DefaultGasProvider()
            );

//Reading from the contract
String contractName = contract.contractName(BigInteger.valueOf(0)).send();

如果没有credentials,我如何阅读合同?

【问题讨论】:

  • 似乎web3j 对(读写)事务和(只读)调用都使用send() 方法 - docs - 并且它决定了哪个 RPC 方法 (@987654328 @ 或 eth_call) 根据合约 ABI 使用。如果是这种情况,您应该能够对带有修饰符 viewpure 的 Solidity 函数执行只读调用,而不需要任何凭据(不应修改合约状态 - docs)。
  • @PetrHejda 是否可以使用钱包的助记词签署交易? stackoverflow.com/q/69832708/11110509
  • 我不知道 Java web3 实现的细节,我的专长是 JS 实现。但通常,您可以从一个助记词生成多个私钥(例如使用 BIP39 标准)。所以首先你需要得到想要的私钥,然后用私钥对交易进行签名。但也许 web3j 使用 Credentials 类在后台执行此操作,我不确定。

标签: java ethereum web3js web3-java


【解决方案1】:

我相信您可以使用encodedFunctions 无需凭据即可读取,但要写入则需要凭据。

例如:余额是合约中的一种方法,只需输入一个地址

Function function = 
  new Function("balances",
               Arrays.asList(new org.web3j.abi.datatypes.Address(walletAddress)),  
               new ArrayList());

String encodedFunction = FunctionEncoder.encode(function);
            org.web3j.protocol.core.methods.response.EthCall response = this.web3.ethCall(
                Transaction.createEthCallTransaction(walletAddress, ContractAddress, encodedFunction),
            DefaultBlockParameterName.LATEST)
        .sendAsync().get();

【讨论】:

    猜你喜欢
    • 2017-10-14
    • 2020-03-22
    • 2022-10-21
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2021-03-01
    • 2021-08-13
    相关资源
    最近更新 更多