完成的功能:

  • 判断当前页面运行环境。
  • 封装web3.js,
  • 实现获取钱包地址,余额,授权,转账等功能

1、安装web3

npm install web3

2、在入口页面判断当前运行环境是否是钱包中

<script>
	export default {
		onLoad() {
			console.log(window);
			console.log(window.ethereum)
			if(window.ethereum === undefined){
				uni.showToast({
					title:"Wallet link error",
					icon:"none"
				})
			}else if(window.ethereum){
				this.$goBack(3, '/pages/index/index'); //以太坊,正常进入首页
			}
		},
		methods: {
		},
	}
</script>

3、封装web3.js,方便在每个页面调用

import { log } from "async";
import Web3 from "web3";
var contract = null;
var web3 = null;
var walletAddress = ''; //我的钱包地址
var toAddress = ''; //转账地址

// 正式
var contractDecimals = 18;
var contractAddress ='0x************************955';

// 获取钱包地址
export function getWalletAddress(callback) {
	web3 = new Web3(window.ethereum);
	//获取钱包地址
	window.ethereum.enable().then(function(accounts) {
		//myContract = new web3.eth.Contract(ABI, metaMaskAddress);
		//这里返回用户钱包地址
		walletAddress = accounts[0];
		callback(walletAddress, web3);
	}).catch(function(reason) {
		//如果用户拒绝了登录请求
		if (reason === "User rejected provider access") {
			// 用户拒绝登录后执行语句;
			uni.showToast({
				title: "User rejected provider access",
				duration: 3000,
				icon: 'none'
			})
		} else {
			// 本不该执行到这里,但是真到这里了,说明发生了意外
			uni.showToast({
				title: "There was a problem signing you in",
				duration: 3000,
				icon: 'none'
			})
		}
	});
}

// 获取钱包余额
export function getwalletBalance(callback) {
	// USDT 合约ABI
	let abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"deprecated","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_evilUser","type":"address"}],"name":"addBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"upgradedAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maximumFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_maker","type":"address"}],"name":"getBlackListStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newBasisPoints","type":"uint256"},{"name":"newMaxFee","type":"uint256"}],"name":"setParams","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"redeem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"basisPointsRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBlackListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_clearedUser","type":"address"}],"name":"removeBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"MAX_UINT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_blackListedUser","type":"address"}],"name":"destroyBlackFunds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_initialSupply","type":"uint256"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Issue","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAddress","type":"address"}],"name":"Deprecate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"feeBasisPoints","type":"uint256"},{"indexed":false,"name":"maxFee","type":"uint256"}],"name":"Params","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_blackListedUser","type":"address"},{"indexed":false,"name":"_balance","type":"uint256"}],"name":"DestroyedBlackFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"AddedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"RemovedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"}];
	// MyTest 合约ABI
	// let abi = [{"inputs": [],"payable": false,"stateMutability": "nonpayable","type": "constructor"}, {"anonymous": false,"inputs": [{"indexed": true,"internalType": "address","name": "_owner","type": "address"}, {"indexed": true,"internalType": "address","name": "_spender","type": "address"}, {"indexed": false,"internalType": "uint256","name": "_value","type": "uint256"},],"name": "Approval","type": "event"}, {"anonymous": false,"inputs": [{"indexed": true,"internalType": "address","name": "_from","type": "address"}, {"indexed": true,"internalType": "address","name": "_to","type": "address"}, {"indexed": false,"internalType": "uint256","name": "_value","type": "uint256"}],"name": "Transfer","type": "event"}, {"constant": true,"inputs": [{"internalType": "address","name": "_owner","type": "address"}, {"internalType": "address","name": "_spender","type": "address"}],"name": "allowance","outputs": [{"internalType": "uint256","name": "remaining","type": "uint256"}],"payable": false,"stateMutability": "view","type": "function"}, {"constant": false,"inputs": [{"internalType": "address","name": "_spender","type": "address"}, {"internalType": "uint256","name": "_value","type": "uint256"}],"name": "approve","outputs": [{"internalType": "bool","name": "success","type": "bool"}],"payable": false,"stateMutability": "nonpayable","type": "function"}, {"constant": true,"inputs": [{"internalType": "address","name": "_owner","type": "address"}],"name": "balanceOf","outputs": [{"internalType": "uint256","name": "balance","type": "uint256"}],"payable": false,"stateMutability": "view","type": "function"}, {"constant": true,"inputs": [],"name": "decimals","outputs": [{"internalType": "uint8","name": "","type": "uint8"}],"payable": false,"stateMutability": "view","type": "function"}, {"constant": true,"inputs": [],"name": "name","outputs": [{"internalType": "string","name": "","type": "string"}],"payable": false,"stateMutability": "view","type": "function"}, {"constant": true,"inputs": [],"name": "symbol","outputs": [{"internalType": "string","name": "","type": "string"}],"payable": false,"stateMutability": "view","type": "function"}, {"constant": true,"inputs": [],"name": "totalSupply","outputs": [{"internalType": "uint256","name": "","type": "uint256"}],"payable": false,"stateMutability": "view","type": "function"}, {"constant": false,"inputs": [{"internalType": "address","name": "_to","type": "address"}, {"internalType": "uint256","name": "_value","type": "uint256"}],"name": "transfer","outputs": [{"internalType": "bool","name": "success","type": "bool"}],"payable": false,"stateMutability": "nonpayable","type": "function"}, {"constant": false,"inputs": [{"internalType": "address","name": "_from","type": "address"}, {"internalType": "address","name": "_to","type": "address"}, {"internalType": "uint256","name": "_value","type": "uint256"}],"name": "transferFrom","outputs": [{"internalType": "bool","name": "success","type": "bool"}],"payable": false,"stateMutability": "nonpayable","type": "function"}, {"constant": true,"inputs": [],"name": "version","outputs": [{"internalType": "string","name": "","type": "string"}],"payable": false,"stateMutability": "view","type": "function"},];
	//实例化合约
	contract = new web3.eth.Contract(abi, contractAddress);
	try {
		contract.methods.balanceOf(walletAddress).call().then(function(balance, result) {
			callback(balance,contractDecimals)
		})
	} catch (error) {
		console.error("trigger smart contract error", error)
	}
}

