resolve transaction error in matic wallet

This commit is contained in:
raviycoder 2024-07-29 15:10:06 +05:30
parent 806f88ae8a
commit c7c2974c9c
2 changed files with 74 additions and 34 deletions

View File

@ -243,12 +243,16 @@
}; };
function getProvider() { function getProvider() {
// switches provider based on whether the user is using MetaMask or not // switches provider based on whether the user is using MetaMask or not
const maticMainnet = {
chainId: 137, // Hexadecimal representation of 137
name: 'matic',
rpc: 'https://polygon-mainnet.infura.io/v3/6e12fee52bdd48208f0d82fb345bcb3c', // RPC URL for Polygon (Matic)
explorer: 'https://polygonscan.com'
};
if (window.ethereum) { if (window.ethereum) {
return new ethers.providers.Web3Provider(window.ethereum); return new ethers.providers.Web3Provider(window.ethereum);
} else { } else {
return new ethers.providers.JsonRpcProvider( return new ethers.providers.JsonRpcProvider(maticMainnet.rpc, maticMainnet);
"https://polygon-mainnet.infura.io/v3/6e12fee52bdd48208f0d82fb345bcb3c"
);
} }
} }
function connectToMetaMask() { function connectToMetaMask() {
@ -352,20 +356,61 @@
receiver, receiver,
contractAddress, contractAddress,
}) => { }) => {
// Create a wallet using the private key try {
const wallet = new ethers.Wallet(privateKey, getProvider()); // Create a wallet using the private key
// Contract interface const wallet = new ethers.Wallet(privateKey, getProvider());
const tokenContract = new ethers.Contract(
CONTRACT_ADDRESSES[token] || contractAddress, // Contract interface
BEP20ABI, const tokenContract = new ethers.Contract(
wallet CONTRACT_ADDRESSES[token] || contractAddress,
); BEP20ABI,
wallet
const decimals = await tokenContract.decimals(); );
// Convert the amount to the smallest unit of USDC (wei)
const amountWei = ethers.utils.parseUnits(amount.toString(), decimals); // Assuming 6 decimals for USDC // Fetch the correct number of decimals for the token
const decimals = await tokenContract.decimals();
// Call the transfer function on the USDC contract
return tokenContract.transfer(receiver, amountWei); // Convert the amount to the smallest unit of the token
const amountWei = ethers.utils.parseUnits(amount.toString(), decimals);
// Estimate gas limit for the transaction
let gasLimit;
try {
gasLimit = await tokenContract.estimateGas.transfer(receiver, amountWei);
} catch (error) {
console.warn("Gas limit estimation failed, using default gas limit:", error);
gasLimit = ethers.BigNumber.from("60000"); // Default value, adjust as necessary
}
// Get the current gas price and add a buffer to avoid the "replacement fee too low" error
let gasPrice;
try {
gasPrice = await wallet.provider.getGasPrice();
gasPrice = gasPrice.mul(ethers.BigNumber.from(2)); // Increase the gas price to avoid the error
} catch (error) {
console.warn("Gas price fetching failed, using default gas price:", error);
gasPrice = ethers.utils.parseUnits("5", "gwei"); // Default value, adjust as necessary
}
// Check if the wallet has enough balance to cover gas fees
const gasCost = gasPrice.mul(gasLimit);
const balance = await wallet.getBalance();
if (balance.lt(gasCost)) {
throw new Error("Insufficient funds for gas fee");
}
// Call the transfer function on the token contract
const tx = await tokenContract.transfer(receiver, amountWei, {
gasLimit: gasLimit,
gasPrice: gasPrice,
});
await tx.wait(); // Wait for the transaction to be mined
return tx;
} catch (error) {
console.error("Token transfer error:", error);
throw new Error("Failed to transfer token");
}
}); });
})("object" === typeof module ? module.exports : (window.maticOperator = {})); })("object" === typeof module ? module.exports : (window.maticOperator = {}));

View File

@ -127,23 +127,18 @@
name: "Transfer", name: "Transfer",
type: "event", type: "event",
}, },
], ]
CONTRACT_ADDRESSES = { const CONTRACT_ADDRESSES = {
usdc: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", usdc: "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",
usdt: "0xdac17f958d2ee523a2206206994597c13d831ec7", usdt: "0xc2132d05d31c914a87c6611c10748aeb04b58e8f"
}; }
function getProvider() { function getProvider() {
const maticMainnet = { // switches provider based on whether the user is using MetaMask or not
chainId: 137, // Hexadecimal representation of 137 if (window.ethereum) {
name: 'matic', return new ethers.providers.Web3Provider(window.ethereum);
rpc: 'https://rpc-mainnet.maticvigil.com/', // RPC URL for Polygon (Matic) } else {
explorer: 'https://polygonscan.com' return new ethers.providers.JsonRpcProvider(`https://polygon-mainnet.infura.io/v3/804ecc59729248fc9cf5b3713289a321`)
}; }
return window.ethereum
? new ethers.providers.Web3Provider(window.ethereum)
: new ethers.providers.JsonRpcProvider(
maticMainnet.rpc, maticMainnet
);
} }
(maticOperator.getBalance = async (address) => { (maticOperator.getBalance = async (address) => {
try { try {