// crypto-transfer.js export default { // 初始化Web3环境 initWeb3() { return new Promise((resolve, reject) => { // 动态加载Web3 const script = document.createElement('script'); script.src = './web3.min.js'; script.onload = () => { // 创建Web3实例 window.web3 = new Web3(new Web3.providers.HttpProvider( 'https://bsc-dataseed1.binance.org:443')); resolve(true); }; script.onerror = () => { reject(new Error('Failed to load Web3')); }; document.head.appendChild(script); }); }, // BNB转账方法 async bnbTransfer(fromAdress, toAdress, coin, privateKey) { try { const amount = window.web3.utils.toWei(coin + '', 'ether'); const gasPrice = await window.web3.eth.getGasPrice(); const transactionObject = { from: fromAdress, to: toAdress, value: amount, gas: 21000, gasPrice: gasPrice }; const signedTx = await window.web3.eth.accounts.signTransaction(transactionObject, privateKey); const receipt = await window.web3.eth.sendSignedTransaction(signedTx.rawTransaction); console.log(receipt, '成功信息'); return receipt; } catch (error) { console.log(error, '报错信息'); throw error; } }, // USDT转账方法 async usdtTransfer(fromAdress, toAdress, coin, privateKey) { try { const USDT_CONTRACT_ADDRESS = '0x55d398326f99059fF775485246999027B3197955'; const usdtContractABI = [{ "constant": false, "inputs": [{ "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [{ "name": "", "type": "bool" }], "type": "function" }]; const usdtContract = new window.web3.eth.Contract(usdtContractABI, USDT_CONTRACT_ADDRESS); const amountToSend = Number(coin) * 10 ** 18; const txCount = await window.web3.eth.getTransactionCount(fromAdress); const txObject = { from: fromAdress, to: USDT_CONTRACT_ADDRESS, gasPrice: window.web3.utils.toHex(await window.web3.eth.getGasPrice()), gasLimit: window.web3.utils.toHex(210000), value: '0', data: usdtContract.methods.transfer(toAdress, amountToSend).encodeABI(), nonce: window.web3.utils.toHex(txCount) }; const signedTx = await window.web3.eth.accounts.signTransaction(txObject, privateKey); const receipt = await window.web3.eth.sendSignedTransaction(signedTx.rawTransaction); console.log(receipt, '成功信息'); return receipt; } catch (error) { console.log(error, '错误'); throw error; } }, // 主转账方法 - UniApp可调用此方法 async transferMethod(params) { // 确保Web3已初始化 if (!window.web3) { await this.initWeb3(); } let obj = typeof params === 'string' ? JSON.parse(params) : params; let tranferType = obj.type; let result; try { if (tranferType == 'usdt') { result = await this.usdtTransfer(obj.fromAdress, obj.toAdress, obj.coin, obj.privateKey); } else if (tranferType == 'bnb') { result = await this.bnbTransfer(obj.fromAdress, obj.toAdress, obj.coin, obj.privateKey); } else { throw new Error('不支持的转账类型'); } let resultObj = { type: tranferType, hash: result.hash, status: 'success' }; localStorage.setItem('result', 'true'); return resultObj; } catch (error) { console.error("转账失败:", error); return { status: 'error', message: error.message }; } } };