跳到主要内容

区块链转账

区块链转账

信息

在DeBox的小程序中可以通过Web3js标准接口实现获取钱包地址、钱包授权、签名转账等功能;
DeBox App中支持的所有链,在小程序中都可以进行连接,并进行相关操作;
截止到2024年1月3号,支持ETH , BNB , Polygon , Arbitrum One , Optimism , zkSync Era,其对应chainId如下:
ETH:0x1 , BNB:0x38 , Polygon:0x89 , Arbitrum One:0xa4b1 , Optimism:0xa , zkSync Era : 0x144

技术支持

欢迎加入技术支持群:https://m.debox.pro/group?id=cc0onr82

下面是一个在小程序中进行区块链转账的Demo,支持上面六条链。
可以通过选择框切换公链,实际项目中请根据自身业务构造自己的UI

请确保对应钱包中有足够的资产,并给予足够的gasprice,否则可能因gas费不足、资产不足而无法拉起转账页面。

Demo体验地址:https://docs.debox.pro/demo/web3.html ,复制地址在DeBox中打开即可体验。
Demo下载链接:点击下载Demo的代码

第一步,引入web3.js

<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>

第二步,检查浏览器环境中web3对象是否被正常注入

1、检查 Web3是否存在
2、检查window.ethereum是否存在
3、用new Web3(window.ethereum);构造web3对象 Alt text 示例代码如下:

  <script>
window.str = "";
function checkWallet() {
if (typeof Web3 !== 'undefined') {
str= "存在Web3 type";
if (window.ethereum) {
// 使用 window.ethereum
str += "<br/>存在window.ethereum对象";
window.web3 = new Web3(window.ethereum);
str += "<br/>生成window.web3对象";
} else if (window.web3) {
// 使用 window.web3.currentProvider(Web3.js v0.x.x)
str += "存在window.web3对象";
window.web3 = new Web3(window.web3.currentProvider);
} else {
// 提示用户安装以太坊提供的钱包
str += '请安装 MetaMask 或其他以太坊提供的钱包';
}
str += "<br/>" + "web3.currentProvider.isMetaMask==" + web3.currentProvider.isMetaMask;
$("#account").html(str);
} else {
$("#env").html("No web3? 需要安装<a href='https://metamask.io/'>MetaMask</a>!");
}
}
</script>

如果js正常引入,代码运行结果如下:
Alt text

第三步,选择区块链网络

1、通过html构造切换区块链网络的UI
2、DeBox当前支持六条链,chainID分别为:
eth:0x1 , bnb:0x38 , Polygon:0x89 , Arbitrum One:0xa4b1 , Optimism:0xa , zkSync Era : 0x144 Alt text

切换链的示例代码demo如下:

          <script>
function changeWallet() {
try {
var chainId = $("#chainid").val()
web3.currentProvider.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: chainId }],
});
} catch (error) {
str += "<br/>error wallet_switchEthereumChain:" + error;
$("#account").html(str);
}
}
</script>

选择DeBox支持的任意链,进行网络切换:
Alt text

第四步,拉起区块链钱包、签名授权、而后完成转账

1、通过eth_requestAccounts 获取转账的钱包账户
2、构造转账的交易对象transactionObject
3、调用web3.eth.sendTransaction拉起钱包签名授权,并完成转账 Alt text

转账代码demo如下:

<script>
// 转账函数
function transfer() {

// 请求用户授权
// window.ethereum.enable()
window.ethereum.request({ method: 'eth_requestAccounts' })
.then(accounts => {
var from = accounts[0]; // 用户授权的账户地址
var to = $("#to").val();
var value = $("#amount").val();
var amountValue = web3.utils.toWei(value, 'ether');
// alert("amountValue: " + JSON.stringify(amountValue));

var gas = $("#gas").val();
var gasprice = web3.utils.toWei($("#gasprice").val(), 'gwei');

$("#from").val(from);



// 构造一个简单的以太坊交易对象
const transactionObject = {
from: from,
to: to,
value: amountValue,
gas: gas, // 交易所需的 gas 数量
gasPrice: gasprice, // gas 价格(gwei)
data:"",
};

str += "<br/>构造的交易对象:" + JSON.stringify(transactionObject);
$("#account").html(str);

// alert("transactionObject" + JSON.stringify(transactionObject )
// 发送交易

str += "<br/>开始交易,调用sendTransaction";
$("#account").html(str);
web3.eth.sendTransaction(transactionObject)
// web3.eth.signTransaction(transactionObject)
.then(receipt => {
// 交易成功后的处理
console.log('Transaction receipt:', receipt);
str += "<br/>交易成功,receipt:" + receipt.transactionHash;
$("#account").html(str);
})
.catch(error => {
// 处理错误
console.error('Error:', error);
str += "<br/>调用sendTransaction时出现异常:" + error;
$("#account").html(str);

});
})
.catch(error => {
// 用户拒绝了授权请求或发生其他错误
console.error('Error:', error);
str += "<br/>调用window.ethereum.request获取账户时出现异常:" + error
$("#account").html(str);

});
}

运行转账代码,拉起转账签名界面,点击确定后完成转账:
Alt text

F.A.Q

代码逻辑都对,为何拉不起来支付页面?

1、gasprice给的太低,小于base价格。
2、资产不足。资产余额小于转账金额+gas费。
3、网络不好,由于区块链一些节点在境外,可能存在因网络不通导致无法正常转账,科学上网。