uni-app 构建以太坊/币安链 DApp 转帐实战

·

关键词:uni-app、DApp、Web3.js、ETH 转账、BNB 转账、钱包集成、智能合约调用

面向移动端的 uni-app 无需切换技术栈即可快速上线 以太坊币安智能链(BSC)等多链 DApp。本指南聚焦「转账」这一高频场景,手把手演示如何集成 Web3.js、连接钱包、调合约,一行行代码贴给你。


一、环境准备 & 安装依赖

1. 初始化项目

vue create -p dcloudio/uni-preset-vue my-dapp
cd my-dapp

2. 安装 web3

npm install web3 --save
如果体积过大可选用 web3.min.js CDN,但移动端推荐 npm 打包到云函数。

3. 开启节点 RPC


二、页面结构:一键检测钱包

核心页面 pages/transfer/index.vue

<template>
  <view class="container">
    <text class="title">钱包地址:{{ walletAddress || '未连接' }}</text>
    <button @tap="initWallet">连接 MetaMask</button>

    <view class="card">
      <input v-model="amount" placeholder="数量" type="number" />
      <picker :range="tokenList" @change="setToken">
        <view>{{ currentToken || '选择代币' }}</view>
      </picker>
      <input v-model="toAddress" placeholder="接收地址" />
      <button @tap="submit">发生转账</button>
    </view>
  </view>
</template>

三、核心逻辑:三步完成转账

1. 连接钱包(MetaMask/H5)

onLoad() {
  // H5 环境
  if (window.ethereum) {
    window.ethereum.request({ method: 'eth_requestAccounts' })
      .then(accounts => this.walletAddress = accounts[0])
      .catch(() => alert('用户拒绝连接'));
  } else {
    alert('请安装 MetaMask 或兼容钱包');
  }
}

2. 初始化 Web3 与合约实例

getWeb3() {
  return new Web3(window.ethereum || 'https://bsc-dataseed1.binance.org');
}

3. 划重点:两种转账场景

✔ 原生链币(ETH/BNB)转账

transferNative() {
  const web3  = this.getWeb3();
  const wei   = web3.utils.toWei(this.amount, 'ether');
  web3.eth.sendTransaction({
    from:  this.walletAddress,
    to:    this.toAddress,
    value: wei,
    gas:   21000,
    gasPrice: web3.utils.toWei('5', 'gwei')
  }).on('transactionHash', hash => {
    console.log('转账 Hash', hash);
  });
}

✔ 代币(USDT、DAI 等)转账

async transferToken() {
  const web3  = this.getWeb3();
  const contract = new web3.eth.Contract(ERC20ABI, this.currentTokenAddress);

  const decimals = await contract.methods.decimals().call();
  const amountInUnit = new BigNumber(this.amount).times(10 ** decimals);

  await contract.methods.transfer(this.toAddress, amountInUnit.toString())
    .send({
      from: this.walletAddress,
      gas:  80000,
      gasPrice: web3.utils.toWei('5', 'gwei')
    });
}

四、常见坑与解决办法

痛点原因快速修复
MetaMask 弹窗被拒绝用户未授权引导到设置 → 站点权限
gas 估算失败页面未连接节点刷新或切换 RPC
转账卡住 pendinggas 过低手动提升或取消重发

五、实战 FAQ:3 分钟解决疑惑

Q1:uni-app H5 发布到 App Store 会被拒吗?
A:只要 DApp 本身不直接提供金融承诺,上架无望拒。建议隐藏敏感功能、使用 TestFlight 内测。

Q2:如何获取最新 gasPrice?
A:调用 web3.eth.getGasPrice(),或以 👉 链上实时推荐费率 为准,让用户选择「缓解拥堵/普通/快速」。

Q3:钱包签名失败?
A:确认 私钥/助记词 保密,插件升级到最新稳定版即可。

Q4:ERC20 的 ABI 通用吗?
A:标准的 transfer、balanceOf 基本一致,但Approve 权限函数需谨慎,防止过度授权。


六、进阶:多端打包与合约审计

  1. H5Android/iOS:通过 HBuilderX 一键云打包,无需额外改动。
  2. 钱包签名uniCloud签名:将私钥托管到云函数,前端通过 token 换取交易签名结果,提高安全性。
  3. 合约安全 → 推荐使用开源审计模版:OpenZeppelin 合约。若有自定义安全需求,务必做 Slither 静态扫描。

七、小结

完成以上步骤,你就拥有了一个在 安卓、iOS、微信、浏览器 全端通用的 uni-app ETH/BSC DApp
提前搭建测试网(Goerli / BNB Testnet),把 uni-app、Web3.js、钱包连接、转账逻辑 跑通,即可安心发布主网。祝开发顺利!

👉 查看最新链上手续费与测试代币领取入口