Web3j新账户与testrpc交易

Web3j新账户与testrpc交易

问题描述:

我是区块链开发新手。目前,我正在学习以太坊平台,这听起来是一个非常好的环境。我测试了我的Android应用程序的web3j库,它工作正常。我用下面的代码连接到我的testrpc节点:Web3j新账户与testrpc交易

Web3j web3 = Web3jFactory.build(new HttpService("http://192.168.1.108:8545")); 
BigInteger gasPrice = BigInteger.valueOf(20000000000L); 
    BigInteger gasLimit = BigInteger.valueOf(500000L); 
    BigInteger nonce = null; 


    String contractAddress="0x0dd3b0efbce5c4eba2dc9b8500ecafb0b1cec28f"; 

    String from = "0x2d6fcee3c3435ebda9184bdddf8481a87b7d1948"; 
    List<Type> inputParameters = new ArrayList<>(); 
    String hash ="232131231232141231231231231232123123123"; 
    byte[] b =Arrays.copyOfRange(new BigInteger(hash, 16).toByteArray(), 1, 33); 

    Type _telNumber = new Bytes32(b); 
    Type _publicKey = new Bytes32(b); 
    inputParameters.add(_telNumber); 
    inputParameters.add(_publicKey); 
    Function function = new Function("addPerson", 
      inputParameters, 
      Collections.<TypeReference<?>>emptyList()); 
    String functionEncoder = FunctionEncoder.encode(function); 



    Transaction transaction = Transaction.createFunctionCallTransaction(from, nonce,gasPrice,gasLimit,contractAddress,new BigInteger("0"), functionEncoder); 

    try { 
     EthSendTransaction transactionResponse = web3.ethSendTransaction(transaction).sendAsync().get(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 

上面的代码工作,我能够与智能合同(调用一个函数)进行交互。

的主要问题是,参数是硬编码(我从帐户testrpc名单得到了它)。

我想实现的目标:我想创建一个应用程序,用户可以在其中创建新的钱包(帐户),并使用它们与网络进行交易。我创建了钱包成功地使用下面的代码:

String filePath = Environment.getExternalStorageDirectory().toString() + "/Pictures"; 


    Web3j web3 = Web3jFactory.build(new HttpService("http://192.168.1.108:8545")); 
    Web3ClientVersion web3ClientVersion = null; 

    try { 
     String fileName = WalletUtils.generateNewWalletFile("your password",new File(filePath),false); 
     Log.d("FILENAME",fileName); 

     Credentials credentials = WalletUtils.loadCredentials(
       "your password", 
       filePath+"/"+fileName); 

     myAddress = credentials.getAddress(); 
     Log.d("My address",credentials.getAddress()); 

    } catch (CipherException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (InvalidAlgorithmParameterException e) { 
     e.printStackTrace(); 
    } catch (NoSuchAlgorithmException e) { 
     e.printStackTrace(); 
    } catch (NoSuchProviderException e) { 
     e.printStackTrace(); 
    } 

什么是下一个步骤?我应该向网络广播我的地址吗?

主要问题是from参数是硬编码的(我从testrpc帐户列表中获得)。

您可以调用您的文件并解密以获取您的地址,每当您创建一个新帐户时使用您的密钥生成一个文件。

val credentialsOne = WalletUtils.loadCredentials("your password", "your path") 

当你与你的节点连接,它会自动检测地址