{"id":7366,"date":"2024-03-20T06:53:14","date_gmt":"2024-03-20T06:53:14","guid":{"rendered":"https:\/\/metaschool.so\/articles\/?p=7366"},"modified":"2024-03-20T06:53:19","modified_gmt":"2024-03-20T06:53:19","slug":"use-different-addresses-in-hardhat-scripts","status":"publish","type":"post","link":"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/","title":{"rendered":"How To Use Different Addresses To Call Functions in Hardhat Scripts?"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_56_1 ez-toc-wrap-left counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title \" >Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#1_Understanding_Ethereum_addresses\" title=\"1. Understanding Ethereum addresses\">1. Understanding Ethereum addresses<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#2_Generating_multiple_Ethereum_addresses\" title=\"2. Generating multiple Ethereum addresses\">2. Generating multiple Ethereum addresses<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#3_Deploying_contracts_with_different_accounts\" title=\"3. Deploying contracts with different accounts\">3. Deploying contracts with different accounts<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#4_Interacting_with_contracts_using_different_accounts\" title=\"4. Interacting with contracts using different accounts\">4. Interacting with contracts using different accounts<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#5_Managing_balances_and_transactions\" title=\"5. Managing balances and transactions\">5. Managing balances and transactions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#6_Handling_events_and_assertions\" title=\"6. Handling events and assertions\">6. Handling events and assertions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#7_Cleaning_up\" title=\"7. Cleaning up\">7. Cleaning up<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/metaschool.so\/articles\/use-different-addresses-in-hardhat-scripts\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n\n<p>Using different addresses to call functions in Hardhat tests and scripts can be crucial for various scenarios, such as testing contract behavior with different users, simulating transactions from multiple parties, or verifying contract functionalities under various conditions. In this guide, I&#8217;ll walk you through the process of managing multiple addresses effectively within your Hardhat tests and scripts.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-understanding-ethereum-addresses\"><span class=\"ez-toc-section\" id=\"1_Understanding_Ethereum_addresses\"><\/span>1. <strong>Understanding Ethereum addresses<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Ethereum addresses are alphanumeric identifiers representing user accounts or smart contracts on the Ethereum blockchain. These addresses are derived from public-private key pairs and are used to send and receive Ether or interact with <a href=\"https:\/\/metaschool.so\/articles\/guide-move-smart-contract-programming-language\/\" target=\"_blank\" rel=\"noreferrer noopener\">smart contracts<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-generating-multiple-ethereum-addresses\"><span class=\"ez-toc-section\" id=\"2_Generating_multiple_Ethereum_addresses\"><\/span>2. <strong>Generating multiple Ethereum addresses<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Ethereum, you can generate multiple addresses easily. Typically, each Ethereum address corresponds to a unique private key. Hardhat provides utilities for generating Ethereum addresses programmatically. For instance, you can use the <code>ethers<\/code> library to create multiple accounts:<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>const { ethers } = require('hardhat');\n\nasync function generateAccounts(numAccounts) {\n    const accounts = &#91;];\n    for (let i = 0; i &lt; numAccounts; i++) {\n        const wallet = ethers.Wallet.createRandom();\n        accounts.push(wallet);\n    }\n    return accounts;\n}\n\nconst numAccounts = 5;\nconst accounts = await generateAccounts(numAccounts);<\/code><\/pre>\n\n\n\n<p>This code will generate five Ethereum addresses along with their corresponding private keys.<\/p>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/one-piece-personality-dapp-solidity\" target=\"_blank\" rel=\"noreferrer noopener\">Build a One Piece Personality dApp With Solidity<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-deploying-contracts-with-different-accounts\"><span class=\"ez-toc-section\" id=\"3_Deploying_contracts_with_different_accounts\"><\/span>3. <strong>Deploying contracts with different accounts<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Hardhat allows you to deploy contracts using different Ethereum addresses. This is useful for testing contract deployment and initialization logic from various perspectives.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>const { ethers } = require('hardhat');\n\nasync function deployContractWithAccount(contractName, account) {\n    const Contract = await ethers.getContractFactory(contractName);\n    const contract = await Contract.connect(account).deploy();\n    return contract;\n}\n\nconst contractName = 'MyContract';\nconst deployedContracts = &#91;];\nfor (let i = 0; i &lt; numAccounts; i++) {\n    const contract = await deployContractWithAccount(contractName, accounts&#91;i]);\n    deployedContracts.push(contract);\n}<\/code><\/pre>\n\n\n\n<p>This code deploys the contract <code>MyContract<\/code> using each of the generated Ethereum addresses.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-interacting-with-contracts-using-different-accounts\"><span class=\"ez-toc-section\" id=\"4_Interacting_with_contracts_using_different_accounts\"><\/span>4. <strong>Interacting with contracts using different accounts<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Once contracts are deployed, you can interact with them using different accounts. This allows you to test various scenarios, such as different users accessing specific functionalities.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>const contract = deployedContracts&#91;0]; \/\/ Using the first deployed contract\nconst signer = accounts&#91;1]; \/\/ Using the second generated account for interaction\n\nawait contract.connect(signer).someFunction(); \/\/ Call contract function with the second account<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-managing-balances-and-transactions\"><span class=\"ez-toc-section\" id=\"5_Managing_balances_and_transactions\"><\/span>5. <strong>Managing balances and transactions<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Ethereum, each transaction requires gas fees to be paid. When testing contracts with multiple accounts, you need to ensure each account has sufficient Ether balance for executing transactions.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>const { ethers } = require('hardhat');\n\nasync function fundAccount(account, amount) {\n    await ethers.provider.sendTransaction({\n        to: account.address,\n        value: ethers.utils.parseEther(amount)\n    });\n}\n\nconst amountToFund = '10'; \/\/ Ether amount to fund\nfor (let i = 0; i &lt; numAccounts; i++) {\n    await fundAccount(accounts&#91;i], amountToFund);\n}\n\n<\/code><\/pre>\n\n\n\n<p>This code funds each generated account with a specified amount of Ether.<\/p>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/build-hogwarts-sorting-cap-dapp-on-polygon-mumbai\" target=\"_blank\" rel=\"noreferrer noopener\">Build Hogwarts Sorting Hat dApp on Polygon<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-handling-events-and-assertions\"><span class=\"ez-toc-section\" id=\"6_Handling_events_and_assertions\"><\/span>6. <strong>Handling events and assertions<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In your tests, you might need to verify certain events emitted by contracts or assert specific conditions after function calls. Hardhat provides utilities for listening to events and making assertions.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ Example: Listening to an event\nconst tx = await contract.someFunction();\nawait tx.wait(); \/\/ Ensure the transaction is mined\nconst receipt = await ethers.provider.getTransactionReceipt(tx.hash);\nconst event = contract.interface.parseLog(receipt.logs&#91;0]);\n\n\/\/ Example: Assertion\nassert(event.name === 'SomeEvent', 'Event not emitted');<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-cleaning-up\"><span class=\"ez-toc-section\" id=\"7_Cleaning_up\"><\/span>7. <strong>Cleaning up<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>After testing or executing scripts, it&#8217;s essential to clean up any state changes, such as reverting transactions or resetting contract states. Hardhat allows you to revert transactions or reset blockchain state easily.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ Example: Reverting transactions\nawait expect(\n    contract.someFunctionThatShouldFail()\n).to.be.revertedWith('Revert reason');\n\n\/\/ Example: Resetting blockchain state\nawait hre.network.provider.request({\n    method: \"hardhat_reset\",\n    params: &#91;],\n});<\/code><\/pre>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/build-marketplace-erc404-tokens\" target=\"_blank\" rel=\"noreferrer noopener\">Build a Semi-Fungible ERC404 Tokens&#8217; Marketplace<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Managing multiple addresses effectively in Hardhat tests and scripts enables you to thoroughly test smart contracts under various conditions, ensuring their robustness and reliability. By generating addresses, deploying contracts, interacting with contracts, managing balances, handling events, and cleaning up, you can conduct comprehensive testing and simulation of Ethereum-based applications.<\/p>\n\n\n\n<p>Remember to consider gas fees, state changes, and contract behaviors meticulously to ensure accurate and reliable testing outcomes. With the right approach and tools provided by Hardhat, you can streamline the testing process and improve the quality of your Ethereum smart contracts.<\/p>\n\n\n\n<p><strong>Try it out, ask us questions, and tell us how it went by tagging Metaschool on Social Media.<\/strong><\/p>\n\n\n\n<p><strong>Follow us on<\/strong>&nbsp;\u2013<\/p>\n\n\n\n<p>\ud83d\udd2eTwitter \u2013\u00a0<a href=\"https:\/\/twitter.com\/0xmetaschool\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/twitter.com\/0xmetaschool<\/a><\/p>\n\n\n\n<p>\ud83d\udd17LinkedIn \u2013\u00a0<a href=\"https:\/\/www.linkedin.com\/company\/0xmetaschool\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.linkedin.com\/company\/0xmetaschool\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":15,"featured_media":7367,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"neve_meta_sidebar":"","neve_meta_container":"","neve_meta_enable_content_width":"","neve_meta_content_width":0,"neve_meta_title_alignment":"","neve_meta_author_avatar":"","neve_post_elements_order":"","neve_meta_disable_header":"","neve_meta_disable_footer":"","neve_meta_disable_title":"","footnotes":""},"categories":[292],"tags":[],"class_list":["post-7366","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-answers"],"_links":{"self":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7366","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/users\/15"}],"replies":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/comments?post=7366"}],"version-history":[{"count":2,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7366\/revisions"}],"predecessor-version":[{"id":7369,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7366\/revisions\/7369"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media\/7367"}],"wp:attachment":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media?parent=7366"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/categories?post=7366"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/tags?post=7366"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}