Java SDK Getting Started

更新时间:
复制 MD 格式

This guide walks you through connecting to the Blockchain as a Service (BaaS) platform and running a sample Java application that creates accounts, deploys a smart contract, issues credits, transfers credits between accounts, and queries account balances.

The sample application simulates a credit system. It uses the BaaS Java SDK to:

  1. Create two blockchain accounts (testAccount1 and testAccount2)

  2. Deploy an EVM smart contract

  3. Issue 100 credits to testAccount2

  4. Transfer 50 credits from testAccount2 to testAccount1

  5. Query testAccount2's balance and verify it equals 50

The application connects to a BaaS node over SSL using four certificate files. You compile and run it locally using Maven and IntelliJ IDEA.

Prerequisites

Before you begin, ensure that you have:

  • A BaaS node deployed on the BaaS platform

  • The node's IP address and port number (available on the node details page)

  • IntelliJ IDEA installed

  • Maven installed

  • Java Development Kit (JDK) installed

Step 1: Prepare your environment

Get the SSL certificate files

To establish an SSL connection to the BaaS platform, generate and download the following four certificate files:

FileDescriptionHow to get it
client.crtClient certificateUse the key generation tool to generate a certificate request file (client.csr), submit it to the BaaS platform, and download the .crt file after approval.
client.keyClient private keyUse the key generation tool to generate the file.
trustCaTrustStore containing the CA certificateDownload from the BaaS platform. The password is mychain.
user.keyAccount private keyUse the key generation tool to generate the file.

Get the node IP address and port number

On the BaaS platform, open the node details page and note the node's IP address and port number. The application uses these to connect to the blockchain.

Step 2: Set up the project

  1. In IntelliJ IDEA, create a Maven-based demo project. After the project is created, the directory structure looks like this:

    1545295559042-521770ec-412b-49ed-935e-a6b644bb0949.png

  2. In the java directory, create a package named com.example.demo. Copy the contents of DemoSample.java into this package, and place the four certificate files (client.crt, client.key, trustCa, and user.key) in the resources directory. Download DemoSample.java.

    The demo project requires the EVM bytecode compiled from your Solidity contract source code. For details on writing Solidity contracts, see Solidity contract development. For the compilation tool, see Solidity contract compilation tool.

    1

  3. Add the BaaS SDK and logging dependencies to pom.xml. Always use the latest SDK version.

    <dependencies>
        <dependency>
            <groupId>com.alipay.mychainx</groupId>
            <artifactId>mychainx-sdk</artifactId>
                <!-- Use the latest SDK version -->
            <version>0.10.2.6</version>
        </dependency>
    
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.8.0-alpha0</version>
        </dependency>
    </dependencies>
    
    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.1</version>
            </extension>
        </extensions>
    </build>
  4. Add log4j.properties to the resources directory with the following content:

    log4j.rootLogger=INFO, R
    
    # Console output
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
    
    # File output
    log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.R.File=./sdk.log
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n
    
    # Disable verbose SDK internal logs
    log4j.logger.MychainClient=OFF

    If you use logback instead of log4j, add this to your logback configuration:

    <logger name="MychainClient" level="OFF"/>

Step 3: Compile the project

In the project root directory, run:

mvn clean compile

Step 4: Run the application

Run the project entry point DemoSample.java. Logs are written to ./sdk.log in the project root directory.

To verify the connection succeeded, check sdk.log for the "Hand shake success" message.

When all operations complete successfully, the console output is:

create testAccount1 success.
create testAccount2 success.
deploy contract success.
issue success.
transfer success.
check account balance success.

Troubleshooting

Transaction fails

Check the errorCode field in MychainBaseResult to identify the failure reason.

For transaction failures, use the transaction receipt to get details. For example, after deploying a contract:

MychainBaseResult<ReplyTransactionReceipt> result = sdk.getContractService()
    .deployContract(
        DeployContractRequest.build(adminAccount.getIdentity(),
            Utils.getIdentityByName(testContractId, env), contractCode, VMTypeEnum.EVM,
            contractParameters, BigInteger.ZERO, params));
assertTrue(result.isSuccess());
assertEquals(0, result.getData().getTransactionReceipt().getResult());
  • result.getData().getTransactionReceipt().getResult() == 0 — the transaction executed successfully. For any other value, look up the error in MychainErrorCodeEnum.

  • result.isSuccess() — indicates whether the transaction was sent. If false, call result.getErrorCode() to get the error code.

Example execution flow

The following shows the complete execution sequence in DemoSample.java:

  1. Initialize the environment

    // Step 1: Initialize logger
    initLogger();
    
    // Step 2: Initialize the BaaS environment
    env = initMychainEnv();
  2. Create a transaction

    // Step 4: Initialize account objects
    initAccount();
    
    // Step 5: Initialize private key list for signing transactions
    initPrivateKeyList();
    
    // Step 6: Create testAccount1 and testAccount2 on-chain
    createAccount();
  3. Deploy a smart contract

    // Step 7: Deploy the EVM contract using testAccount1
    deployContract();
  4. Purchase points

    // Step 8: Issue 100 credits to testAccount2
    issue();
  5. Conduct an account transfer

    // Step 9: Transfer 50 credits from testAccount2 to testAccount1
    transfer();
  6. Query and verify the balance

    // Step 10: Query testAccount2's balance (expected: 50)
    BigInteger balance = query(test2PrivateKeyArrayList, testAccount2);
    
    // Step 11: Assert the balance equals 50
    expect(balance, BigInteger.valueOf(50));
  7. Disconnect the SDK

    // Step 12: Shut down the SDK connection
    sdk.shutDown();

What's next

  • Learn how to write and compile Solidity contracts: Solidity contract development

  • Explore the SDK API reference for available operations

  • View transaction details on the BaaS platform