如何在 vue3 中连接sui 生态钱包,发起交易

Vue 前端框架如何接入 sui 生态

最近在做老的前端项目改造,老项目用的 vue作为前端框架,如何连接sui 生态的钱包一直我头疼的问题在以前的开发中,如果使用 react 框架,那可以很容易的使用官方的 @mysten/dapp-kit 构建一整套钱包连接和发起交易,签名的方法。

在 mysten labs 提供的方法中,有提供"@mysten/wallet-standard 这个库,搭配上@mysten/sui 便能自己构建相应的方法进行钱包连接,签名交易,我连接钱包的流程如下:

image.png

  1. 判断用户是否连接过钱包:

    initWallet() {
     // 通过存储的本地变量判断,一个记录连接的钱包名字,一个记录连接的钱包地址:
      const connectedWallet = window.localStorage.getItem("connectedWallet")
      const connectedAddress = window.localStorage.getItem("connectedAddress")
      if (connectedWallet && this.supportWallets.includes(connectedWallet) && connectedAddress) {
        this.connectWallet(connectedWallet)
      }
    }
  2. 连接钱包

    // 连接钱包(以 Slush 为例)
    async connectWallet(walletName) {
    try {
    const availableWallets = getWallets().get();
    let wallet = availableWallets.find(e => e.name === walletName)
    await wallet.features['standard:connect'].connect();
    if (wallet.accounts.length > 0) {
      // 通常第一个就是当前 active 的地址
      const address = wallet.accounts[0].address
      this.connectedWallet = wallet.name
      this.address = address
      window.localStorage.setItem("connectedAddress", address)
      window.localStorage.setItem("connectedWallet", wallet.name)
    }
    // 监听钱包地址变化, 断开
    wallet.features['standard:events'].on('change', (event) => {
      // 如果当前钱包的地址与存储的地址不一致或者断开连接的业务逻辑
      if (event.accounts.length === 0 || event.accounts[0].address !== this.address) {
        console.log('User change or disconnect ...');
        setTimeout(() => {
          window.localStorage.removeItem("connectedAddress")
          window.localStorage.removeItem("connectedWallet")
          window.location.reload()
        }, 1000)
      }
    });
    } catch (error) {
    console.log(error);
    }
    }

    下面就是转账的操作,所有的交易都可以使用wallet.features['sui:signTransaction'].signTransaction来进行签名:

    // 转账
    async transferSui() {
    try {
    const wallet = getWallets().get().find(e => e.name === this.connectedWallet)
    const amount = this.amount
    const toAddress = this.toAddress
    const tx = new Transaction()
    const [coin] = tx.splitCoins(tx.gas, [amount * 1e9])
    tx.transferObjects([coin], toAddress)
    const { bytes, signature } = await wallet.features['sui:signTransaction'].signTransaction({
      transaction: tx,
      account: wallet.accounts[0],
      chain: `sui:${import.meta.env.VITE_SUPPORT_NETWORK}`
    });
    const executeRes = await suiClient.executeTransactionBlock({
      transactionBlock: bytes,
      signature: signature,
      options: {
        showEffects: true,
        showObjectChanges: true,
        showBalanceChanges: true,
        showEvents: true,
        showInput: true
      }
    });
    this.hash = executeRes.digest
    } catch (error) {
    console.log(error);
    }
    }

    最后,可以在 web 上面做一个断开钱包连接的功能:

    // 断开钱包
    async disconnectWallet() {
    try {
    const availableWallets = getWallets().get();
    const walletName = window.localStorage.getItem("connectedWallet")
    let wallet = availableWallets.find(e => e.name === walletName)
    await wallet.features['standard:disconnect'].disconnect();
    window.localStorage.removeItem("connectedAddress")
    window.localStorage.removeItem("connectedWallet")
    window.location.reload()
    } catch (error) {
    console.log('meet some errors ');
    }
    },

代码详情可查看: https://github.com/djytwy/vite-vue

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Rainer Tian
Rainer Tian
0x190c...03bf
江湖只有他的大名,没有他的介绍。