我正在使用web3j庫來生成一個用于我的solidity以太坊智能合約的Java封裝包,我已經将該智能合約部署到區塊鍊中,并且它已經被挖掘,現在我想使用Java封裝包在Java中加載該以太坊智能合約。
java封裝包是
SimpleStorage
,web3j已經生成了用于加載以太坊智能合約的以下方法簽名: public static SimpleStorage load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
return new SimpleStorage(contractAddress, web3j, credentials, gasPrice, gasLimit);
}
public static SimpleStorage load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
return new SimpleStorage(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}
如何提供
Credentials
對象?我有一個公鑰、私鑰和位址,它是我在區塊鍊上部署的,但是
Credentials
對象需要一個
ECKeyPair
,它希望私鑰和公鑰是一個
BigInteger
,但是我的密鑰隻是字元串形式的。
加載參數可以傳遞給這個方法:
public static Credentials create(String privateKey, String publicKey) {
return create(new ECKeyPair(Numeric.toBigInt(privateKey), Numeric.toBigInt(publicKey)));
}
如果我的公鑰和私鑰不能轉換成
BigInt
,那麼這将失敗。
問題的解決
若要生成憑據,如果你有普通的公鑰和私鑰,則需要将它們轉換為十六進制的表示形式,然後将它們傳遞給構造函數用于
Credentials
。
String hexPrivateKey = String.format("%040x", new BigInteger(1, privateKey.getBytes()));
String hexPublicKey = String.format("%040x", new BigInteger(1, publicKey.getBytes()));
Credentials creds = Credentials.create(hexPrivateKey, hexPublicKey);
其中
privateKey
和
privateKey
是包含你的私鑰和公鑰的字元串。
原文《以太坊常見問題和錯誤》中的:
http://cw.hubwiz.com/card/c/ethereum-FAQ/1/1/13/另外推薦幾個很受歡迎全網稀缺的互動教程: