WEB3J Tutorial: How Java and Android use WEB3J to develop ethereum smart contracts and trade them

Source: Internet
Author: User

Broadly speaking, there are web3j to support three types of Ethereum transactions:

    • 1. Ethereum transactions from one party to the other
    • 2. Create a smart contract
    • 3. Trading with Smart contracts

In order to carry out these transactions, it is necessary to have the etheric currency (the token of the Ethereum blockchain) in the Ethereum account where the transaction occurred. This is to pay the gas cost, which is to pay for the transaction execution cost of the Ethereum client participating in the transaction, and to pay this cost to submit the results to the Ethereum blockchain. The instructions for obtaining the etheric currency are described below.

In addition, we can also query the status of smart contracts.

How to get the ethereum ether

There are two ways you can choose to get the ether:

    • 1. Mine mining by myself
    • 2. Get the etheric coins from others

Digging yourself in a private chain, or a public test chain ( testnet ) is very straightforward. However, in the main public chain ( mainnet ), it requires a lot of obvious dedicated GPU time, unless you already have more than one dedicated GPU miner, which is largely impractical. If you want to use a private chain, there are some guidelines in this official document.

To purchase the ether, you need to go through the exchange. Because there are different exchanges in different regions, you need to study where you are going to fit. The official documentation contains multiple exchanges and is a good reference.

Ethereum test Chain (testnets)

There are many dedicated test networks or test chains for Ethereum Ethereum, which are supported by various clients.

    • 1.Rinkeby: Only Geth clients are supported.
    • 2.Kovan: Only parity clients are supported.
    • 3.Ropsten: Supports Geth and parity clients.

For development, it is recommended that you use Rinkeby or KoVan test the chain. This is because they use a proof-of-work POA consensus mechanism to ensure that transactions and blocks are created in a consistent and timely manner. The Ropsten test chain, although closest to the public chain ( Mainnet ), has POW been subjected to XXX and often has more problems for ethereum developers because the workload it uses proves to be a consensus mechanism.

You can go through Rinkeby the test chain of the Rinkeby Crypto Fauce request Ethereum, specifically how to do can see here https://www.rinkeby.io/.

Details on how to request Kovan a test chain can be found here.

If you need to Ropsten get some etheric coins on, post the message of your wallet address to the WEB3J gitter channel and then send some to you.

Mining on testnet test chain or private chain

In the Ethereum ether test chain testnet , digging is less difficult than the public chain mainnet . This means that you can use a regular CPU, such as your laptop, to tap into the new etheric currency. What you need to do is run an Ethereum client, for geth example Parity , or start doing some storage. Further information can be obtained on their official website.

    • Geth:https://github.com/ethereum/go-ethereum/wiki/mining
    • Parity:https://github.com/paritytech/parity/wiki/mining

Once you have mined some etheric coins, you can start using the Ethereum blockchain.

However, as mentioned above, it is simpler to use Kovan or Rinkeby test the network.

Gas

When a transaction occurs at Ethereum Ethereum, the transaction cost must be paid to the client executing the transaction, and the output of the transaction is submitted to the Ethereum blockchain Ethereum blockchain.

This cost is measured by gas, which is used to execute the number of trade orders in the Ethereum virtual machine. Please refer to the official documentation for more information.

When you use the Ethereum client, this means that there are two parameters that indicate how much ethernet you want to spend to complete the transfer:

    • Gas prices: The price of gases, which is the consumption of ether in each unit. The default price used by WEB3J is 22000000000 Wei (22x10-8 ether). This is defined in the transaction management.
    • Gas limit: The largest quantity of gases, which is the maximum amount you would like to spend on trading execution. The maximum limit for a single transaction in an Ethereum block, which is typically limited to less than 6700000. The current gas limit is here to check https://ethstats.net/.

Together, these two parameters determine the largest amount of ethereum ether you are willing to spend on transaction costs. In other words, you won't spend more gas than that gas price * gas limit . Gas prices also affect the speed at which transactions occur, depending on whether other deals can provide more favourable gas prices for miners.

You may need to adjust these parameters to ensure that the transaction is in time.

Trading mechanism

When you create a valid account with some etheric currency ether, you can use two mechanisms to trade with ethereum.

    • Authenticating and signing transactions via Ethereum Ethereum client
    • Offline Transaction Signature Authentication

Both of these mechanisms are supported by WEB3J.

Authenticating and signing transactions via Ethereum Ethereum client

In order to trade through the Ethereum client, you first need to make sure that the client you are using knows your wallet address. It is best to run your own Ethereum client, such as geth / Parity , so that you can do it more conveniently. Once you have a client running, you can create an Ethereum wallet by:

    • The Geth wiki contains different mechanisms that Geth supports to run well, such as importing a private key file and creating a new Ethereum account from the console.
    • Alternatively, you can use JSON-RPC to manage commands via the client, for example, personal_newAccount to geth Parity create a new Ethereum account.

By creating your wallet file, you can open the account via WEB3J and first create geth Parity a web3j instance of the Support/management command:

Admin web3j = Admin.build(new HttpService());

Then, you can unlock the account and, if it is successful, you can send a transaction:

PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount("0x000...", "a password").send();if (personalUnlockAccount.accountUnlocked()) {    // send a transaction}

Transactions sent in this manner should be created through ethsendtransaction, using the transaction type:

Transaction transaction = Transaction.createContractTransaction(              <from address>,              <nonce>,              BigInteger.valueOf(<gas price>),  // we use default gas limit              "0x...<smart contract code to execute>"      );      org.web3j.protocol.core.methods.response.EthSendTransaction              transactionResponse = parity.ethSendTransaction(ethSendTransaction)              .send();      String transactionHash = transactionResponse.getTransactionHash();      // poll for transaction response via org.web3j.protocol.Web3j.ethGetTransactionReceipt(<txHash>)

Where nonce the value is obtained, the following is mentioned.
For more information about this trading workflow, see Deploycontractit and scenario.

Further details of the various management commands supported by WEB3J are in the management APIs.

Offline transaction signature authentication offline transaction signing

If you do not want to manage your own Ethereum client, or if you do not want to provide the Ethereum client with details such as a password, then you can authenticate the signature by offline trading.

Offline Trading Signature authentication allows you to sign transactions using your Ethereum wallet in web3j, allowing you to fully control your private credentials. Then, a transaction created offline can be sent to any Ethereum client on the network, so long as it is a valid transaction, it propagates the transaction to the other nodes.

If required, you can also perform out-of-process transaction signing authentication. This can be achieved by overriding the Eckeypair sign method.

Create and use wallet files Ethereum wallet file

In order to offline offline trading, you need to have your wallet file or the public and private keys associated with your private wallet/account.

WEB3J can generate a new secure Ethereum wallet file for you ethereum wallet file, or you can also work with the existing wallet file by using the private key.

Create a new Wallet file:

String fileName = WalletUtils.generateNewWalletFile(        "your password",        new File("/path/to/destination"));

Load credentials from the wallet file:

Credentials credentials = WalletUtils.loadCredentials(        "your password",        "/path/to/walletfile");

These credentials will then be used to sign the transaction, see WEB3 Secure Store Definition Wallet file specification Web3 Secret Storage definition

Sign Ethereum deal

To make an offline signed transaction sign, you need to set a rawtransaction type. RawTransactionsimilar to the previously mentioned Transaction type, but it does not need to be requested by a specific account address, because it can be inferred from the signature.

In order to create and sign native transactions, the order of transactions is as follows:

    • 1. Determine the next available random number for the transaction initiator accountnonce
    • 2. Create an RawTransaction object
    • 3. Encode an object using recursive length prefix encoding (RLP is recursive length Prefix) RawTransaction
    • 4. Signature of the RawTransaction object
    • 5. RawTransaction sending an object to a node for processing

nonceis an increasing number used to uniquely identify a transaction. One can nonce only be used once, until the transaction is mined, and multiple versions of the transaction may be sent with the same random number, but once one is excavated, the other subsequent commits will be rejected.

Once you get the next available nonce , the value can be used to create the transaction object:

RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(             nonce, <gas price>, <gas limit>, <toAddress>, <value>);

The transaction can then be signed and encoded:

byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, <credentials>);String hexValue = Numeric.toHexString(signedMessage);

Where the credentials are loaded based on the creation and use of the wallet file.

Then use Eth_sendrawtransaction to send the transaction:

EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();String transactionHash = ethSendTransaction.getTransactionHash();// poll for transaction response via org.web3j.protocol.Web3j.ethGetTransactionReceipt(<txHash>)

For a complete example of creating and sending the original transaction, see Createrawtransactionit.

Transaction random number Nonce

nonceis an increasing number used to uniquely identify a transaction. One can nonce only be used once, until the transaction is mined, and multiple versions of the transaction may be sent with the same random number, but once one is excavated, the other subsequent commits will be rejected.

eth_getTransactionCountthe next available method can be obtained by means of nonce :

EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(             address, DefaultBlockParameterName.LATEST).sendAsync().get();     BigInteger nonce = ethGetTransactionCount.getTransactionCount();

You can then use nonce the Create your trading object:

RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(             nonce, <gas price>, <gas limit>, <toAddress>, <value>);
Type of transaction

The different types of transactions in WEB3J are used Transaction and RawTransaction objects. The key difference is that the transaction object must always have an address so that eth_sendTransaction the Ethereum client processing the request knows which wallet to use to represent the sender of the message and send the transaction. As mentioned above, this is not necessary for the original transaction signed by the offline signature authentication.

The next section outlines the key trading attributes required for different transaction types. The following properties are the same for everyone:

    • Gas prices
    • Gas limitation gas limit
    • Nonce Random Number
    • From send address

Transactionand RawTransaction objects can be used interchangeably in all subsequent examples.

The etheric currency is traded from one party to the other

The minimum amount of information that is required to trade objects between the two parties is the ether of the etheric currency:

    • To: Destination wallet Address
    • Value: The number of etheric coins that you want to send to your destination
BigInteger value = Convert.toWei("1.0", Convert.Unit.ETHER).toBigInteger();RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(             <nonce>, <gas price>, <gas limit>, <toAddress>, value);// send...

However, it is recommended that you use Transferclass to send the ether, which is responsible for nonce managing and providing responses to you through ongoing polling:

Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");TransactionReceipt transactionReceipt = Transfer.sendFunds(        web3, credentials, "0x<address>|<ensName>",        BigDecimal.valueOf(1.0), Convert.Unit.ETHER).send();
Use Smart Contract Packager smart contract wrappers

When using the Smart Contract packager listed below, you will have to manually perform all conversions from solidity to native Java types. Using the solidity Smart contract wrappers is very effective and it is responsible for all code generation and conversion.

Create a smart contract

To deploy a new smart contract, you need to provide the following properties:

    • Value: The amount of ethereum ether you wish to store in the smart contract (default is 0 if not provided)
    • Data: Hexadecimal formatted, compiled smart contract creation code
// using a raw transactionRawTransaction rawTransaction = RawTransaction.createContractTransaction(        <nonce>,        <gasPrice>,        <gasLimit>,        <value>,        "0x <compiled smart contract code>");// send...// get contract addressEthGetTransactionReceipt transactionReceipt =             web3j.ethGetTransactionReceipt(transactionHash).send();if (transactionReceipt.getTransactionReceipt.isPresent()) {    String contractAddress = transactionReceipt.get().getContractAddress();} else {    // try again}

If the smart contract contains a constructor, you must encode the associated constructor Number field value and attach it to the compiled smart contract code compiled smart contract code :

String encodedConstructor =             FunctionEncoder.encodeConstructor(Arrays.asList(new Type(value), ...));// using a regular transactionTransaction transaction = Transaction.createContractTransaction(        <fromAddress>,        <nonce>,        <gasPrice>,        <gasLimit>,        <value>,        "0x <compiled smart contract code>" + encodedConstructor);// send...
Trading with smart contracts

To trade with an existing smart contract, you need to provide the following properties:

    • To: Smart contract address
    • Value: The amount of ether that you wish to store in the smart contract (if the smart contract accepts the ether of the etheric currency)
    • Data: Encoded function selector and argument arguments

WEB3J is responsible for function encoding, see the Application Binary Interface section application binary Interface for further details on implementation.

Function function = new Function<>(             "functionName",  // function we‘re calling             Arrays.asList(new Type(value), ...),  // Parameters to pass as Solidity Types             Arrays.asList(new TypeReference<Type>() {}, ...));String encodedFunction = FunctionEncoder.encode(function)Transaction transaction = Transaction.createFunctionCallTransaction(             <from>, <gasPrice>, <gasLimit>, contractAddress, <funds>, encodedFunction);org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse =             web3j.ethSendTransaction(transaction).sendAsync().get();String transactionHash = transactionResponse.getTransactionHash();// wait for response using EthGetTransactionReceipt...

It is not possible to return a value from a transactional function call, regardless of the return type of the message signature. However, it is possible to use the filter to capture the value returned by the function. For details, see the Filters and Events section.

Query Smart Contract Status

This functionality is implemented by Eth_call by JSON-RPC calling.

Eth_call allows you to invoke a method on a smart contract to query a value. This function has no transaction cost associated with it because it does not change the state of any smart contract method, it returns only their values:

Function function = new Function<>(             "functionName",             Arrays.asList(new Type(value)),  // Solidity Types in smart contract functions             Arrays.asList(new TypeReference<Type>() {}, ...));String encodedFunction = FunctionEncoder.encode(function)org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(             Transaction.createEthCallTransaction(<from>, contractAddress, encodedFunction),             DefaultBlockParameterName.LATEST)             .sendAsync().get();List<Type> someTypes = FunctionReturnDecoder.decode(             response.getValue(), function.getOutputParameters());

Note : If an invalid function call is executed, or if you get a null NULL to return the result, the return value will be an collections.emptylist instance.

  • Share a web3j tutorial that focuses on the web3j development of blockchain Ethereum for Java and Android programmers.

Original visit here

WEB3J Tutorial: How Java and Android use WEB3J to develop ethereum smart contracts and trade them

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.