Go-Ethereum

如何使用 web3j 使用私鑰和地址進行交易

  • October 22, 2020

我有一個私鑰和地址。是否可以使用 web3j 與這些參數進行交易。

如果您想以合約所有者的身份發送自定義代幣,請在此處查看我的答案:將自定義 ERC20 代幣從一個地址發送到另一個地址

如果你想代表另一個使用者發送令牌,這個想法是相似的。

首先從 privatekey 中檢索使用者的憑據,然後進行交易。

Credentials getUserInfo (String privateKeyInHex){

   BigInteger privateKeyInBT = new BigInteger(privateKeyInHex, 16);

   ECKeyPair aPair = ECKeyPair.create(privateKeyInBT);
   Credentials aCredential = Credentials.create(aPair);

   return aCredential;
}

發送令牌:

process(){
   ... 

   Credentials newUser =  getUserInfo(privateKeyInHex);

   TransactionReceiptProcessor transactionReceiptProcessor = new NoOpProcessor(web3);
   TransactionManager transactionManager = new RawTransactionManager(
                           web3, newUser, ChainId.MAINNET, transactionReceiptProcessor);
                   //if testing, use ChainId.ROPSTEN
   ...
Web3j web3j = Web3j.build(new HttpService(""));
   Credentials credentials = Credentials.create("privateKey");
   BigInteger nonce = web3j.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).sendAsync().get().getTransactionCount();
   BigInteger gasPrice = web3j.ethGasPrice().sendAsync().get().getGasPrice();
   RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, Constants.ETH_GAS_LIMIT, "address", Convert.toWei("amount", Convert.Unit.ETHER).toBigIntegerExact());
   EthSendTransaction response = web3j.ethSendRawTransaction(Numeric.toHexString(TransactionEncoder.signMessage(rawTransaction, credentials))).send();
   String hash = response.getTransactionHash();

引用自:https://ethereum.stackexchange.com/questions/41194