DQtech Column | Learn from DEX about PlatON Application Development – Javascript (II)

In the previous chapter, we completed the construction of the environment and query the balance of the wallet. In this chapter, we will explain how to call common interfaces through JavaScript.
   For simplicity of testing, all outputs covered in this chapter are printed directly on the console. To open the console, press F12 in the browser to pop up the following dialog box,

微信图片_20211124221836

Select the Console option interface。

1,Batch Request

The official website example only illustrates the usage of this interface and does not explain the callback function After the author tests the return value of the callback function, the first one is null and can be ignored, and the second one is the balance of the wallet The code is as follows:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo1</title>
</head>
<body>

    <script src="./web3.js"></script>

    <script>

        // 构建web3对象,这里的网址是PlatON的测试链地址

        let platonWeb = new Web3(new Web3.providers.HttpProvider('http://35.247.155.162:6789'));

        // 1, 批量获取钱包的余额,以下为笔者准备的两个钱包地址

        let addr1 = "lat1zrq89dhle45g78mm4j8aq3dq5m2shpu56ggc6e";

        let addr2 = "lat1sc64spe34m4zt5mycf9njkvw7fg98g0uncwgsa";

        // 2, 创建批量请求
        let batch = new platonWeb.BatchRequest();
        // 3,添加请求
        batch.add(platonWeb.platon.getBalance.request(addr1, "latest",
            (arg1, balance) => {

                // arg1 忽略
                console.log("arg1:" + arg1 + ", balance_1:" + balance);
            }));

        batch.add(platonWeb.platon.getBalance.request(addr2, "latest",
            (arg1, balance) => {
                console.log("arg1:" + arg1 + ", balance_2:" + balance);
            }));

        // 执行请求
        batch.execute();
    </script>
</body>
</html>

We can select network in the console and click request. From payload, we can see that this interface will merge our two requests into one HTTP request Then return the balance under their respective callback
Resoult as below:

7b6214e53e7ca83579104dfe1e8dc7e

2,Get Address Hrp

Codes here:

   // 获取当前链的地址前缀
    platonWeb.platon.getAddressHrp().then(res=>{
        console.log(res);
    });

Because the wallet address prefix of Platon is lat, all the values obtained by this interface are lat.

ed802b7a1eafdac3fbf20c0ccfc2ebf

3, Get Gas Price

Codes below:

    // 获取当前gas的价格
    platonWeb.platon.getGasPrice().then(res => {
        console.log("von:" + res, "lat:" + platonWeb.utils.fromVon(res));
    });

The unit of the returned value of this interface is von. If you want to obtain the quantity of lat, you can convert it through the function web3.utils.fromVon. This value is determined by the median of the nearest blocks It can be used as a reference value for us to set gas.

bccab09a792c1d26a311f93b0341419

4, Get Block Number

Codes below :

    // 获取当前的块高
    platonWeb.platon.getBlockNumber().then(res => {
        console.log(res);
    });

5, Get Block

Codes below:

     // 获取指定块信息
    platonWeb.platon.getBlock(6533257).then(res => {
        console.log(res);
    });
e8f53babe804b8bd429edc16d637790

The following is an explanation of the fields returned from the official website:

  • number – Number: The Block number. The block in pending state is null. The block number we queried is 6533257, so this value is 6533257
  • hash 32 Bytes – String: The hashvalue of blocks. The block in pending state is null.
  • parentHash 32 Bytes – String: The hashvalue of Parent Block 
  • nonce 8 Bytes – String: The hashvalue of generative proof-of-work ,The block in pending state is null.
  • logsBloom 256 Bytes – String: The bloom filter of Log in block,The block in pending state is null.
  • transactionsRoot 32 Bytes – String: The transaction root node in block
  • stateRoot 32 Bytes – String: The final state root in the block
  • miner – String: The miner Address for receiving the reward
  • extraData – String: The “extra data” field of block
  • size – Number: Block size in bytes
  • gasLimit – Number: The maximum gas value allowed for this block
  • gasUsed – Number: The total amount of gas used by all transactions in this block
  • timestamp – Number: The UNIX timestamp of outgoing block
  • transactions – Array: The transaction object array, or 32 byte long transaction hash value. It depends on the setting of returnTransactionObjects

Transactions is an array of all transaction hashes of the current block. In the return result of our example call, this field is an empty array, indicating that the block is an empty block, so the gasused field is 0 Here I’d like to ask a question, what is the meaning of empty blocks?

6, Get Block Transaction Count

We should obtain the code of the specified block and the transaction quantity of the specified block first. The code is as follows:

    // 获取指定块或者地址的交易数量
    platonWeb.platon.getBlockTransactionCount(6533257).then(res => {
        console.log(res);
    });
b168d2470934ac4fdff3dd31348714a

Through the return value of the getblock interface, we already know that the block is an empty block, so we can see that the number of returned transactions is 0

Next, we will get the number of transactions of the block through the hash value of the block. Previously, we obtained the hash value of block 6533257 through the getblock interface: 0x0561ab627d3053c486a552e594f6b3f40f7acc2fd107866169feb34de346129b. Let’s replace the block encoding with the hash value of the block

Codes below:

 // 获取指定块或者地址的交易数量

 platonWeb.platon.getBlockTransactionCount("0x0561ab627d3053c486a552e594f6b3f40f7acc2fd107866169feb34de346129b").then(res => {
        console.log(res);
    });

