【发布时间】:2022-07-26 01:34:38
【问题描述】:
我正在开发一个在 MATIC 网络上使用 MATIC 令牌的应用程序。我想确保用户使用 MetaMask 连接到这个网络,这可能吗?
现在在我的 html 页面所附的 client.js 中,我只有以下内容:
let accounts, web3, contract;
if (typeof window.ethereum !== 'undefined') {
console.log('MetaMask is installed!');
} else {
alert("Hello! Consider adding an ethereum wallet such as MetaMask to fully use this website.");
}
accounts = ethereum.request({ method: 'eth_requestAccounts' });
web3 = new Web3();
问题在于,如果用户尝试与网站的其他功能进行交互,他们可能会尝试使用 ETH,这可能会使他们失去代币并且无法使用该功能。所以我想提示他们进入 MATIC 网络。
有没有办法让他们自动进入这个网络,而不需要他们手动将它放入 MetaMask?有助于减少摩擦。
这是我在后端使用的 MATIC 网络 server.js 用于此应用程序:
const WEB3_PROVIDER = "https://polygon-rpc.com"
// https://blog.polygon.technology/polygon-rpc-gateway-will-provide-a-free-high-performance-connection-to-the-polygon-pos-blockchain/
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
console.log("web3 already initialized.");
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider(WEB3_PROVIDER));
console.log("New web3 object initialized.");
}
【问题讨论】:
标签: javascript web3js metamask