java - 从 Java 应用程序交互智能合约

标签 java ethereum smartcontracts web3-java

我正在努力从 java 应用程序交互我的智能合约,我正在使用 testrpc。

要与智能合约交互,我们需要:1-连接到本地主机 2-拥有一个发送交易的帐户(凭证)。 3-部署合约并获取地址(使用truffle部署到testrpc网络并已拥有地址)

1- Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/
2- Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");

3- YourSmartContract contract = YourSmartContract.deploy(
    <web3j>, <credentials>,
    GAS_PRICE, GAS_LIMIT,
    <initialEtherValue>,
    <param1>, ..., <paramN>).get();  // constructor params

我的问题是:如何使用 testrpc 帐户作为“凭据”?!!

如何使用 truffle 已部署的智能合约的地址?

最佳答案

how I can use testrpc accounts for "credentials"??!!

您需要私钥和公钥来创建 Credentials目的。 TestRPC 在启动时显示私钥。它们在每次重新启动时都会发生变化,因此如果您想让它们保持静态,您可以使用您自己的私钥和 --accounts 指定初始帐户集。选项。

格式:testrpc --account "<PRIVATE_KEY>,<STARTING_BALANCE_IN_WEI>"

示例:

testrpc --account "0x70f1384b24df3d2cdaca7974552ec28f055812ca5e4da7a0ccd0ac0f8a4a9b00,300000000000000000000" --account "0xad0352cfc09aa0128db4e135fcea276523c400163dcc762a11ecba29d5f0a34a,300000000000000000000"

有了私钥,就可以生成公钥。有几个 有关如何执行此操作的在线示例。请参阅here对于 JS 示例或 here例如使用 web3j(这会创建一个新的 key 对,但您应该能够重用它)。

使用公钥和私钥,您现在可以创建 Credentials 对象:

import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.utils.Numeric;

...

String privateKey = <YOUR_PRIVATE_KEY>;
String publicKey = <YOUR_PUBLIC_KEY>;

ECKeyPair keyPair = new ECKeyPair(Numeric.toBigInt(privateKey), Numeric.toBigInt(publicKey));

Credentials credentials = Credentials.create(keyPair);

How I can use the address of the smart contract which already deployed by truffle??

你不deploy一份契约(Contract),你load契约(Contract)。来自 web3j docs :

YourSmartContract contract = YourSmartContract.load(
        "0x<address>|<ensName>", <web3j>, <credentials>, GAS_PRICE, GAS_LIMIT);

关于java - 从 Java 应用程序交互智能合约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791713/

相关文章:

java - 为什么在第二种情况下不允许字符串连接?

java - 如何抛出 IOException?

java - hive XML 解析错误

java - XMLGregorianCalendar 编码时未以正确的格式显示

go - geth account new - 命令行密码

smartcontracts - 契约(Contract)前任 vs 签署人 vs 当前

blockchain - 从 web3js 中的 Solidity 函数访问多个返回值(a、b、c)

ethereum - Solidity 是否支持 float

ethereum - 如何判断接收方是否为流动性池?

javascript - 如何使用智能合约获得正确的余额?