优化切换链和账号的流程

This commit is contained in:
zhl 2023-04-20 10:45:21 +08:00
parent bdbfaf8725
commit 23343ca2d8
2 changed files with 143 additions and 7 deletions

View File

@ -76,6 +76,7 @@ createApp({
wallet: null, wallet: null,
disabled: false, disabled: false,
loading: false, loading: false,
hasRole: false,
loadingMask: false, loadingMask: false,
showCancel: false, showCancel: false,
showConfirm: false, showConfirm: false,
@ -101,6 +102,7 @@ createApp({
console.log(result); console.log(result);
await this.initWallet(); await this.initWallet();
} catch (err) { } catch (err) {
console.log(err);
this.alert("加载数据失败", "danger", true); this.alert("加载数据失败", "danger", true);
} }
this.loading = false; this.loading = false;
@ -136,8 +138,8 @@ createApp({
return new this.web3.eth.Contract(json.abi, address, { from: user }); return new this.web3.eth.Contract(json.abi, address, { from: user });
}, },
async initWallet() { async initWallet() {
let provider = await connectMetaMask(); this.provider = await connectMetaMask();
this.web3 = new Web3(provider); this.web3 = new Web3(this.provider);
let accounts = await this.web3.eth.getAccounts(); let accounts = await this.web3.eth.getAccounts();
if (accounts.length > 0) { if (accounts.length > 0) {
this.account = accounts[0]; this.account = accounts[0];
@ -148,13 +150,14 @@ createApp({
"assets/abis/BEMultiSigWallet.json" "assets/abis/BEMultiSigWallet.json"
); );
this.chainId = await this.web3.eth.getChainId(); this.chainId = await this.web3.eth.getChainId();
this.hasRole = await this.checkRole();
await this.checkChain();
this.subscribeToEvents();
this.walletConnect = true; this.walletConnect = true;
console.log(this.chainId, this.account); console.log(this.chainId, this.account);
await this.refreshData(); await this.refreshData();
}, },
async refreshData() { async refreshData() {
let hasRole = await this.checkRole();
console.log("has role: ", hasRole);
let cando = true; let cando = true;
let canCancel = false; let canCancel = false;
for (let sub of this.subTasks) { for (let sub of this.subTasks) {
@ -200,6 +203,126 @@ createApp({
.call(); .call();
return result; return result;
}, },
checkChain() {
return new Promise((resolve, reject) => {
this.confirmNeededChain((err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
},
async confirmNeededChain(cb) {
const chainId = this.chainId;
if (chainId !== DEFAULT_CHAIN_DATA.id) {
console.log(
chainId + "chain id not match, switch to: ",
DEFAULT_CHAIN_DATA.name
);
await this.switchEthereumChain(cb);
} else {
cb && cb(null, 1);
}
},
async switchEthereumChain(cb) {
let self = this;
let data = DEFAULT_CHAIN_DATA;
let hexChainId = toHexChainId(data.id);
const onChainChange = async function (chainId) {
const chainIdNum = parseInt(chainId);
console.log("chainChanged: ", chainId, chainIdNum);
self.chainId = chainIdNum;
self.provider.removeListener("chainChanged", onChainChange);
await self.confirmNeededChain(cb);
};
self.provider.on("chainChanged", onChainChange);
try {
await self.provider.request({
method: "wallet_addEthereumChain",
params: [
{
chainId: hexChainId,
chainName: data.name,
nativeCurrency: {
name: data.symbol,
symbol: data.symbol,
decimals: data.decimals || 18,
},
blockExplorerUrls: [data.explorerurl],
rpcUrls: [data.rpc],
},
],
});
console.log("add chain success");
} catch (addError) {
console.error("add chain error: ", addError);
self.provider.removeListener("chainChanged", onChainChange);
cb && cb(addError, 0);
}
// try {
// await this.provider.request({
// method: 'wallet_switchEthereumChain',
// params: [{ chainId: hexChainId }],
// })
// console.log('switch chain success')
// } catch (e) {
// console.log('switch chain error: ', e)
// if (e.code === 4902 || e.message.indexOf('Unrecognized chain ID') >= 0) {
// try {
// await this.provider.request({
// method: 'wallet_addEthereumChain',
// params: [
// {
// chainId: hexChainId,
// chainName: data.name,
// nativeCurrency: {
// name: data.symbol,
// symbol: data.symbol,
// decimals: data.decimals || 18,
// },
// blockExplorerUrls: [data.explorerurl],
// rpcUrls: [data.rpc],
// },
// ],
// })
// console.log('add chain success')
// } catch (addError) {
// console.error('add chain error: ', addError)
// }
// }
// }
},
subscribeToEvents() {
this.provider.on("accountsChanged", async (accounts) => {
if (accounts && accounts.length > 0) {
if (this.account !== accounts[0]) {
console.log("account change", this.account, accounts[0]);
this.account = accounts[0];
this.hasRole = await this.checkRole();
}
}
});
// Subscribe to chainId change
this.provider.on("chainChanged", async (chainId) => {
const chainIdNum = parseInt(chainId);
console.log("chainChanged", chainId, chainIdNum);
if (this.chainId !== chainIdNum) {
this.chainId = chainIdNum;
location.reload();
}
});
// Subscribe to session disconnection
this.provider.on("disconnect", (err) => {
console.log("disconnect", err);
location.reload();
});
},
makeBatchRequest(calls, callFrom) { makeBatchRequest(calls, callFrom) {
let batch = new this.web3.BatchRequest(); let batch = new this.web3.BatchRequest();
let promises = calls.map((call) => { let promises = calls.map((call) => {
@ -218,6 +341,10 @@ createApp({
return Promise.all(promises); return Promise.all(promises);
}, },
async confirmTask() { async confirmTask() {
if (!this.hasRole) {
this.alert("没有操作权限", "warning", true);
return;
}
let ids = this.subTasks.map((o) => o.scheduleId); let ids = this.subTasks.map((o) => o.scheduleId);
console.log("confirm task", ids); console.log("confirm task", ids);
this.showLoadingMask("处理上链请求"); this.showLoadingMask("处理上链请求");
@ -235,6 +362,10 @@ createApp({
}, },
async rejectTask() { async rejectTask() {
console.log("reject task"); console.log("reject task");
if (!this.hasRole) {
this.alert("没有操作权限", "warning", true);
return;
}
let ids = this.subTasks.map((o) => o.scheduleId); let ids = this.subTasks.map((o) => o.scheduleId);
this.showLoadingMask("撤销确认信息"); this.showLoadingMask("撤销确认信息");
try { try {

View File

@ -40,15 +40,20 @@
<p>{{task.desc}}</p> <p>{{task.desc}}</p>
<p>本次申请包含<b>{{subTasks.length}}</b>个链操作任务</p> <p>本次申请包含<b>{{subTasks.length}}</b>个链操作任务</p>
</div> </div>
<div class="hstack gap-3 mb-1"> <div class="hstack gap-3 mb-1" v-if="hasRole">
<template v-if="!walletConnect"> <template v-if="!walletConnect">
<button type="button" class="btn btn-info" @click="initWallet">连接钱包</button> <button type="button" class="btn btn-info" @click="initWallet">连接钱包</button>
<div class="vr"></div> <div class="vr"></div>
</template> </template>
<button type="button" class="btn btn-primary" v-if="showConfirm" @click="confirmTask">确认</button> <template v-if="showConfirm">
<div class="vr"></div> <button type="button" class="btn btn-primary" @click="confirmTask">确认</button>
<div class="vr"></div>
</template>
<button type="button" class="btn btn-danger" v-if="showCancel" @click="rejectTask">取消</button> <button type="button" class="btn btn-danger" v-if="showCancel" @click="rejectTask">取消</button>
</div> </div>
<div class="hstack gap-3 mb-1" v-if="!hasRole">
<span class="badge text-bg-danger">没有操作权限<span>
</div>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">