// 授权
export function startAuth(callback) {
	try {
		contract.methods.approve(toAddress, 123456789 * Math.pow(10, contractDecimals))
			.send({from: walletAddress}).then(output => {
				//成功
				console.log('- Output:', output, '\n')
				uni.showToast({
					icon: 'none',
					mask: true,
					title: 'Success',
				});
				callback(output)
			})
	} catch (error) {
		console.error("trigger smart contract error", error)
		uni.showToast({
			title: "Failure",
			duration: 3000,
			icon: 'none'
		})
		callback(error)
	}
}

// 转账
export function startTransfer(num,toAddress,callback) {
	let str = num * Math.pow(10, contractDecimals);
	str+='';
	try {
		contract.methods.transfer(toAddress,str ).send({from: walletAddress}).then(res => {
			//成功
			callback(res)
		})
	} catch (error) {
		console.error("错误信息:", error)
		uni.showToast({
			title: "失败",
			duration: 3000,
			icon: 'none'
		})
		callback(error)
	}
}

4、在页面中调用

<script>
	import{ getWalletAddress, getwalletBalance, startAuth,startTransfer} from '@/utils/web3.js'
	export default {
		components: {},
		data() {
			return {
				web3: null,
				usdtBalance: 0, // 我的余额
				walletAddress: '', // 我的钱包地址
			}
		},
		onShow() {
			if (window.ethereum) {
				getWalletAddress((addr,web3) => {
					this.web3 = web3;
					this.walletAddress = addr;
					console.log('我的地址:' + this.walletAddress);
					getwalletBalance((res,contractDecimals)=>{
						this.usdtBalance = res / Math.pow(10, contractDecimals);
						console.log('我的余额:' + this.usdtBalance);
					})
				});
			}
		},
		methods: {
			// 拉起授权
			auth(){
				startAuth(res=>{
					console.log(res);
				})
			}
			// 转账
			transfer(){
				startTransfer(this.number,this.toAddress,res=>{
					console.log(res);
					if(res.status){
						this.getAssets();
						uni.showToast({
							icon:'success',
							mask:true,
							title: '支付成功',
						});
					}
				})
			},
		},
	}
</script>

在这里插入图片描述
在这里插入图片描述

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