Testing Infura integration

This commit is contained in:
sairaj mote 2023-11-12 03:36:51 +05:30
parent 56e8e28d7a
commit fb199d9a33
8 changed files with 386 additions and 102 deletions

View File

@ -882,6 +882,7 @@ aside h4 {
place-content: center;
place-items: center;
text-align: center;
grid-column: 1/-1;
}
#error_section .icon {
height: 8rem;

2
css/main.min.css vendored

File diff suppressed because one or more lines are too long

View File

@ -817,6 +817,7 @@ aside {
place-content: center;
place-items: center;
text-align: center;
grid-column: 1/-1;
.icon {
height: 8rem;
width: 8rem;

View File

@ -92,7 +92,7 @@
</button>
<theme-toggle></theme-toggle>
</header>
<aside class="flex flex-direction-column">
<aside id="saved_addresses_wrapper" class="flex flex-direction-column">
<h4>
Searched addresses
</h4>
@ -234,7 +234,7 @@
<script src="scripts/floEthereum.js" type="text/javascript"></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/usdc_balance.js" type="text/javascript"> </script>
<script src="scripts/ethOperator.js" type="text/javascript"> </script>
<script>
const uiGlobals = {}
const { html, svg, render: renderElem } = uhtml;
@ -465,15 +465,20 @@
}).catch((error) => {
console.error(error)
})
connectToMetaMask().then(() => {
// connectToMetaMask().then(() => {
console.log('MetaMask connected')
if (window.ethereum) {
// setMetaMaskStatus(window.ethereum.isConnected())
window.ethereum.on('chainChanged', (networkId) => {
if (networkId !== '1') {
window.ethereum.on('chainChanged', (chainId) => {
console.log(chainId)
if (chainId !== '0x1') {
getRef('error__title').textContent = 'Please switch MetaMask to Ethereum Mainnet'
getRef('main_section').classList.add('hidden')
getRef('saved_addresses_wrapper').classList.add('hidden')
getRef('error_section').classList.remove('hidden')
} else {
getRef('main_section').classList.remove('hidden')
getRef('saved_addresses_wrapper').classList.remove('hidden')
getRef('error_section').classList.add('hidden')
}
})
@ -483,26 +488,29 @@
if (chainId !== '0x1') {
getRef('error__title').textContent = 'Please switch MetaMask to Ethereum Mainnet'
getRef('main_section').classList.add('hidden')
getRef('saved_addresses_wrapper').classList.add('hidden')
getRef('error_section').classList.remove('hidden')
} else {
getRef('main_section').classList.remove('hidden')
getRef('saved_addresses_wrapper').classList.remove('hidden')
getRef('error_section').classList.add('hidden')
}
})
}).catch((error) => {
setMetaMaskStatus(false)
if (error.code === 4001) {
// EIP-1193 userRejectedRequest error
notify('Please connect to MetaMask to continue', 'error')
} else {
if (error === 'MetaMask not installed') {
getRef('main_section').classList.add('hidden')
getRef('error_section').classList.remove('hidden')
}
else
console.error(error)
}
})
}
// }).catch((error) => {
// setMetaMaskStatus(false)
// if (error.code === 4001) {
// // EIP-1193 userRejectedRequest error
// notify('Please connect to MetaMask to continue', 'error')
// } else {
// if (error === 'MetaMask not installed') {
// getRef('main_section').classList.add('hidden')
// getRef('error_section').classList.remove('hidden')
// }
// else
// console.error(error)
// }
// })
if (typeof window.ethereum !== 'undefined') {
ethereum.on('accountsChanged', (accounts) => {
getRef('eth_balance_wrapper').classList.add('hidden')
@ -559,41 +567,45 @@
}
if (!ethAddress) return
buttonLoader('check_balance_button', true)
Promise.all([checkUSDCBalance(ethAddress), checkUSDTBalance(ethAddress)]).then(([usdcBalance, usdtBalance]) => {
compactIDB.readData('contacts', floAddress).then(result => {
if (result) return
compactIDB.addData('contacts', {
ethAddress,
}, floAddress).then(() => {
renderSearchedAddressList()
}).catch((error) => {
console.error(error)
Promise.all([
ethOperator.checkTokenBalance({ address: ethAddress, token: 'usdc' }),
ethOperator.checkTokenBalance({ address: ethAddress, token: 'usdt' })
])
.then(([usdcBalance, usdtBalance]) => {
compactIDB.readData('contacts', floAddress).then(result => {
if (result) return
compactIDB.addData('contacts', {
ethAddress,
}, floAddress).then(() => {
renderSearchedAddressList()
}).catch((error) => {
console.error(error)
})
})
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('eth_balance_wrapper').classList.remove('hidden')
getRef('eth_balance_wrapper').animate([
{
transform: 'translateY(-1rem)',
opacity: 0
},
{
transform: 'none',
opacity: 1
}
], {
easing: 'ease',
duration: 300,
fill: 'forwards'
})
}).catch((error) => {
notify(error, 'error')
}).finally(() => {
buttonLoader('check_balance_button', false)
})
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('eth_balance_wrapper').classList.remove('hidden')
getRef('eth_balance_wrapper').animate([
{
transform: 'translateY(-1rem)',
opacity: 0
},
{
transform: 'none',
opacity: 1
}
], {
easing: 'ease',
duration: 300,
fill: 'forwards'
})
}).catch((error) => {
notify(error, 'error')
}).finally(() => {
buttonLoader('check_balance_button', false)
})
}
function handleInvalidSearch() {
if (document.startViewTransition)

318
scripts/ethOperator.js Normal file
View File

@ -0,0 +1,318 @@
(function (EXPORTS) { //ethOperator v0.0.1
/* ETH Crypto and API Operator */
if (!window.ethers)
return console.error('ethers.js not found')
const ethOperator = EXPORTS;
const ERC20ABI = [
{
"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: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
usdt: "0xdac17f958d2ee523a2206206994597c13d831ec7"
}
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://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 checkTokenBalance = ethOperator.checkTokenBalance = 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['usdc'] || contractAddress, ERC20ABI, getProvider());
const balance = await usdcContract.balanceOf(address);
return balance;
} catch (e) {
console.error(e);
}
}
const sendTransaction = ethOperator.sendTransaction = async ({ privateKey, receiver, amount }) => {
const signer = new ethers.Wallet(privateKey, provider);
const limit = provider.estimateGas({
from: signer.address,
to: receiver,
value: ethers.utils.parseUnits(amount, "ether"),
});
// Creating and sending the transaction object
const tx = await signer.sendTransaction({
to: receiver,
value: ethers.utils.parseUnits(amount, "ether"),
gasLimit: limit,
nonce: signer.getTransactionCount(),
maxPriorityFeePerGas: ethers.utils.parseUnits("2", "gwei"),
chainId: 3,
});
const receipt = await tx.wait();
console.log("Transaction Hash:", tx.hash);
console.log("Transaction Receipt:", receipt);
}
const sendToken = ethOperator.sendToken = async ({ token, privateKey, amount, receiver, contractAddress }) => {
try {
// 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, ERC20ABI, 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
const tx = await tokenContract.transfer(receiver, amountWei);
// Wait for the transaction to be mined
const receipt = await tx.wait();
console.log('Transaction Hash:', tx.hash);
console.log('Transaction Receipt:', receipt);
} catch (error) {
console.error('Error:', error.message);
}
}
})('object' === typeof module ? module.exports : window.ethOperator = {});

1
scripts/ethOperator.min.js vendored Normal file
View File

@ -0,0 +1 @@
!function(EXPORTS){if(!window.ethers)return console.error("ethers.js not found");const ethOperator=EXPORTS,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.checkTokenBalance=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 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"),chainId:3}),receipt=await tx.wait();console.log("Transaction Hash:",tx.hash),console.log("Transaction Receipt:",receipt)},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),receipt=await tx.wait();console.log("Transaction Hash:",tx.hash),console.log("Transaction Receipt:",receipt)}catch(error){console.error("Error:",error.message)}}}("object"==typeof module?module.exports:window.ethOperator={});

View File

@ -1,48 +0,0 @@
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();
async function checkUSDCBalance(ethAddress) {
try {
if (!window.ethereum.isConnected()) {
await connectToMetaMask();
}
const provider = new ethers.providers.Web3Provider(window.ethereum);
const usdcContractAddress = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"; // USDC contract address on Ethereum mainnet
const usdcContract = new ethers.Contract(usdcContractAddress, ["function balanceOf(address) view returns (uint256)"], provider);
const balance = await usdcContract.balanceOf(ethAddress);
return balance;
} catch (e) {
console.log(e);
}
}
async function checkUSDTBalance(ethAddress) {
try {
if (!window.ethereum.isConnected()) {
await connectToMetaMask();
}
const provider = new ethers.providers.Web3Provider(window.ethereum);
const usdtContractAddress = "0xdac17f958d2ee523a2206206994597c13d831ec7"; // USDT contract address on Ethereum mainnet
const usdtContract = new ethers.Contract(usdtContractAddress, ["function balanceOf(address) view returns (uint256)"], provider);
const balance = await usdtContract.balanceOf(ethAddress);
return balance;
} catch (e) {
console.log(e);
}
}

View File

@ -1 +0,0 @@
function connectToMetaMask(){return new Promise(((resolve,reject)=>void 0===window.ethereum?reject("MetaMask not installed"):resolve(!0)))}async function checkUSDCBalance(ethAddress){try{window.ethereum.isConnected()||await connectToMetaMask();const provider=new ethers.providers.Web3Provider(window.ethereum),usdcContractAddress="0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",usdcContract=new ethers.Contract(usdcContractAddress,["function balanceOf(address) view returns (uint256)"],provider);return await usdcContract.balanceOf(ethAddress)}catch(e){console.log(e)}}async function checkUSDTBalance(ethAddress){try{window.ethereum.isConnected()||await connectToMetaMask();const provider=new ethers.providers.Web3Provider(window.ethereum),usdtContractAddress="0xdac17f958d2ee523a2206206994597c13d831ec7",usdtContract=new ethers.Contract(usdtContractAddress,["function balanceOf(address) view returns (uint256)"],provider);return await usdtContract.balanceOf(ethAddress)}catch(e){console.log(e)}}connectToMetaMask();