The number of transactions obtained still remain to 0.

7, Get Transaction Count

Codes below:


platonWeb.platon.getTransactionCount("lat1zrq89dhle45g78mm4j8aq3dq5m2shpu56ggc6e").then(res => {

        console.log(res);
    });

b299549f5fc5c2470949855d32ce4d4

We can see that the return value is 1255. Then we should view the transaction record of this address in the browser of the official website: https://devnetscan.platon.network/address-detailaddress=lat1zrq89dhle45g78mm4j8aq3dq5m2shpu56ggc6e

Drag the page to the bottom we could see that our total number of records is 1257.

b0b6b050a31deea80687f210df8bcb2

It seems that there are two more records, so what’s going on? Let’s look at the function of this interface. The value obtained by this interface is the number of transactions sent We found in the transaction records of the browser that there are two records of receiving transfers under this account

16255ec5c3f3a7bdcbbba773a27e28b

Interface transfer does not belong to the issued transaction quantity, so 2 needs to be subtracted, which is just the value obtained through the interface This interface is often used to set the nonce value of the transaction we send

8, Use Platon_sendRawTransaction to Complete the First Transfer

Our goal is to transfer lat to 1zrq89dhle45g78mm4j8aq3dq5m2shpu56ggc6e.

ca5bf02bfec412f61da94262ee15d7e

We need to modify a bug before compiling. Open the file client-sdk-js/packages/web3-utils/src/utils.js , find the function decodebech32address, and then add the var keyword before the address, as shown in the figure below:

45a280051b5d73e07e5fd11d1ad13a2
b0983ba243837eecd7b07c89c7c40af

Open the console in the current directory and enter npm run build-all

a98953c3f327327b991c2b492f0e92e

The compilation process needs to wait. After execution, you can see the following:

f99c4d1f80a11c59b155fd7a3bc3d76

Some of these errors do not affect the use and can be ignored. After compiling, we can see the newly compiled components in dist directory.

7f2fcf6b8c19cd3be84928573468981
  • 4, Introduce SDK. Here we always introduce Web3 eth accounts JS. The introduced code is as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>demo1</title>
    </head>
    <body>
        <!-- 新引入的sdk -->
        <script src="./web3-eth-accounts.js"></script>
        <script src="./web3.js"></script>
        <script>
            // 构建web3对象,这里的网址是PlatON的测试链地址
            let platonWeb = new Web3(new Web3.providers.HttpProvider('http://35.247.155.162:6789'));
     </script>
    </body>
    </html>
  • 5, Start to Write Code

    // 1, 第一个通过getTransactionCount获取当前账号的交易数量,用作nonce值

  platonWeb.platon.getTransactionCount("lat1tgu6pts6nhmneu5zhqly3rc83r6y6ecfmde03e").then(nonce => {

        // 2, 获取近期块的gasprice

        platonWeb.platon.getGasPrice().then(gasPrice => {

            // 3, 构建交易参数

            let txData = {

                from: "lat1tgu6pts6nhmneu5zhqly3rc83r6y6ecfmde03e", //转账的钱包地址

                to: "lat1zrq89dhle45g78mm4j8aq3dq5m2shpu56ggc6e", // 接收转账的地址

                value: '10000000000000000000', //value的单位为von 从官网得知 1Lat = 1e18个VON, 这里转10lat

                chainId: "210309", // 链ID 从官网得知 测试链的id为 210309

                gasPrice: gasPrice, //每一步的费用

                gas: 21000, // 步数 就是gasLimit

                nonce: nonce,

                data: ""

            };

            // 4, 使用私钥对参数签名

            platonWeb.platon.accounts.signTransaction(txData, "a4ac816da1ab40f805d026009247002f47c8c0a9af95b35ca9741c576466e1a8").then(signTxtData => {

                // 5, 调用接口把请求发送出去, 这里只需要发送rawTransaction
                platonWeb.platon.sendSignedTransaction(signTxtData.rawTransaction).then(res => {
                    // 6, 使用 transactionHash值去查询发送情况
                    platonWeb.platon.getTransactionReceipt(res.transactionHash).then(receipt => {
                        console.log(receipt);
                    });
                });
            });
        });
    });

Output results:

fac480b17ba5b70f178ee579ca6cfa2
Step description:

 1, The first transaction quantity of the current account obtained through getTransactionCount is used as the nonce value.

 2, Get gasplice of recent block

 3, Build transaction parameters

 4, Signing parameters with a private key

 5, Call the interface to send the request

 6, Judge whether the transaction is successful by obtaining the transaction hash value. There is a status field in the return value of this step. True means successful and false means  fail.
6cb32f7aa622ce2e56306eded2da7c5
1cbfcb09bb205acbb5a217a062821d2

Well, that’s the end of this chapter. In the next chapter, we can start building browser plug-ins

The URL of github : https://github.com/DQTechnology/Platon_DevGuideProject 

This article is reproduced from https://forum.latticex.foundation/t/topic/5818

Like (0)
PlatOnWorld-Kita's avatarPlatOnWorld-KitaOfficial
Previous December 20, 2021 11:18
Next December 21, 2021 10:39

相关推荐

Leave a Reply

Please Login to Comment