resolve matic balance check page

This commit is contained in:
raviycoder 2024-07-19 21:23:28 +05:30
parent 4376190cdb
commit 0d7bdaffd9
4 changed files with 407 additions and 399 deletions

4
css/main.min.css vendored
View File

@ -812,13 +812,13 @@ aside h4 {
display: grid;
gap: 0.5rem;
}
#bsc_balance_wrapper {
#matic_balance_wrapper {
background-color: rgba(var(--text-color), 0.06);
padding: max(1rem, 1.5vw);
border-radius: 0.5rem;
width: 100%;
}
#bsc_balance_wrapper li:not(:last-of-type) {
#matic_balance_wrapper li:not(:last-of-type) {
border-bottom: solid thin rgba(var(--text-color), 0.3);
padding-bottom: 0.5rem;
}

View File

@ -254,8 +254,8 @@
<div class="grid gap-0-5">
<h4>Did you forget your Matic Address?</h4>
<p>
If you have your MATIC/BTC/FLO Private Key, enter it here and recover your
Matic Address.
If you have your MATIC/BTC/FLO Private Key, enter it here and
recover your Matic Address.
</p>
</div>
<sm-form>
@ -342,12 +342,16 @@
<script src="scripts/tap_combined.js" type="text/javascript"></script>
<script src="scripts/keccak.js" type="text/javascript"></script>
<script src="scripts/floEthereum.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/@alch/alchemy-sdk@1.2.0/dist/index.cjs.min.js"></script>
<script src="scripts/compactIDB.js" type="text/javascript"></script>
<script
src="https://cdn.ethers.io/lib/ethers-5.6.umd.min.js"
type="text/javascript"
></script>
<script src="scripts/maticOperator.js" type="text/javascript"></script>
<script
src="scripts/ethOperator_polygon.js"
type="text/javascript"
></script>
<script>
const uiGlobals = {};
const { html, svg, render: renderElem } = uhtml;
@ -638,7 +642,7 @@
window.smCompConfig = {
"sm-input": [
{
selector: "[data-MATIC-address]",
selector: "[data-matic-address]",
customValidation: (value) => {
if (!value)
return {
@ -646,7 +650,7 @@
errorText: "Please enter a Matic address",
};
return {
isValid: MATICOperator.isValidAddress(value),
isValid: maticOperator.isValidAddress(value),
errorText: `Invalid address.<br> It usually starts with "0x"`,
};
},
@ -758,9 +762,7 @@
.then((chainId) => {
window.currentChainId = chainId;
if (chainId !== "0x38") {
renderError(
"Please switch MetaMask to Matic Wallet Mainnet"
);
renderError("Please switch MetaMask to Matic Wallet Mainnet");
} else {
router.routeTo(location.hash);
}
@ -1234,9 +1236,7 @@
<div class="flex space-between align-center">
<div class="flex flex-direction-column gap-0-5">
<h4>Sender</h4>
<p>
Amount will be deducted from equivalent Matic address
</p>
<p>Amount will be deducted from equivalent Matic address</p>
</div>
<button
id="check_balance_button"
@ -1327,7 +1327,7 @@
<sm-input
class="receiver-address"
placeholder="Receiver's Matic address"
data-MATIC-address
data-matic-address
animate
required
></sm-input>
@ -1343,7 +1343,25 @@
required
>
<div class="asset-symbol flex" slot="icon">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 1024 1024" id="polygon-token"><circle cx="512" cy="512" r="512" fill="#8247E5"></circle><path fill="#fff" d="M681.469 402.456C669.189 395.312 653.224 395.312 639.716 402.456L543.928 457.228L478.842 492.949L383.055 547.721C370.774 554.865 354.81 554.865 341.301 547.721L265.162 504.856C252.882 497.712 244.286 484.614 244.286 470.325V385.786C244.286 371.498 251.654 358.4 265.162 351.256L340.073 309.581C352.353 302.437 368.318 302.437 381.827 309.581L456.737 351.256C469.018 358.4 477.614 371.498 477.614 385.786V440.558L542.7 403.646V348.874C542.7 334.586 535.332 321.488 521.824 314.344L383.055 235.758C370.774 228.614 354.81 228.614 341.301 235.758L200.076 314.344C186.567 321.488 179.199 334.586 179.199 348.874V507.237C179.199 521.525 186.567 534.623 200.076 541.767L341.301 620.353C353.582 627.498 369.546 627.498 383.055 620.353L478.842 566.772L543.928 529.86L639.716 476.279C651.996 469.135 667.961 469.135 681.469 476.279L756.38 517.953C768.66 525.098 777.257 538.195 777.257 552.484V637.023C777.257 651.312 769.888 664.409 756.38 671.553L681.469 714.419C669.189 721.563 653.224 721.563 639.716 714.419L564.805 672.744C552.525 665.6 543.928 652.502 543.928 638.214V583.442L478.842 620.353V675.125C478.842 689.414 486.21 702.512 499.719 709.656L640.944 788.242C653.224 795.386 669.189 795.386 682.697 788.242L823.922 709.656C836.203 702.512 844.799 689.414 844.799 675.125V516.763C844.799 502.474 837.431 489.377 823.922 482.232L681.469 402.456Z"></path></svg>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
fill="none"
viewBox="0 0 1024 1024"
id="polygon-token"
>
<circle
cx="512"
cy="512"
r="512"
fill="#8247E5"
></circle>
<path
fill="#fff"
d="M681.469 402.456C669.189 395.312 653.224 395.312 639.716 402.456L543.928 457.228L478.842 492.949L383.055 547.721C370.774 554.865 354.81 554.865 341.301 547.721L265.162 504.856C252.882 497.712 244.286 484.614 244.286 470.325V385.786C244.286 371.498 251.654 358.4 265.162 351.256L340.073 309.581C352.353 302.437 368.318 302.437 381.827 309.581L456.737 351.256C469.018 358.4 477.614 371.498 477.614 385.786V440.558L542.7 403.646V348.874C542.7 334.586 535.332 321.488 521.824 314.344L383.055 235.758C370.774 228.614 354.81 228.614 341.301 235.758L200.076 314.344C186.567 321.488 179.199 334.586 179.199 348.874V507.237C179.199 521.525 186.567 534.623 200.076 541.767L341.301 620.353C353.582 627.498 369.546 627.498 383.055 620.353L478.842 566.772L543.928 529.86L639.716 476.279C651.996 469.135 667.961 469.135 681.469 476.279L756.38 517.953C768.66 525.098 777.257 538.195 777.257 552.484V637.023C777.257 651.312 769.888 664.409 756.38 671.553L681.469 714.419C669.189 721.563 653.224 721.563 639.716 714.419L564.805 672.744C552.525 665.6 543.928 652.502 543.928 638.214V583.442L478.842 620.353V675.125C478.842 689.414 486.21 702.512 499.719 709.656L640.944 788.242C653.224 795.386 669.189 795.386 682.697 788.242L823.922 709.656C836.203 702.512 844.799 689.414 844.799 675.125V516.763C844.799 502.474 837.431 489.377 823.922 482.232L681.469 402.456Z"
></path>
</svg>
</div>
</sm-input>
<sm-chips
@ -1692,7 +1710,8 @@
function generateNewID() {
const { floID, privKey } = floCrypto.generateNewID();
const ethPrivateKey = coinjs.wif2privkey(privKey).privkey;
const maticAddress = floEthereum.ethAddressFromPrivateKey(ethPrivateKey);
const maticAddress =
floEthereum.ethAddressFromPrivateKey(ethPrivateKey);
const btcPrivKey = btcOperator.convert.wif(privKey);
const btcAddr = btcOperator.bech32Address(btcPrivKey);
renderElem(
@ -1738,9 +1757,9 @@
let maticPrivateKey = getRef("retrieve_btc_addr_field").value.trim();
getRef("recovered_btc_addr_wrapper").classList.remove("hidden");
getRef("recovered_btc_addr").value =
maticPrivateKey.startsWith("R") ||
maticPrivateKey.startsWith("L") ||
maticPrivateKey.startsWith("K")
maticPrivateKey.startsWith("R") ||
maticPrivateKey.startsWith("L") ||
maticPrivateKey.startsWith("K")
? floEthereum.ethAddressFromPrivateKey(
coinjs.wif2privkey(maticPrivateKey).privkey
)

View File

@ -0,0 +1,369 @@
(function (EXPORTS) {
//maticOperator v1.0.2
/* ETH Crypto and API Operator */
if (!window.ethers) return console.error("ethers.js not found");
const maticOperator = EXPORTS;
const isValidAddress = (maticOperator.isValidAddress = (address) => {
try {
// Check if the address is a valid checksum address
const isValidChecksum = ethers.utils.isAddress(address);
// Check if the address is a valid non-checksum address
const isValidNonChecksum =
ethers.utils.getAddress(address) === address.toLowerCase();
return isValidChecksum || isValidNonChecksum;
} catch (error) {
return false;
}
});
const BEP20ABI = [
{
constant: true,
inputs: [],
name: "name",
outputs: [
{
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
name: "_spender",
type: "address",
},
{
name: "_value",
type: "uint256",
},
],
name: "approve",
outputs: [
{
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "totalSupply",
outputs: [
{
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
name: "_from",
type: "address",
},
{
name: "_to",
type: "address",
},
{
name: "_value",
type: "uint256",
},
],
name: "transferFrom",
outputs: [
{
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "decimals",
outputs: [
{
name: "",
type: "uint8",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [
{
name: "_owner",
type: "address",
},
],
name: "balanceOf",
outputs: [
{
name: "balance",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "symbol",
outputs: [
{
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
name: "_to",
type: "address",
},
{
name: "_value",
type: "uint256",
},
],
name: "transfer",
outputs: [
{
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [
{
name: "_owner",
type: "address",
},
{
name: "_spender",
type: "address",
},
],
name: "allowance",
outputs: [
{
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
payable: true,
stateMutability: "payable",
type: "fallback",
},
{
anonymous: false,
inputs: [
{
indexed: true,
name: "owner",
type: "address",
},
{
indexed: true,
name: "spender",
type: "address",
},
{
indexed: false,
name: "value",
type: "uint256",
},
],
name: "Approval",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
name: "from",
type: "address",
},
{
indexed: true,
name: "to",
type: "address",
},
{
indexed: false,
name: "value",
type: "uint256",
},
],
name: "Transfer",
type: "event",
},
];
const CONTRACT_ADDRESSES = {
usdc: "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",
usdt: "0xc2132d05d31c914a87c6611c10748aeb04b58e8f",
};
function getProvider() {
// switches provider based on whether the user is using MetaMask or not
if (window.ethereum) {
return new ethers.providers.Web3Provider(window.ethereum);
} else {
return new ethers.providers.JsonRpcProvider(
"https://polygon-mainnet.infura.io/v3/6e12fee52bdd48208f0d82fb345bcb3c"
);
}
}
function connectToMetaMask() {
return new Promise((resolve, reject) => {
// if (typeof window.ethereum === "undefined")
// return reject("MetaMask not installed");
return resolve(true);
ethereum
.request({ method: "eth_requestAccounts" })
.then((accounts) => {
console.log("Connected to MetaMask");
return resolve(accounts);
})
.catch((err) => {
console.log(err);
return reject(err);
});
});
}
// connectToMetaMask();
const getBalance = (maticOperator.getBalance = async (address) => {
try {
if (!address || !isValidAddress(address))
return new Error("Invalid address");
// Get the balance
const provider = getProvider();
const balanceWei = await provider.getBalance(address);
const balanceEth = parseFloat(ethers.utils.formatEther(balanceWei));
return balanceEth;
} catch (error) {
console.error("Error:", error.message);
return error;
}
});
const getTokenBalance = (maticOperator.getTokenBalance = async (
address,
token,
{ contractAddress } = {}
) => {
try {
// if (!window.ethereum.isConnected()) {
// await connectToMetaMask();
// }
if (!token)
return new Error("Token not specified");
if (!CONTRACT_ADDRESSES[token] && contractAddress)
return new Error('Contract address of token not available')
const usdcContract = new ethers.Contract(CONTRACT_ADDRESSES[token] || contractAddress, BEP20ABI, getProvider());
let balance = await usdcContract.balanceOf(address);
balance = parseFloat(ethers.utils.formatUnits(balance, 6)); // Assuming 6 decimals
return balance;
} catch (e) {
console.error(e);
}
});
const estimateGas = (maticOperator.estimateGas = async ({
privateKey,
receiver,
amount,
}) => {
try {
const provider = getProvider();
const signer = new ethers.Wallet(privateKey, provider);
return provider.estimateGas({
from: signer.address,
to: receiver,
value: ethers.utils.parseUnits(amount, "ether"),
});
} catch (e) {
throw new Error(e);
}
});
const sendTransaction = (maticOperator.sendTransaction = async ({
privateKey,
receiver,
amount,
}) => {
try {
const provider = getProvider();
const signer = new ethers.Wallet(privateKey, provider);
const limit = await estimateGas({ privateKey, receiver, amount });
// Creating and sending the transaction object
return signer.sendTransaction({
to: receiver,
value: ethers.utils.parseUnits(amount, "ether"),
gasLimit: limit,
nonce: signer.getTransactionCount(),
maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei"),
});
} catch (e) {
throw new Error(e);
}
});
const sendToken = (maticOperator.sendToken = async ({
token,
privateKey,
amount,
receiver,
contractAddress,
}) => {
// Create a wallet using the private key
const wallet = new ethers.Wallet(privateKey, getProvider());
// Contract interface
const tokenContract = new ethers.Contract(
CONTRACT_ADDRESSES[token] || contractAddress,
BEP20ABI,
wallet
);
// Convert the amount to the smallest unit of USDC (wei)
const amountWei = ethers.utils.parseUnits(amount.toString(), 6); // Assuming 6 decimals for USDC
// Call the transfer function on the USDC contract
return tokenContract.transfer(receiver, amountWei);
});
})("object" === typeof module ? module.exports : (window.maticOperator = {}));

View File

@ -1,380 +0,0 @@
(function (EXPORTS) { //maticOperator v1.0.2
/* ETH Crypto and API Operator */
if (!window.ethers)
return console.error('ethers.js not found')
const maticOperator = EXPORTS;
const isValidAddress = maticOperator.isValidAddress = (address) => {
try {
// Check if the address is a valid checksum address
const isValidChecksum = ethers.utils.isAddress(address);
// Check if the address is a valid non-checksum address
const isValidNonChecksum = ethers.utils.getAddress(address) === address.toLowerCase();
return isValidChecksum || isValidNonChecksum;
} catch (error) {
return false;
}
}
const BEP20ABI = [
{
"constant": true,
"inputs": [],
"name": "name",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [
{
"name": "",
"type": "uint8"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "balance",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "symbol",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"payable": true,
"stateMutability": "payable",
"type": "fallback"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "owner",
"type": "address"
},
{
"indexed": true,
"name": "spender",
"type": "address"
},
{
"indexed": false,
"name": "value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "address"
},
{
"indexed": true,
"name": "to",
"type": "address"
},
{
"indexed": false,
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
}
]
const CONTRACT_ADDRESSES = {
usdc: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",
usdt: "0x3813e82e6f7098b9583FC0F33a962D02018B6803"
};
function getProvider() {
// Configuration for the Polygon (Matic) network
const maticMainnet = {
chainId: 137, // Hexadecimal representation of 137
name: 'matic',
rpc: 'https://rpc-mainnet.maticvigil.com/', // RPC URL for Polygon (Matic)
explorer: 'https://polygonscan.com'
};
if (window.ethereum) {
const provider = new ethers.providers.Web3Provider(window.ethereum);
// Optional: Switch network to Matic if not already connected
provider.send("wallet_addEthereumChain", [{
chainId: maticMainnet.chainId,
chainName: maticMainnet.name,
rpcUrls: [maticMainnet.rpc],
blockExplorerUrls: [maticMainnet.explorer],
nativeCurrency: {
name: "MATIC",
symbol: "MATIC",
decimals: 18
}
}]).catch(console.error);
return provider;
} else {
return new ethers.providers.JsonRpcProvider(maticMainnet.rpc, maticMainnet);
}
}
function connectToMetaMask() {
return new Promise((resolve, reject) => {
// if (typeof window.ethereum === "undefined")
// return reject("MetaMask not installed");
return resolve(true)
ethereum
.request({ method: 'eth_requestAccounts' })
.then((accounts) => {
console.log('Connected to MetaMask')
return resolve(accounts)
})
.catch((err) => {
console.log(err)
return reject(err)
})
})
}
// connectToMetaMask();
const getBalance = maticOperator.getBalance = async (address) => {
try {
if (!address || !isValidAddress(address))
return new Error('Invalid address');
// Get the balance
const provider = getProvider();
const balanceWei = await provider.getBalance(address);
const balanceEth = parseFloat(ethers.utils.formatEther(balanceWei));
return balanceEth;
} catch (error) {
console.error('Error:', error.message);
return error;
}
}
const getTokenBalance = maticOperator.getTokenBalance = async (address, token, { contractAddress } = {}) => {
try {
if (!address) {
throw new Error("Address not specified");
}
if (!token) {
throw new Error("Token not specified");
}
if (!CONTRACT_ADDRESSES[token] && !contractAddress) {
throw new Error("Contract address of token not available");
}
const provider = getProvider(); // Ensure this returns a valid provider for matic
const contract = new ethers.Contract(CONTRACT_ADDRESSES[token] || contractAddress, BEP20ABI, provider);
let balance = await contract.balanceOf(address);
// Assuming 18 decimals for most tokens like USDT and USDC
const decimals = 18;
balance = parseFloat(ethers.utils.formatUnits(balance, decimals));
// Format the balance to 2 decimal places for display
balance = balance.toFixed(2);
return balance;
} catch (e) {
console.error("Error getting token balance:", e.message);
throw new Error("Failed to get token balance");
}
}
const estimateGas = maticOperator.estimateGas = async ({ privateKey, receiver, amount }) => {
try {
const provider = getProvider();
const signer = new ethers.Wallet(privateKey, provider);
return provider.estimateGas({
from: signer.address,
to: receiver,
value: ethers.utils.parseUnits(amount, "ether"),
});
} catch (e) {
throw new Error(e)
}
}
const sendTransaction = maticOperator.sendTransaction = async ({ privateKey, receiver, amount }) => {
try {
const provider = getProvider();
const signer = new ethers.Wallet(privateKey, provider);
const limit = await estimateGas({ privateKey, receiver, amount })
// Creating and sending the transaction object
return signer.sendTransaction({
to: receiver,
value: ethers.utils.parseUnits(amount, "ether"),
gasLimit: limit,
nonce: signer.getTransactionCount(),
maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei"),
})
} catch (e) {
throw new Error(e)
}
}
const sendToken = maticOperator.sendToken = async ({ token, privateKey, amount, receiver, contractAddress }) => {
// Create a wallet using the private key
const wallet = new ethers.Wallet(privateKey, getProvider());
// Contract interface
const tokenContract = new ethers.Contract(CONTRACT_ADDRESSES[token] || contractAddress, BEP20ABI, wallet);
// Convert the amount to the smallest unit of USDC (wei)
const amountWei = ethers.utils.parseUnits(amount.toString(), 6); // Assuming 6 decimals for USDC
// Call the transfer function on the USDC contract
return tokenContract.transfer(receiver, amountWei)
}
})('object' === typeof module ? module.exports : window.maticOperator = {});