{"id":7495,"date":"2024-03-26T07:46:10","date_gmt":"2024-03-26T07:46:10","guid":{"rendered":"https:\/\/metaschool.so\/articles\/?p=7495"},"modified":"2024-03-26T07:46:13","modified_gmt":"2024-03-26T07:46:13","slug":"get-the-address-of-a-contract-deployed-by-another-contract-in-solidity","status":"publish","type":"post","link":"https:\/\/metaschool.so\/articles\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/","title":{"rendered":"How To Get the Address of a Contract Deployed by Another Contract in Solidity"},"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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Introduction_to_contract_interaction_in_Solidity\" title=\"Introduction to contract interaction in Solidity\">Introduction to contract interaction in Solidity<\/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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Using_an_external_function_to_return_the_address\" title=\"Using an external function to return the address\">Using an external function to return the address<\/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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Emitting_an_event_with_the_address\" title=\"Emitting an event with the address\">Emitting an event with the address<\/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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Using_a_factory_design_pattern\" title=\"Using a factory design pattern\">Using a factory design pattern<\/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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Using_return_values_in_deployment_functions\" title=\"Using return values in deployment functions\">Using return values in deployment functions<\/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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Call_before_you_make_a_transaction\" title=\"Call before you make a transaction\">Call before you make a transaction<\/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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Calculate_the_future_address\" title=\"Calculate the future address\">Calculate the future address<\/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\/get-the-address-of-a-contract-deployed-by-another-contract-in-solidity\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n\n<h2 class=\"wp-block-heading\" id=\"introduction-to-contract-interaction-in-solidity\"><span class=\"ez-toc-section\" id=\"Introduction_to_contract_interaction_in_Solidity\"><\/span>Introduction to contract interaction in Solidity<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Solidity, the programming language used for Ethereum <a href=\"https:\/\/metaschool.so\/articles\/structure-of-a-smart-contract\/\" target=\"_blank\" rel=\"noreferrer noopener\">smart contracts<\/a>, allows contracts to interact with each other. When one contract deploys another, it&#8217;s common to need the address of the deployed contract for further interactions. There are several ways to achieve this, depending on your specific requirements and constraints.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"using-an-external-function-to-return-the-address\"><span class=\"ez-toc-section\" id=\"Using_an_external_function_to_return_the_address\"><\/span>Using an external function to return the address<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>One common approach is to define an external function in the deploying contract that returns the address of the deployed contract. This function can be called by other contracts or externally by users.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>pragma solidity ^0.8.0;\n\ncontract Deployer {\n    address public deployedContract;\n\n    function deploy() external {\n        deployedContract = address(new MyContract());\n    }\n}\n\ncontract MyContract {\n    \/\/ Contract logic...\n}<\/code><\/pre>\n\n\n\n<p>In this example, the <code>Deployer<\/code> contract deploys <code>MyContract<\/code> and stores its address in the <code>deployedContract<\/code> variable. Other contracts or users can then query this address using the <code>deployedContract<\/code> public variable.<\/p>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/create-your-own-ethereum-token-in-just-30-mins\" target=\"_blank\" rel=\"noreferrer noopener\">Create Your Own Ethereum Token in Just 30 Mins<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"emitting-an-event-with-the-address\"><span class=\"ez-toc-section\" id=\"Emitting_an_event_with_the_address\"><\/span>Emitting an event with the address<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Another approach is to emit an event containing the address of the deployed contract. Events are useful for notifying external entities about state changes within the contract.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>pragma solidity ^0.8.0;\n\ncontract Deployer {\n    event ContractDeployed(address indexed deployedAddress);\n\n    function deploy() external {\n        MyContract deployed = new MyContract();\n        emit ContractDeployed(address(deployed));\n    }\n}\n\ncontract MyContract {\n    \/\/ Contract logic...\n}<\/code><\/pre>\n\n\n\n<p>Here, when <code>Deployer<\/code> deploys <code>MyContract<\/code>, it emits a <code>ContractDeployed<\/code> event containing the address of the deployed contract. External entities can listen to this event and capture the deployed contract&#8217;s address.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"using-a-factory-design-pattern\"><span class=\"ez-toc-section\" id=\"Using_a_factory_design_pattern\"><\/span>Using a factory design pattern<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The Factory design pattern is a common solution for deploying multiple instances of a contract and keeping track of their addresses. In this pattern, a separate factory contract is responsible for deploying instances of another contract.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>pragma solidity ^0.8.0;\n\ncontract MyContractFactory {\n    event ContractDeployed(address indexed deployedAddress);\n\n    function deploy() external {\n        MyContract deployed = new MyContract();\n        emit ContractDeployed(address(deployed));\n    }\n}\n\ncontract MyContract {\n    \/\/ Contract logic...\n}<\/code><\/pre>\n\n\n\n<p>In this setup, <code>MyContractFactory<\/code> serves as the factory contract responsible for deploying instances of <code>MyContract<\/code>. It emits an event upon deployment, providing the address of the new contract.<\/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=\"using-return-values-in-deployment-functions\"><span class=\"ez-toc-section\" id=\"Using_return_values_in_deployment_functions\"><\/span>Using return values in deployment functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Solidity provides a way to return values from functions, even constructor functions, which can be useful for retrieving the address of the deployed contract.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>pragma solidity ^0.8.0;\n\ncontract Deployer {\n    function deploy() external returns (address) {\n        return address(new MyContract());\n    }\n}\n\ncontract MyContract {\n    \/\/ Contract logic...\n}<\/code><\/pre>\n\n\n\n<p>In this scenario, the <code>deploy<\/code> function of the <code>Deployer<\/code> contract returns the address of the deployed <code>MyContract<\/code>. External callers can invoke this function and capture the returned address.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"call-before-you-make-a-transaction\"><span class=\"ez-toc-section\" id=\"Call_before_you_make_a_transaction\"><\/span>Call before you make a transaction<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Before making a transaction to deploy a contract, you can first make a call to the factory contract to retrieve the address of the future contract. This approach allows you to obtain the address without actually deploying the contract, providing assurance and flexibility.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>var address = web3.eth.contract(objectFactoryAbi)\n    .at(contractFactoryAddress)\n    .createObject.call(\"object\");<\/code><\/pre>\n\n\n\n<p>In this code snippet, <code>objectFactoryAbi<\/code> represents the ABI (Application Binary Interface) of the factory contract, and <code>contractFactoryAddress<\/code> is the address of the factory contract. The <code>.createObject.call(\"object\")<\/code> call simulates the deployment of the contract without actually committing the transaction. It returns the address where the contract will be deployed.<\/p>\n\n\n\n<p>Once you have obtained the address, you can proceed with the transaction to deploy the contract:<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>var txHash = web3.eth.contract(objectFactoryAbi)\n    .at(contractFactoryAddress)\n    .createObject(\"object\", { gas: price, from: accountAddress });<\/code><\/pre>\n\n\n\n<p>Here, <code>.createObject(\"object\", { gas: price, from: accountAddress })<\/code> initiates the transaction to deploy the contract. Ensure to specify the necessary gas and sender address (<code>accountAddress<\/code>) for the transaction to be processed successfully.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"calculate-the-future-address\"><span class=\"ez-toc-section\" id=\"Calculate_the_future_address\"><\/span>Calculate the future address<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Alternatively, you can calculate the address of the future contract without actually deploying it. This method utilizes Ethereum&#8217;s address derivation algorithm to compute the address based on the factory contract&#8217;s address and nonce.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>var ethJsUtil = require('ethereumjs-util');\nvar futureAddress = ethJsUtil.bufferToHex(ethJsUtil.generateAddress(\n      contractFactoryAddress,\n      await web3.eth.getTransactionCount(contractFactoryAddress)));<\/code><\/pre>\n\n\n\n<p>In this code snippet, <code>ethereumjs-util<\/code> library is used for Ethereum-specific utilities. <code>generateAddress<\/code> function computes the address based on the factory contract&#8217;s address (<code>contractFactoryAddress<\/code>) and the nonce, obtained using <code>web3.eth.getTransactionCount(contractFactoryAddress)<\/code>. The resulting <code>futureAddress<\/code> represents the address where the contract will be deployed.<\/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=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>These are some of the methods you can employ to obtain the address of a contract deployed by another contract in Solidity. Each approach has its advantages and may be more suitable depending on the specific requirements of your application. Whether it&#8217;s through direct return values, events, external functions, call before initiating a transaction, or calculating the future address, Solidity offers flexibility in contract interaction to accommodate various use cases. Understanding these techniques will empower you to design robust and interoperable smart contracts on the Ethereum blockchain.<\/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":7497,"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":[51,31,46,29],"class_list":["post-7495","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-answers","tag-blockchain","tag-ethereum-blockchain","tag-solidity","tag-web3"],"_links":{"self":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7495","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=7495"}],"version-history":[{"count":2,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7495\/revisions"}],"predecessor-version":[{"id":7499,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7495\/revisions\/7499"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media\/7497"}],"wp:attachment":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media?parent=7495"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/categories?post=7495"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/tags?post=7495"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}