{"id":7473,"date":"2024-03-25T08:06:12","date_gmt":"2024-03-25T08:06:12","guid":{"rendered":"https:\/\/metaschool.so\/articles\/?p=7473"},"modified":"2024-03-25T08:06:14","modified_gmt":"2024-03-25T08:06:14","slug":"how-to-receive-a-value-returned-by-solidity-transacting-function","status":"publish","type":"post","link":"https:\/\/metaschool.so\/articles\/how-to-receive-a-value-returned-by-solidity-transacting-function\/","title":{"rendered":"How To Receive a Value Returned by Solidity Transacting Function?"},"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\/how-to-receive-a-value-returned-by-solidity-transacting-function\/#Understanding_smart_contract_functions\" title=\"Understanding smart contract functions\">Understanding smart contract functions<\/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\/how-to-receive-a-value-returned-by-solidity-transacting-function\/#Interacting_with_smart_contracts\" title=\"Interacting with smart contracts\">Interacting with smart contracts<\/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\/how-to-receive-a-value-returned-by-solidity-transacting-function\/#Steps_to_receive_a_value_returned_by_a_smart_contract_transacting_function\" title=\"Steps to receive a value returned by a smart contract transacting function\">Steps to receive a value returned by a smart contract transacting function<\/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\/how-to-receive-a-value-returned-by-solidity-transacting-function\/#Example_Sending_ether_and_receiving_value\" title=\"Example: Sending ether and receiving value\">Example: Sending ether and receiving value<\/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\/how-to-receive-a-value-returned-by-solidity-transacting-function\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n\n<p>Sure, I&#8217;d be happy to guide you through receiving a value returned by a Solidity <a href=\"https:\/\/metaschool.so\/articles\/guide-move-smart-contract-programming-language\/\" target=\"_blank\" rel=\"noreferrer noopener\">smart contract<\/a> transacting function. This process involves interacting with the Ethereum blockchain, so understanding the fundamentals is crucial. Let&#8217;s break it down step by step:<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"understanding-smart-contract-functions\"><span class=\"ez-toc-section\" id=\"Understanding_smart_contract_functions\"><\/span>Understanding smart contract functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Solidity, smart contracts can have two types of functions: <strong>view<\/strong> and <strong>non-view<\/strong> (or <strong>transacting<\/strong>) functions. View functions are read-only and don&#8217;t change the state of the blockchain. On the other hand, non-view functions modify the state of the blockchain.<\/p>\n\n\n\n<p>When you call a view function, you can receive the return value directly because it doesn&#8217;t require mining and executing a transaction on the blockchain. However, for transacting functions, you need to submit a transaction to the blockchain, wait for it to be mined, and then fetch the return value.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"interacting-with-smart-contracts\"><span class=\"ez-toc-section\" id=\"Interacting_with_smart_contracts\"><\/span>Interacting with smart contracts<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>To interact with a smart contract, you typically use a Web3.js library in JavaScript or similar libraries in other languages. These libraries provide functions to deploy contracts, call their functions, and handle transactions.<\/p>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>&nbsp;<a href=\"https:\/\/metaschool.so\/courses\/create-your-own-ethereum-token-in-just-30-mins\">Create Your Own Ethereum Token in Just 30 Mins<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"steps-to-receive-a-value-returned-by-a-smart-contract-transacting-function\"><span class=\"ez-toc-section\" id=\"Steps_to_receive_a_value_returned_by_a_smart_contract_transacting_function\"><\/span>Steps to receive a value returned by a smart contract transacting function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Here&#8217;s a step-by-step guide on how to receive a value returned by a Solidity smart contract transacting function:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Set Up Web3.js<\/strong>: First, you need to set up Web3.js in your project. This involves connecting to an Ethereum node, which can be a local node (e.g., Ganache) during development or a public node (e.g., Infura) in production.<\/li><li><strong>Instantiate Contract<\/strong>: Use the ABI (Application Binary Interface) and address of the smart contract to instantiate it in your JavaScript code. The ABI provides a way to interact with the contract, and the address identifies the specific instance on the blockchain.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>const contractABI = &#91;...]; \/\/ ABI of the smart contract\nconst contractAddress = '0x123...'; \/\/ Address of the deployed contract\nconst contract = new web3.eth.Contract(contractABI, contractAddress);<\/code><\/pre>\n\n\n\n<p>3. <strong>Send Transaction<\/strong>: Call the transacting function of the smart contract using the <code>send()<\/code> method. This method sends a transaction to the Ethereum network.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>contract.methods.myFunction(param1, param2)\n    .send({from: myAddress, value: valueToSend})\n    .on('transactionHash', (hash) => {\n        console.log('Transaction Hash:', hash);\n    })\n    .on('receipt', (receipt) => {\n        console.log('Transaction Receipt:', receipt);\n    })\n    .on('error', (error) => {\n        console.error('Transaction Error:', error);\n    });<\/code><\/pre>\n\n\n\n<p>Replace <code>myFunction<\/code> with the name of the function you want to call, <code>param1<\/code>, <code>param2<\/code>, etc., with the function parameters, <code>myAddress<\/code> with your Ethereum address, and <code>valueToSend<\/code> with the amount of ether to send (if required).<\/p>\n\n\n\n<p>4. <strong>Wait for Confirmation<\/strong>: After sending the transaction, you need to wait for it to be confirmed by the network. This typically takes a few seconds to a few minutes, depending on network congestion.<\/p>\n\n\n\n<p>5. <strong>Fetch Return Value<\/strong>: Once the transaction is confirmed, you can fetch the return value of the function. For transacting functions, you need to use the <code>call()<\/code> method instead of <code>send()<\/code>, as <code>send()<\/code> doesn&#8217;t return a value.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>contract.methods.myFunction(param1, param2)\n    .call({from: myAddress})\n    .then((result) => {\n        console.log('Return Value:', result);\n    })\n    .catch((error) => {\n        console.error('Call Error:', error);\n    });<\/code><\/pre>\n\n\n\n<p>Replace <code>myFunction<\/code>, <code>param1<\/code>, <code>param2<\/code>, and <code>myAddress<\/code> as before.<\/p>\n\n\n\n<p>6. <strong>Handle Errors<\/strong>: Make sure to handle errors gracefully in case something goes wrong during the transaction or function call.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"example-sending-ether-and-receiving-value\"><span class=\"ez-toc-section\" id=\"Example_Sending_ether_and_receiving_value\"><\/span>Example: Sending ether and receiving value<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Let&#8217;s consider a simple example where we send ether to a smart contract and receive a value in return. Suppose we have a smart contract with a function <code>buyTokens()<\/code> that accepts ether and returns the corresponding number of tokens.<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>contract MyToken {\n    mapping(address => uint256) public balances;\n\n    function buyTokens() public payable returns (uint256) {\n        \/\/ Logic to calculate tokens\n        uint256 tokens = msg.value * 10; \/\/ Simplified for demonstration\n        balances&#91;msg.sender] += tokens;\n        return tokens;\n    }\n}<\/code><\/pre>\n\n\n\n<p>Now, let&#8217;s interact with this contract using Web3.js:<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:18px\"><code>\/\/ Send transaction to buy tokens\ncontract.methods.buyTokens()\n    .send({from: myAddress, value: web3.utils.toWei('1', 'ether')})\n    .on('receipt', (receipt) => {\n        console.log('Tokens Bought:', receipt.events.TokensBought.returnValues.tokens);\n    })\n    .on('error', (error) => {\n        console.error('Transaction Error:', error);\n    });<\/code><\/pre>\n\n\n\n<p>In this example, we&#8217;re sending 1 ether to the <code>buyTokens()<\/code> function and receiving the corresponding number of tokens in return.<\/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=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Receiving a value returned by a Solidity smart contract transacting function involves interacting with the Ethereum blockchain using Web3.js or similar libraries. You need to send a transaction, wait for it to be confirmed, and then fetch the return value using the <code>call()<\/code> method. By following these steps and handling errors properly, you can effectively interact with smart contracts and retrieve return values for further processing.<\/p>\n\n\n\n<p><strong>Try it out, ask us questions, and let us know 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":7475,"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,46,29],"class_list":["post-7473","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-answers","tag-blockchain","tag-solidity","tag-web3"],"_links":{"self":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7473","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=7473"}],"version-history":[{"count":2,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7473\/revisions"}],"predecessor-version":[{"id":7476,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7473\/revisions\/7476"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media\/7475"}],"wp:attachment":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media?parent=7473"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/categories?post=7473"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/tags?post=7473"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}