https://docs.metamask.io/guide/ethereum-provider.html#using-the-provider
This snippet explains how to accomplish the three most common requirements for web3 sites:
- Detect the Ethereum provider (
window.ethereum
) - Detect which Ethereum network the user is connected to
- Get the user’s Ethereum account(s)
/*****************************************/
/* Detect the MetaMask Ethereum provider */
/*****************************************/
import detectEthereumProvider from '@metamask/detect-provider';
// this returns the provider, or null if it wasn't detected
const provider = await detectEthereumProvider();
if (provider) {
startApp(provider); // Initialize your app
} else {
console.log('Please install MetaMask!');
}
function startApp(provider) {
// If the provider returned by detectEthereumProvider is not the same as
// window.ethereum, something is overwriting it, perhaps another wallet.
if (provider !== window.ethereum) {
console.error('Do you have multiple wallets installed?');
}
// Access the decentralized web!
}
/**********************************************************/
/* Handle chain (network) and chainChanged (per EIP-1193) */
/**********************************************************/
const chainId = await ethereum.request({ method: 'eth_chainId' });
handleChainChanged(chainId);
ethereum.on('chainChanged', handleChainChanged);
function handleChainChanged(_chainId) {
// We recommend reloading the page, unless you must do otherwise
window.location.reload();
}
/***********************************************************/
/* Handle user accounts and accountsChanged (per EIP-1193) */
/***********************************************************/
let currentAccount = null;
ethereum
.request({ method: 'eth_accounts' })
.then(handleAccountsChanged)
.catch((err) => {
// Some unexpected error.
// For backwards compatibility reasons, if no accounts are available,
// eth_accounts will return an empty array.
console.error(err);
});
// Note that this event is emitted on page load.
// If the array of accounts is non-empty, you're already
// connected.
ethereum.on('accountsChanged', handleAccountsChanged);
// For now, 'eth_accounts' will continue to always return an array
function handleAccountsChanged(accounts) {
if (accounts.length === 0) {
// MetaMask is locked or the user has not connected any accounts
console.log('Please connect to MetaMask.');
} else if (accounts[0] !== currentAccount) {
currentAccount = accounts[0];
// Do any other work!
}
}
/*********************************************/
/* Access the user's accounts (per EIP-1102) */
/*********************************************/
// You should only attempt to request the user's accounts in response to user
// interaction, such as a button click.
// Otherwise, you popup-spam the user like it's 1999.
// If you fail to retrieve the user's account(s), you should encourage the user
// to initiate the attempt.
document.getElementById('connectButton', connect);
// While you are awaiting the call to eth_requestAccounts, you should disable
// any buttons the user can click to initiate the request.
// MetaMask will reject any additional requests while the first is still
// pending.
function connect() {
ethereum
.request({ method: 'eth_requestAccounts' })
.then(handleAccountsChanged)
.catch((err) => {
if (err.code === 4001) {
// EIP-1193 userRejectedRequest error
// If this happens, the user rejected the connection request.
console.log('Please connect to MetaMask.');
} else {
console.error(err);
}
});
}




.
.
참고자료)
ethereum.request() 를 통해 호출할수 있는 rpc api
https://docs.metamask.io/guide/rpc-api.html#rpc-api
.
window.ethereum.selectedAddress 값이 null이면 사용자가 metamask wallet을 잠군 상태이거나 permission을 허락하지 않은 상태이다.
.
.
window.ethereum.chainId는 사용자가 wallet을 잠구던 아니던 상관없이 값이 있다.
사용자가 metamask wallet에서 네트워크를 polygon으로 하면 chainId 값은 137이되고 ethereum으로 설정하면 1 값을 가진다. 또 mumbai로 설정하면 80001 값을 가진다.
사용자가 wallet을 잠군 상태에서는 최근 마지막 사용한 network chain id 값을 가지고 있게 된다.

.
.
이것을 참조해서 사용자가 metamask wallet을 설치하고 있는지 확인하고 로그인하게 하는 과정을 처리했는데 약간 오래된 코드가 포함되어있다.
window.web3 = new Web3(window.ethereum);
const account = web3.eth.accounts;
이부분의 web3는 deprecated될 부분이고 ethereum을 이용해야한다.
공식문서 해결방법 https://docs.metamask.io/guide/provider-migration.html#replacing-window-web3