The MetaMask API is attached to the window object if MetaMask is installed.
if (!window.ethereum) throw new Error("Meta Mask is not installed!");
/# You must first request access to the users MetaMask Only do this once #/
try {
const accounts = await window.ethereum.request({ method: "eth_requestAccounts" })
} catch(error) {
if (error.code === 4001) {
// EIP-1193 userRejectedRequest error
console.log("Please connect to MetaMask.");
} else {
console.error(error);
}
return;
}
const [from] = await window.ethereum.request({
method: "eth_accounts",
});
const tx = {
to: "0x"
from,
gas: "300000",
data: "0x"
}
window.ethereum.request({
method: "eth_sendTransaction",
params: [tx],
});