From c1a1f7af0c3db2a514879e1fa2cf896ea1c8d1d2 Mon Sep 17 00:00:00 2001 From: sairaj mote Date: Wed, 15 Nov 2023 03:16:35 +0530 Subject: [PATCH] Added ether balance checking --- index.html | 23 ++++++++++++++++------- scripts/ethOperator.js | 5 +++-- scripts/ethOperator.min.js | 2 +- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/index.html b/index.html index a62357d..f3c97a6 100644 --- a/index.html +++ b/index.html @@ -571,7 +571,6 @@ router.addRoute('balance', renderHome) function renderHome(state) { getRef('page_container').dataset.page = 'home' - const isConnectedToEthMainnet = window.currentChainId && window.currentChainId === '0x1' renderElem(getRef('page_container'), html`

- Check USDC/USDT balance + Check Ether, USDC and USDT balance

@@ -614,6 +613,10 @@

Balance

    +
  • +

    Ether

    + 0 +
  • USDC

    0 @@ -627,8 +630,8 @@
`) - if (window.ethereum && !isConnectedToEthMainnet) { - renderError('Please install MetaMask browser extension to use this app') + if (window.ethereum && !(window.currentChainId && window.currentChainId === '0x1')) { + renderError('Please switch MetaMask to Ethereum Mainnet') } renderSearchedAddressList() } @@ -705,10 +708,12 @@ if (!ethAddress) return buttonLoader('check_balance_button', true) Promise.all([ + ethOperator.getBalance(ethAddress), ethOperator.getTokenBalance({ address: ethAddress, token: 'usdc' }), ethOperator.getTokenBalance({ address: ethAddress, token: 'usdt' }) ]) - .then(([usdcBalance, usdtBalance]) => { + .then(([etherBalance, usdcBalance, usdtBalance]) => { + console.log(etherBalance, usdcBalance, usdtBalance) compactIDB.readData('contacts', floAddress).then(result => { if (result) return compactIDB.addData('contacts', { @@ -721,8 +726,9 @@ }) getRef('eth_address').value = ethAddress getRef('flo_address').value = floAddress - getRef('usdc_balance').textContent = `${ethers.utils.formatUnits(usdcBalance, 6)} USDC` - getRef('usdt_balance').textContent = `${ethers.utils.formatUnits(usdtBalance, 6)} USDT` + getRef('ether_balance').textContent = `${etherBalance} ETH` + getRef('usdc_balance').textContent = `${usdcBalance} USDC` + getRef('usdt_balance').textContent = `${usdtBalance} USDT` getRef('eth_balance_wrapper').classList.remove('hidden') getRef('eth_balance_wrapper').animate([ { @@ -812,6 +818,9 @@ `) + if (window.ethereum && !(window.currentChainId && window.currentChainId === '0x1')) { + renderError('Please switch MetaMask to Ethereum Mainnet') + } }) function togglePrivateKeyVisibility(input) { const target = input.closest('sm-input') diff --git a/scripts/ethOperator.js b/scripts/ethOperator.js index 8b80117..0409dcf 100644 --- a/scripts/ethOperator.js +++ b/scripts/ethOperator.js @@ -1,4 +1,4 @@ -(function (EXPORTS) { //ethOperator v0.0.2 +(function (EXPORTS) { //ethOperator v1.0.2 /* ETH Crypto and API Operator */ if (!window.ethers) return console.error('ethers.js not found') @@ -290,7 +290,8 @@ if (!CONTRACT_ADDRESSES[token] && contractAddress) return new Error('Contract address of token not available') const usdcContract = new ethers.Contract(CONTRACT_ADDRESSES['usdc'] || contractAddress, ERC20ABI, getProvider()); - const balance = await usdcContract.balanceOf(address); + let balance = await usdcContract.balanceOf(address); + balance = ethers.utils.formatUnits(balance, 6); // Assuming 6 decimals return balance; } catch (e) { console.error(e); diff --git a/scripts/ethOperator.min.js b/scripts/ethOperator.min.js index 0204c2e..e161cc7 100644 --- a/scripts/ethOperator.min.js +++ b/scripts/ethOperator.min.js @@ -1 +1 @@ -!function(EXPORTS){if(!window.ethers)return console.error("ethers.js not found");const ethOperator=EXPORTS,isValidAddress=ethOperator.isValidAddress=address=>{try{const isValidChecksum=ethers.utils.isAddress(address),isValidNonChecksum=ethers.utils.getAddress(address)===address.toLowerCase();return isValidChecksum||isValidNonChecksum}catch(error){return!1}},ERC20ABI=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],CONTRACT_ADDRESSES={usdc:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",usdt:"0xdac17f958d2ee523a2206206994597c13d831ec7"};function getProvider(){return window.ethereum?new ethers.providers.Web3Provider(window.ethereum):new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/6e12fee52bdd48208f0d82fb345bcb3c")}ethOperator.getBalance=async address=>{try{if(!address||!isValidAddress(address))return new Error("Invalid address");const provider=getProvider(),balanceWei=await provider.getBalance(address);return ethers.utils.formatEther(balanceWei)}catch(error){return console.error("Error:",error.message),error}},ethOperator.getTokenBalance=async({address:address,token:token,contractAddress:contractAddress})=>{try{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.usdc||contractAddress,ERC20ABI,getProvider());return await usdcContract.balanceOf(address)}catch(e){console.error(e)}},ethOperator.sendTransaction=async({privateKey:privateKey,receiver:receiver,amount:amount})=>{const provider=getProvider(),signer=new ethers.Wallet(privateKey,provider),limit=provider.estimateGas({from:signer.address,to:receiver,value:ethers.utils.parseUnits(amount,"ether")}),tx=await signer.sendTransaction({to:receiver,value:ethers.utils.parseUnits(amount,"ether"),gasLimit:limit,nonce:signer.getTransactionCount(),maxPriorityFeePerGas:ethers.utils.parseUnits("2","gwei")});return{tx:tx,hash:tx.hash}},ethOperator.sendToken=async({token:token,privateKey:privateKey,amount:amount,receiver:receiver,contractAddress:contractAddress})=>{try{const wallet=new ethers.Wallet(privateKey,getProvider()),tokenContract=new ethers.Contract(CONTRACT_ADDRESSES[token]||contractAddress,ERC20ABI,wallet),amountWei=ethers.utils.parseUnits(amount.toString(),6),tx=await tokenContract.transfer(receiver,amountWei);return{tx:tx,hash:tx.hash}}catch(error){console.error("Error:",error.message)}}}("object"==typeof module?module.exports:window.ethOperator={}); \ No newline at end of file +!function(EXPORTS){if(!window.ethers)return console.error("ethers.js not found");const ethOperator=EXPORTS,isValidAddress=ethOperator.isValidAddress=address=>{try{const isValidChecksum=ethers.utils.isAddress(address),isValidNonChecksum=ethers.utils.getAddress(address)===address.toLowerCase();return isValidChecksum||isValidNonChecksum}catch(error){return!1}},ERC20ABI=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],CONTRACT_ADDRESSES={usdc:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",usdt:"0xdac17f958d2ee523a2206206994597c13d831ec7"};function getProvider(){return window.ethereum?new ethers.providers.Web3Provider(window.ethereum):new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/6e12fee52bdd48208f0d82fb345bcb3c")}ethOperator.getBalance=async address=>{try{if(!address||!isValidAddress(address))return new Error("Invalid address");const provider=getProvider(),balanceWei=await provider.getBalance(address);return ethers.utils.formatEther(balanceWei)}catch(error){return console.error("Error:",error.message),error}},ethOperator.getTokenBalance=async({address:address,token:token,contractAddress:contractAddress})=>{try{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.usdc||contractAddress,ERC20ABI,getProvider());let balance=await usdcContract.balanceOf(address);return balance=ethers.utils.formatUnits(balance,6),balance}catch(e){console.error(e)}},ethOperator.sendTransaction=async({privateKey:privateKey,receiver:receiver,amount:amount})=>{const provider=getProvider(),signer=new ethers.Wallet(privateKey,provider),limit=provider.estimateGas({from:signer.address,to:receiver,value:ethers.utils.parseUnits(amount,"ether")}),tx=await signer.sendTransaction({to:receiver,value:ethers.utils.parseUnits(amount,"ether"),gasLimit:limit,nonce:signer.getTransactionCount(),maxPriorityFeePerGas:ethers.utils.parseUnits("2","gwei")});return{tx:tx,hash:tx.hash}},ethOperator.sendToken=async({token:token,privateKey:privateKey,amount:amount,receiver:receiver,contractAddress:contractAddress})=>{try{const wallet=new ethers.Wallet(privateKey,getProvider()),tokenContract=new ethers.Contract(CONTRACT_ADDRESSES[token]||contractAddress,ERC20ABI,wallet),amountWei=ethers.utils.parseUnits(amount.toString(),6),tx=await tokenContract.transfer(receiver,amountWei);return{tx:tx,hash:tx.hash}}catch(error){console.error("Error:",error.message)}}}("object"==typeof module?module.exports:window.ethOperator={}); \ No newline at end of file