![]() |
|
[Tut] How I Built My Own ERC-20 Token (2/2) - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How I Built My Own ERC-20 Token (2/2) (/thread-100787.html) |
[Tut] How I Built My Own ERC-20 Token (2/2) - xSicKxBot - 02-22-2023 How I Built My Own ERC-20 Token (2/2) 5/5 – (2 votes) In the first part, we connected the front end with Metamask but couldn’t fetch the balance. Let’s try to fetch the balance from the wallet this time. But first, install the Code: ether.jsCode: npm install --save ethersImport Code: ether.jsCode: App.jsCode: import {ethers} from "ethers";Now we need to import the contract ABI. The contract ABI is the JSON format of the contract that saves the bytecode of the deployed contract.Create a Code: contractsCode: contractsCode: SilverToken.jsonCopy the ABI of the contract from the Remix IDE and paste it inside the JSON file. Now import the ABI from the JSON file to the Code: app.jsCode: import contractABI from "./contracts/SilverToken.json";Create a variable for the contract address. Code: const contractAddress = "0xC16322799f2645D5b7a1287392072aA668F8144B";We need to create a contract instance to get access to the methods of our deployed smart contract. We need three things to create an instance of the contract. Those are the provider, signer, and contract ABI. ![]() We already imported the ABI. So, let’s create state variables for the provider, signer, and contract and initially keep all the values null. Code: const [provider, setProvider] = useState(null);
const [signer, setSigner] = useState(null);
const [contract, setContract] = useState(null);Inside the Code: connectMetamaskCode: providerCode: signerCode: contractCode: const provider = new Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract( contractAddress, contractABI, signer);
setProvider(provider);
setContract(contract);
setSigner(signer);![]() We defined the provider with the help of the Code: Web3ProviderCode: ethersI was unable to access the Code: providersCode: providersCode: npmFirst, install and then import the Code: providersCode: npm i @ethersproject/providerssince we will use the Code: Web3ProviderCode: providersCode: import { Web3Provider } from "@ethersproject/providers";We are committing a transaction, so we must need a signer. We called the signer by using the Code: getSigner()![]() Then we created an instance of our smart contract with the Code: contract()Code: ethersThis Code: contract()Now the provider, signer, and contract are defined. So, we need to change the state of these three that we have defined as null earlier. Now let’s Code: console.logCode: console.log(contract);![]() As you can see in my console, the contract’s state was initially null. But now it returns the contract address that we are connected to. Get Wallet Balance ![]() Create a Code: getBalance()Code: const getBalance = async () => { const balanceInBig = await contract.balanceOf(activeAccount); const balanceInNum = Number(balanceInBig) / 100; setTokenBalance(balanceInNum); };We are using the Code: balanceOfCode: bigIntegerCode: BigIntIn the 2nd line, we converted the big integer number to a readable format. To initiate the Code: getBalance()Code: useEffect()Code: useEffect(() => { if (contract != null) { getBalance(); } }, [contract]);The Code: useEffect()Code: getBalanceCode: useEffect()Transfer the Balance ![]() Now to transfer the balance, we need a form where we will input the address of the account to which we will be transferring the amount. Let’s do this part in a separate functional component. Let’s create a components folder inside the source folder and create a new file called Code: Transaction.jsInside this file, create a component structure by pressing “ Code: rscI will create a simple form using custom codes from flowbite. You can check it out or make your own custom one. Inside the return function, paste the following. Code: return ( <div className="w-1/2 mx-auto bg-slate-600 mt-10 p-5 border rounded-lg"> <form onSubmit={transactionHandler}> <div className="mb-6"> <label for="address" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Receiver Address </label> <input type="text" id="address" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Enter Receiver Address" required /> </div> <div className="mb-6"> <label for="amount" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Transfer Amount </label> <input type="number" id="amount" className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required /> </div> <button type="submit" className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" > Send Token </button> <div className="mt-5"> <h3 className="text-slate-100">{transactionHash}</h3> </div> </form> </div> );We created two input fields inside the form. One is text type for the receiver address, and another is a number type for the amount that would be sent to the receiver. The id of each input filed is changed to “ Code: addressCode: amountA Code: transactionHandler()Code: sendLet’s define the Code: transactionHandler()Code: const transactionHandler = async (event) => { event.preventDefault(); let receiverAddress = event.target.address.value; let sendAmount = event.target.amount.value; let transferAmount = sendAmount * 100; let trans = await contract.transfer(receiverAddress, transferAmount); console.log(trans); setTransactionHash("Transaction confirmed with hash:" + trans.hash); };![]() The Code: transactionHandler()Code: async awaitCode: preventDefault()The Code: transferAmountCode: receiverAddressCode: event.targetCode: amountCode: addressWe need to use the Code: transferCode: app.jsCall the Code: transaction.jsCode: app.jsCode: <Transaction contract={contract}></Transaction>We are using the “ Code: contract.transferWe will get a transaction hash as a transfer confirmation when the transaction is done. We can store this transaction hash as a state variable to display it on the user interface. ![]() Let’s create a new account on the Goerli testnet. This will be our receiver account. Now use this address and send an amount of 50 tokens from the main wallet. We need to multiply the amount by 100 to get the exact value, as we used a two-digit return in the decimals function of the smart contract. Now if you check this transaction hash on the Etherscan website, you will get the complete transaction details. You will also receive the token balance on the Metamask receiver wallet. ![]() This is the screenshot of my recent transaction. To get your transaction details, just use the transaction hash in the search bar. Make sure you choose the Goerli testnet as the network. That’s all for today. Thanks for the reading! ![]() Github: https://github.com/finxter/silver_wallet
|