connectWeb3: async function () {
if (window.ethereum) {
try {
await (window.ethereum as any).request({
method: 'wallet_switchEthereumChain',
params: [{
chainId: Web3.utils.numberToHex(56)
}]
})
} catch (e) {
if ((e as any).code === 4902) {
try {
await (window.ethereum as any).request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: Web3.utils.numberToHex(56),
chainName: 'Binance Smart Chain Mainnet',
nativeCurrency: {
name: 'bnb',
symbol: 'bnb',
decimals: 18
},
rpcUrls: ['https://bsc-dataseed.binance.org'],
blockExplorerUrls: ['https://www.bscscan.com']
}
]
})
} catch (ee) {
}
} else if ((e as any).code === 4001) return
}
}
const func: Function = async function (accounts) {
_this.account = accounts[0];
if (_this.isConnect) {
console.log("Contract Account Changed");
_this.init();
_this.connectWeb3();
}
};
let web3Provider: any = null;
if (window.ethereum) {
(window.ethereum as any).autoRefreshOnNetworkChange = false;
(window.ethereum as any).on("accountsChanged", func);
(window.ethereum as any).on("chainChanged", (chainId1) => {
console.log("Chain Changed");
_this.chainId = chainId1;
func([_this.account]);
});
web3Provider = window.ethereum;
try {
await (window.ethereum as any).enable();
} catch (error) {
console.error("User denied account access");
}
} else if (window.web3) {
web3Provider = window.web3.currentProvider;
} else {
web3Provider = new
Web3.providers.HttpProvider(ChainLink[TargetChainId.toString()]);
}
_this.web3 = new Web3(web3Provider);
_this.web3.eth.getAccounts(function (error, result) {
if (!error) console.log(result);
});
_this.isConnect = true;
_this.account = (window.ethereum as any).selectedAddress || null;
_this.chainId = (window.ethereum as any).networkVersion || null;
if(_this.chainId!=TargetChainId) return;
if (_this.account) {
const time = Math.round(new Date().valueOf() / 1000);
_this.web3.eth.personal.sign("Sign this message to login Game." + time, _this.account)
.then((res) => {
_this.signature = res + "|" + time;
});
_this.connectContract();
}
return _this.account;
}