This topic uses examples to describe how to use the JS SDK.
Environment
Install the SDK
Download and install Node.js from the Node.js official website. We recommend you use v10.11.0 or later versions.
Install the JS SDK. You can follow download instructions to download JS SDK to the project directory and install it in the directory.
npm i alipay-mychain-0.2.27.tgz --save
Prepare files for SSL connection
To build an SSL connection, three certificate files are required: ca.crt
, client.key
, and client.crt
.
If you have not applied for a certificate in the contract blockchain, you can follow the instructions in Quick Start chapter Access the Blockchain to generate certificate-related files.
Certificate file | Description | Source |
---|---|---|
ca.crt | In a contract blockchain, this certificate file is used for server authentication. | This certificate file is open for download in the BaaS platform. |
client.key | The RSA private key. | You can use the key generation tool provided by BaaS to generate the RSA private key. |
client.crt | The RSA certificate. It is in pair with the client.key file. |
You can use the key generation tool to generate the certificate application file client.csr . Submit the application file to the BaaS platform. You can download the certificate after the application is approved. |
Prepare a contract blockchain account
When you submit a transaction on the contract blockchain, you need to use an account that already exists in the blockchain. JS SDK requires the account name and the private key file of the account.
You can apply to create an account in the BaaS platform. To apply for a certificate (follow the instructions in chapter Access to Blockchain), you need to specify the name, public key, and the recovery public key of the account. The user.key
file corresponding to the account public key is the private key file of the account. Convert this private key file so it can be used with ease in JS SDK.
openssl ec -in user.key -passin pass:${key_password} -passout pass:${key_password} -aes256 -out user.pem
${key_password}
with the private key password.Use JS SDK
Connect to the blockchain using an existing instance chain
. You can call the QueryLastBlock
operation to verify the connection between this instance and the blockchain.
const Chain = require("@alipay/mychain/index.node") //Use the TLS protocol in the node environment
const fs = require("fs")
const accountKey = fs.readFileSync("./certs/user.pem", { encoding: "utf8" })
const accountPassword = "123abc" // To be replaced with the user-defined user.pem password
const keyInfo = Chain.utils.getKeyInfo(accountKey, accountPassword)
//The private key and the public key are hexadecimal strings and can be printed
//console.log('private key:', keyInfo.privateKey.toString('hex'))
//console.log('public key:', keyInfo.publicKey.toString('hex'))
const passphrase = "123abc" //To be replaced with the user-defined client.key password
//Configuration options
let opt = {
host: '127.0.0.1', //IP of the target blockchain node
port: 18130, //Port number
timeout: 30000, //Time configuration for connection timeout
cert: fs.readFileSync("./certs/client.crt", { encoding: "utf8" }),
ca: fs.readFileSync("./certs/ca.crt", { encoding: "utf8" }),
key: fs.readFileSync("./certs/client.key", { encoding: "utf8" }),
userPublicKey: keyInfo.publicKey,
userPrivateKey: keyInfo.privateKey,
userRecoverPublicKey: keyInfo.publicKey,
userRecoverPrivateKey: keyInfo.privateKey,
passphrase: passphrase
}
//Initialize a connection instance
const chain = Chain(opt)
//Call the QueryLastBlock operation to query the last block
chain.ctr.QueryLastBlock({}, (err, data) => {
console.log('raw data:', data) //The block structure data
console.log('block hash:', data.block.block_header.hash) //The block hash
console.log('block number:', data.block.block_header.block_number) //The height of the block
})
Sample successful results:
raw data: { msg_type: 58,
sequence: 1,
return_code: 0,
group_id: '0x0000000000000000000000000000000000000000',
block:
{ block_header:
{ hash:
'0xe99d8958a45e8c87a7b10efc259828f06fe083995be52997f5d310f2b6d073a6',
version: 2,
block_number: 84265,
parent_hash:
'0x918b263a8e6c6fff594b89570970ef4bef24cf93aeed5347f7b250b070857c4b',
transaction_root:
'0x0000000000000000000000000000000000000000000000000000000000000000',
receipt_root:
'0x0000000000000000000000000000000000000000000000000000000000000000',
state_root:
'0x9f71cb9ce960e5637bad6da5be8daa2d7e557942208f241a60589b2de98e6c71',
gas_used: 0,
timestamp: 1547382477852,
log_bloom:
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' },
block_body:
{ transaction_list: [],
receipt_list: [],
consensus_proof:
'0xf8f2f8c9b8419746989382c1613c6c3ce98bf79ac92a8d69952c22f4064194869c53b4075d517cfc98eda861212687e49b186c08d196770bd356762fa2a88d0288c0556f271a01b84138a97446a75c76a31d24880c343407bd7bc24608685c494240ac603cad62201a01a423718661b24e517ee6f6b2fee6d356b57833305860700cca81b0238f870400b841eaf508392d9098a3e7fb46f6f7aa4b53311e5a0d13e300d02025af7453ea130a6c27407c1da254578cae80ed498d4807587883f837c1716b0be8ae02cf955d6000e61e83014929a0e200d8bee723d820022d5c5a1f8fe6b521c0a4fff0b5ec03a7c6061276d68b58' } },
api: 'QueryLastBlock' }
block hash: 0xe99d8958a45e8c87a7b10efc259828f06fe083995be52997f5d310f2b6d073a6
block number: 84265
Sample results contain the
return_code
field. If the value of the return_code
field is 0, the call is successful, otherwise, it is an error code that indicates the call has failed. The result
field in the transaction receipt works in the same way. For more information about error codes, see Error codes.JS SDK reference
JS SDK is referenced differently in different environments.
Node environment:
const Chain = require("@alipay/mychain/index.node")
Web environment:
const Chain = require("@alipay/mychain")
Configuration items
Before you initialize the instance connected to the blockchain, you can modify the configurations. Each configuration item is described as follows:
Configuration item | Required | Description | Sample value |
---|---|---|---|
host | true | The IP address or server name of a blockchain node. It refers to the IP address when the TLS protocol is used and the server name when the HTTPS protocol is used. | 127.0.0.1 , https://www.alipay.com or https://127.0.0.1 |
port | true | The port number of the open blockchain node. It must be numbers only. | 18130 |
clients | false | You can specify multiple addresses host:port as backups. When the primary node has a connection problem, the SDK switches to other nodes in the list for reconnection. If you configure this parameter, you do not need to set the host parameter and the port parameter. |
[{host:’127.0.0.1’,port:18130}, {host:’127.0.0.2’,port:18130}] |
timeout | true | The time configuration for connection timeout. The unit is milliseconds. | 30000 |
ca | true | The root certificate of the target contract blockchain. | You can apply for the certificate in the BaaS platform. For more information, see Quick start |
cert | true | The client certificate file. | You can apply for the certificate in the BaaS platform. For more information, see Quick start |
key | true | The private key file generated by the client. It is used to generate a certificate request file for certificate application. | You can use the key generation tool to generate the certificate application file. For more information, see Quick start |
userPublicKey | true | The public key of the account. The key is a hexadecimal string. | 0x971c77d38bf220572fe8294d7884b184adeeb9bac4d61c1b3e1e924575e526152145763eaba40c8713c82cc2961fba98f71c8b93984d4e3d10b2ff53ea039551 |
userPrivateKey | true | The private key of the account. The key is a hexadecimal string. | 0x4015e39643765014b874dbd35a53f1a01418c66f7c47da35f3a84122c743d9a3 |
userRecoverPublicKey | true | The recovery public key of the account. The key is a hexadecimal string. | 0xb961f6a1a43b9e7aa368be8d093ed7bec2d0ff85ff7646ec968d86bd546151efbd037cfe09933684b5c98978a1593074cdff465de3a3620089f5634911bf7b2e |
userRecoverPrivateKey | true | The recovery private key of the account. The key is a hexadecimal string. | 0x44a973e5286f1d3513561360bb0214235425b942a4649c7d371f780ca1ee0e80 |
passphrase | true | The user-defined password of the client.key file. This password is used for the TLS or HTTPS connection. |
123abc |
checkServerIdentity | false | This configuration item is used for the TLS connection and is of the boolean type. This configuration determines whether to enable the checking of the server hostname. That is to check whether the CN field matches the hostname. The default value is false. |
false |
tx_querycount | false | After you submit a transaction, you can call the QueryTransactionReceipt operation to query the receipt. In this configuration item, you can set the number of retries. The number of retries is a numerical value and the default value is 3. |
5 |
tx_querytime | false | After you submit a transaction, you can call the QueryTransactionReceipt operation to query the receipt. In this configuration item, you can set the time interval. The time interval is a numerical value and the default value is 3,000 milliseconds. |
200 |