Contract-Invocation
如何為合約互動 Web3j 創建 RawTransaction
我想簽署一個呼叫智能合約功能的交易並將其發送到 Rinkeby 網路。
我在 Web3j 文件中找到了支持合約創建和乙太坊交換方法的RawTransaction類,但是我無法發送從智能合約呼叫函式的原始交易。
我怎樣才能做到這一點?有沒有辦法使用Transaction類中的createFunctionCallTransaction並用我的憑據對其進行簽名?
讓我們以下面的簡單儲存合約為例:
pragma solidity ^0.5.6; contract SimpleStorage { uint storedData; function set(uint x) public { storedData = x; } function get() public view returns (uint) { return storedData; } }
您可以使用以下程式碼將交易發送到(已部署的)智能合約:
// Connect to the node System.out.println("Connecting to Ethereum ..."); Web3j web3j = Web3j.build(new HttpService("http://localhost:8545")); System.out.println("Successfuly connected to Ethereum"); // Load an account String pk = "0xabcdef...1234567890"; Credentials credentials = Credentials.create(pk); // Contract and functions String contractAddress = "0x12d8e4546CD10e282083344CD4CA2C55FC3dAbeC"; Function function = new Function("set", // Function name Arrays.asList(new Uint(BigInteger.valueOf(20))), // Function input parameters Collections.emptyList()); // Function returned parameters //Encode function values in transaction data format String txData = FunctionEncoder.encode(function); // RawTransactionManager use a wallet (credential) to create and sign transaction TransactionManager txManager = new RawTransactionManager(web3j, credentials); // Send transaction String txHash = txManager.sendTransaction( DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT, contractAddress, txData, BigInteger.ZERO).getTransactionHash(); // Wait for transaction to be mined TransactionReceiptProcessor receiptProcessor = new PollingTransactionReceiptProcessor( web3j, TransactionManager.DEFAULT_POLLING_FREQUENCY, TransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH); TransactionReceipt txReceipt = receiptProcessor.waitForTransactionReceipt(txHash);
程式碼也可以在 github 上找到
使用 Java 智能合約包裝器還有其他更方便的解決方案(請參閱此處)