Community Selections | Reform Digging to Support the Transfer Function of ATON WallectConnect

ATON 1.1.0 Version has already supported walletconnect protocol. Users can realize the connection and transaction signature with DApp on the premise of ensuring that the private key does not leave the mobile device and is not exposed to DApp. In this chapter we will transform the Digging of browser version to realize the transfer function through WallectConnect.

Create project

This function is built by deleting the source code in Learning from DEX Platon Application Development – JavaScript. The transformed project directory is as follows:

8c3131f295b5bbb85b4b9d7092ae7ec

We only keep main-page.vue ands end-lat-page.vue here. At the same time, we need to move all the files in the public/js directory to the public directory, and only keep web3.js and web3-eth-accounts.js. After that, modify the contents of manifest.json as follows:

{
  "manifest_version": 2,
  "name": "Digging",
  "version": "0.10",
  "description": "Digging Wallect Connect",
  "author": "DQTech",
  "content_security_policy": "default-src 'self';script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline';img-src 'self' data: base64; connect-src *",
  "icons": {
    "48": "48.png"
  },
  "browser_action": {
    "default_icon": "32.png",
    "default_title": "Digging",
    "default_popup": "popup.html"
  },

  "permissions": [
    "tabs",
    "storage",
    "unlimitedStorage",
    "clipboardWrite",
    "activeTab",
    "webRequest"
  ]
}

Then we introduce web3.js and web3-eth-accounts.js into home.html, and 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" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <title>DQTech</title>

    <style>
      .mord {
        padding-left: 0px !important;
      }
    </style>
  </head>

  <body>
    <div id="app"></div>
    <script src="./web3.js"></script>
    <script src="./web3-eth-accounts.js"></script>
  </body>
</html>

Install WallectConnect SDK

Open the current console with the console and enter the command

npm install @walletconnect/client @walletconnect/qrcode-modal

Start writing the code of main-page.vue after install

Write the code of main-page

The layout code is as follows:

<template>
    <div v-if="isConnect" class="main-outer-page">
        <div class="main-page vertical-only-layout">
            <div class="horzontal-layout flex-center ">
                <header-bar />
                <span class="flex-1"></span>
            </div>
            <div class="vertical-layout main-container ">
                <div class="horzontal-layout menu-bar ">
                    <div class="flex-1"></div>

                    <el-tooltip effect="dark" :content="copyText" placement="bottom">
                        <div
                            class="account-bar vertical-layout flex-1 flex-center pointer"
                            @mouseleave="onTipLeave"
                            @click="onCopyAccount"
                        >
                            <span class="account">当前账号</span>
                            <span class="address">{{ address }}</span>
                        </div>
                    </el-tooltip>
                    <span class="flex-1"></span>
                </div>
                <div class="wallet-overview vertical-layout-center">
                    <img src="@/assets/logo.png" class="logo" />

                    <div class="horzontal-layout flex-center currency-container">
                        <span class="currency" style="margin-right:6px;">{{ lat }}</span>
                        <span class="currency">LAT</span>
                    </div>
                    <el-button type="primary" round @click="onJumpToSendLatPage">
                        <i class="el-icon-position"></i>
                        发送</el-button
                    >
                </div>
            </div>
        </div>
    </div>
</template>


The logic code is as follows:

<script>
import headerBar from "@/component/header-bar.vue";
// 引入walletconnect的sdk
import WalletConnect from "@walletconnect/client";
import QRCodeModal from "@walletconnect/qrcode-modal";

import { mapState } from "vuex";
export default {
    components: {
        headerBar
    },
    computed: {
        ...mapState(["connector"])
    },
    data() {
        return {
            isConnect: false, //判断是否和aton连接,如果未连接不显示主页面
            address: "", // 地址
            lat: 0, // 当前余额
            web3Ins: null
        };
    },
    mounted() {
        let isOpenInTab = window.location.pathname !== "/popup.html";

        //先默认在tab打开
        if (!isOpenInTab) {
            chrome.tabs.create({ url: "home.html" });
        } else {
            this.init();
        }
    },
    methods: {
        init() {
            // 创建web的对象,用于获取余额和转换地址
            this.web3Ins = new Web3(new Web3.providers.HttpProvider("http://35.247.155.162:6789"));
            this.walletConnectInit();
        },

        async walletConnectInit() {
            // 构建wallet connector的session
            const bridge = "https://bridge.walletconnect.org";
            let connector = new WalletConnect({ bridge, qrcodeModal: QRCodeModal });
            if (!connector.connected) {
                await connector.createSession();
            }
            // 设置到store,让其他页面也可以使用connector
            this.$store.commit("SetConnector", connector);
            this.subscribeToEvents();
        },
        async subscribeToEvents() {
            // 订阅时间
            if (!this.connector) {
                return;
            }
            // 建立连接
            this.connector.on("connect", (error, payload) => {
                if (error) {
                    throw error;
                }
                this.onConnect();
            });
            // 连接断开
            this.connector.on("disconnect", (error, payload) => {
                console.log(`connector.on("disconnect")`, payload);
                if (error) {
                    throw error;
                }
                this.onDisconnect();
            });

            this.onConnect();
        },

        onConnect() {
            if (!this.connector.connected) {
                return;
            }
            const { chainId, accounts } = this.connector;
            let address = accounts[0];
            this.isConnect = true;
            // wallectconnect获取的地址都是16进制的,这里转成lat开头的地址
            this.address = this.web3Ins.utils.toBech32Address("lat", address);

            this.getBalanceOf();
        },
        async getBalanceOf() {
            // 获取钱包地址,这里需要使用lat开头的地址
            let balance = await this.web3Ins.platon.getBalance(this.address);
            this.lat = this.web3Ins.utils.fromVon(balance, "lat");
        },
        onJumpToSendLatPage() {
            this.$router.push({
                path: "/send-lat",
                query: {
                    account: this.accountName
                }
            });
        }
    }
};
</script>


