Develop Ethereum dapp using web3.js in vue

How to use Ethereum smart contract methods on the front end

What we are talking about here is the interaction between the front end and MetaMask

The official documents involved in the article
web3.js 1.0 Chinese manual
MetaMask official document

web3.js file
link: https://pan.baidu.com/s/1_mPT-ZcQ9GU_U1CVhBKpLA
extraction code: cbey

#### 一、唤起MetaMask钱包进行登录
创建web3.js文件
```javascript
//web3.js
// 智能合约地址
const contractAddress = '.....'
// 智能合约ABI
const contractABI=[]
var contract=null;
/**
 * 初始化
 * @param {Object} callback 返回账户地址
 */
function Init(callback){
	//判断用户是否安装MetaMask钱包插件
	if (typeof window.ethereum === "undefined") {
		//没安装MetaMask钱包进行弹框提示
		alert("Looks like you need a Dapp browser to get started.");
		alert("Consider installing MetaMask!");
	} else {
		//如果用户安装了MetaMask,你可以要求他们授权应用登录并获取其账号
		ethereum.enable()
		.catch(function (reason) {
			//如果用户拒绝了登录请求
			if (reason === "User rejected provider access") {
				// 用户拒绝登录后执行语句;
			} else {
				// 本不该执行到这里,但是真到这里了,说明发生了意外
				alert("There was an issue signing you in.");
			}
			}).then(function (accounts) {
				//如果用户同意了登录请求,你就可以拿到用户的账号
				var currentProvider = web3.currentProvider;
				var Web3 = web3js.getWeb3();
				web3 = new Web3();
				web3.setProvider(currentProvider);
				contract = new web3.eth.Contract(contractABI, contractAddress);
				// console.log('地址列表', accounts)
				//这里返回用户钱包地址
				callback(accounts[0]);
			});
	}
}
//导出相应的方法
export default {
	Init,
}

Then import it on the page you need to use

import NCWeb3 from "@/web3";
NCWeb3.Init(addr=>{
    
    
	//得到相应的钱包地址
	console.log(addr)
})

2. Call the methods in the smart contract (divided into two types, those that require gas fees and those that do not)

It is relatively simple to not require gas fees. Call it directly through contract.methods.Smart contract method (required parameters).call()

// 投资授权
function Approve(addr,value, callback) {
    
    
	contract.methods
		//智能合约方法(所需的参数)
		.approve(addr,value)
		.call()
		.then((res) => {
    
    
			console.log('投资授权成功', res)
			callback(res);
		})
		.catch((err) => {
    
    
			alert('投资授权失败,稍后再试:', err)
		});
}
//导出相应的方法
export default {
    
    
	Init,
	Approve,
}

It is a little more troublesome to require gas fees. First call the web3.eth.estimateGas() method to estimate the gas usage of the transaction. Then use the web3.eth.getGasPrice() method to get the current gas price, and finally use the ethereum.sendAsync method to send ether and call the smart contract:

// 投资
function join(account, addr,val, callback) {
    
    
	//要支付的ETH,十六进制
	let value = "0x0";
	//智能合约的参数也需要进行转换
	//web3.utils.padLeft左侧补0补齐到指定长度的字符串
	//参数数字转换
	val = web3.utils.toHex(val).substring(2);
	val = web3.utils.padLeft(val, 64);
	//参数地址转换
	addr=web3.utils.padLeft(addr, 64).substring(2)
	//智能合约方法,获取方式看下面
	let fun="0x095ea7b3"
	let data = fun + addr + val;
	sendTransfer(account, data, value, callback, errorCallBack);
}
/**
 * 发送交易
 * @param {Object} account 用户地址
 * @param {Object} data 数据
 * @param {Object} value 转账金额
 * @param {Object} callback 返回hash
 * @param {Object} errorCallBack 返回的错误
 */
function sendTransfer(account, data, value, callback, errorCallBack) {
    
    
	// estimateGas获取交易的 gas 用量
	const params = {
    
    
		from: account,
		to: contractAddress,
		data: data,
		value: value,
 	 };
	web3.eth.estimateGas(params, function (error1, gaslimit) {
    
    
		if (error1) {
    
    
			errorCallBack(error1);
		} else {
    
    
			// gasprice获取当前gas价格
			web3.eth.getGasPrice(function (error2, gasPrice) {
    
    
				if (error2) {
    
    
					errorCallBack(error2);
				} else {
    
    
					gaslimit -= -10000;
					let params = [
						{
    
    
							gasPrice: gasPrice,
							gasLimit: gaslimit,
							from: account,
							to: contractAddress,
							data: data,
							value: value,
						},
					];
					//ethereum.sendAsync方法发送以太币、调用智能合约:
					ethereum.sendAsync(
						{
    
    
							method: "eth_sendTransaction",
							params: params,
							from: account,
						},
						function (error, hash) {
    
    
							if (error) {
    
    
								// alert(error.message);
								errorCallBack(error.message);
							} else {
    
    
								callback(hash);
							}
						}
		           );
		           //监听MetaMask的事件
		           ethereum.on('accountsChanged', function (accounts) {
    
    
		             console.log(accounts[0])
		           })
				}
			});
		}
	});
}
//导出相应的方法
export default {
    
    
	Init,
	Approve,
	join,
}

Obtain the hexadecimal format of the smart contract method
Insert image description here
and then introduce it on the page where it is needed. However, one thing to note is that the contract method cannot be called until initialization is completed.

import NCWeb3 from "@/web3";
NCWeb3.Init(addr=>{
    
    
	//得到相应的钱包地址
	console.log(addr)
	NCWeb3.Approve(addr,value, res=>{
    
    
		console.log('Approve方法返回的数据',res)
	})
	NCWeb3.join(account, addr,val, res=>{
    
    
		//由于join方法存在交易,所以这里会返回交易哈希值
		console.log('join方法返回的数据',res)
	})
})

The method that requires postage has a transaction and needs to be packaged and confirmed on the chain. You can monitor the execution of this method through the web3.eth.getTransactionReceipt('transaction hash value') method. If the transaction is in the pending state, null is returned, otherwise an object is returned. If the status attribute is true, it succeeds, otherwise it fails.

Finally, if reading this is useful to you, please click to collect and follow. Thank you for your support. If you have any questions, you can leave a comment.

Guess you like

Origin blog.csdn.net/qingshui_zhuo/article/details/112978150