The interface would be like follows:

1,QR code page displayed by browser:

YQ30MJYHN%DU1~`12R@DK

2,When you open Aton and scan the QR code

970C24BA73AA7CD6CE5B6705567E4A39
7E0E25708EB53E8ABE4D516A8CC9C7F3

3,The Authorization Page of Aton

2749885FFA9BE338E724DE3D27AC3E06

4,The Page after Successful Authorization

9223D110BAA9CF8B9423EDF941CEF4F2

5,The browser page will be as shown in the figure below:

%LOFQEM$R37O)ZQ(}EE

You can see the same balance as ATON here

Write Transfer Function

The layout code of send-lat-page.vue is as follow:

<template>
    <div class="send-lat-page vertical-only-layout">
        <header-bar />
        <div class="go-back" @click="onGoBack">< Back</div>
        <page-title>发送LAT</page-title>
        <el-form ref="sendForm" :model="sendInfo">
            <el-form-item prop="toAddress" label="接收地址">
                <el-input
                    class="send-input"
                    v-model="sendInfo.toAddress"
                    placeholder="请输入接收地址"
                />
            </el-form-item>
            <el-form-item prop="lat" label="LAT数量">
                <el-input
                    class="send-input"
                    type="number"
                    v-model="sendInfo.lat"
                    placeholder="请输入要发送的LAT数量"
                />
            </el-form-item>

            <el-form-item>
                <div class="horzontal-layout">
                    <span class="flex-1"></span>
                    <el-button class="create-btn" @click="onGoBack">取消</el-button>

                    <el-button class="create-btn" type="primary" @click="doSend">发送</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>


Logic code is as follow:

...省略代码
async doSend() {

            let web3Ins = new Web3(new Web3.providers.HttpProvider("http://35.247.155.162:6789"));

            const { accounts } = this.connector;

            // 这里要转成lat账号才可以获取到交易数量

            let latAddress = web3Ins.utils.toBech32Address("lat", accounts[0]);

             // 使用交易数量做nonce

            let nonce = await web3Ins.platon.getTransactionCount(latAddress);

            // 获取当前的手续费用

            let gasPrice = await web3Ins.platon.getGasPrice();

            // wallectconnect只支持16进制的地址,因此需要把lat的地址转换

            let toHexAddress = web3Ins.utils.decodeBech32Address(this.sendInfo.toAddress);

            this.connector

                .sendTransaction({

                    data: "",

                    from: accounts[0],

                    gasLimit: 21000,

                    gasPrice: gasPrice,

                    nonce: nonce,

                    to: toHexAddress,

                    value: web3Ins.utils.toVon(this.sendInfo.lat, "lat")

                })

                .then(txHash => {

                    // 发送交易成功, 钱包会返回交易hash

                    console.log("txHash: ", txHash);

                });

            this.onGoBack();

        },
...省略代码


The interface would be like follows:

1640695891(1)

For demonstrate, here shows to sending five lats, as shown below:

W`O0I{~WIARHL$IZJ4{C8U

The Sent Confirmed Page of ATON:

A9FA5D7327ACE090640CE8083611460A

Screenshot of Successful Sending of ATON:

48DCC3E18F884DE947F6559BAD6CD06D

Meanwhile, the balance of the browser changes as follows:

Y{64(8ENMW3ZQ(HN79EAZ9J

That’s all of this chapter. If you are interested, you can modify the docking mode of Digging and PlatON to WalletConnect according to the idea of this chapter.

The URL of github: https://github.com/DQTechnology/Platon_DevGuideProject/tree/master/wallet-javascript/walle_connect

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

Like (0)
PlatOnWorld-Kita's avatarPlatOnWorld-KitaOfficial
Previous December 29, 2021 11:24
Next December 29, 2021 16:05

相关推荐

Leave a Reply

Please Login to Comment