How to Send and Receive HBAR Using Smart Contracts – Part 1:… | Hedera Hedera Network Services Token Service Mint and configure tokens and accounts. Consensus Service Verifiable timestamps and ordering of events. Smart Contracts Run Solidity smart contracts. HBAR The Hedera network's native cryptocurrency. Insights How It Works Learn about Hedera from end to end. Explorers View live and historical data on Hedera. Dashboards Analyze network activity and metrics. Network Nodes Understand networks and node types. Devs Start Building Get Started Learn core concepts and build the future. Documentation Review the API and build using your favorite language. Developer Resources Integrations Plugins and microservices for Hedera. Fee Estimator Understand and estimate transaction costs. Open Source Hedera is committed to open, transparent code. Learning Center Learn about web3 and blockchain technologies. Grants Grants & accelerators for your project. Bounties Find bugs. Submit a report. Earn rewards. Ecosystem ECOSYSTEM Hedera Ecosystem Applications, developer tools, network explorers, and more. NFT Ecosystem Metrics Analyze on-chain and market NFT ecosystem metrics. CATEGORIES Web3 Applications Connect into the innovative startups decentralizing the web on Hedera. Enterprise Applications Learn about the Fortune 500 companies decentralizing the web on Hedera. Wallets & Custodians Create a Hedera account to manage HBAR, fungible tokens, and NFTs. Network Explorers Hedera mainnet and testnet graphical network explorers. Developer Tooling Third-party APIs, integrations, and plugins to build apps on Hedera. Grants & Accelerators Boost your project with support from the Hedera ecosystem. Partner Program Explore our partners to bring your vision into reality. Hedera Council Over 30 highly diversified organizations govern Hedera. Use Cases Hedera Solutions Asset Tokenization Studio Open source toolkit for tokenizing assets securely. Stablecoin Studio All-in-one toolkit for stablecoin solutions. Hedera Guardian Auditable carbon markets and traceability. Functional Use Cases Data Integrity & AI Reliable, secure, and ethically governed insights. Sustainability Enabling fair carbon markets with trust. Real-World Asset Tokenization Seamless tokenization of real-world assets and digital at scale. Consumer Engagement & Loyalty Mint, distribute, and redeem loyalty rewards. Decentralized Identity Maintain the lifecycle of credentials. Decentralized Logs Scalable, real-time timestamped events. DeFi Dapps built for the next-generation of finance. NFTs Low, fixed fees. Immutable royalties. Payments Scalable, real-time, and affordable crypto-payments. HBAR Overview Learn about Hedera's token, HBAR. Treasury Management Hedera’s report of the HBAR supply. Governance Decentralized Governance Hedera Council See the world's leading organizations that own Hedera. About Meet Hedera's Board of Directors and team. Journey Watch Hedera's journey to build an empowered digital future for all. Transparent Governance Public Policy Hedera's mission is to inform policy and regulation that impact the industry. Meeting Minutes Immutably recorded on Hedera. Roadmap Follow Hedera's roadmap in its journey to build the future. Resources Company What's New Partners Papers Careers Media Blog Technical Press Podcast Community Events Meetups Store Brand Navigation QUICKSTART How to Send and Receive HBAR Using Smart Contracts – Part 1: Using the SDK technical Jul 20, 2022 by Ed Marquez Head of Developer Relations Smart contracts on Hedera can hold and exchange value in the form of HBAR, Hedera Token Service (HTS) tokens, and even ERC tokens. This is fundamental for building decentralized applications that rely on contracts in areas like DeFi, ESG, NFT marketplaces, DAOs, and more. In this tutorial, you will learn how to send and receive HBAR to and from Hedera contracts. At a high level, there are two ways to transfer HBAR to and from a contract on Hedera: the SDKs and Solidity.  Part 1 focuses on using the Hedera SDKs. Read Part 2 for transferring HBAR to and from contracts using Solidity. Try It Yourself Get a Hedera testnet account Use this Codesandbox to try the example Fork the sandbox Remember to provide your testnet account credentials in the .env file Open a new terminal to execute index.js Get the example code from GitHub Transfer HBAR Using the SDKs Here are a few key points about transferring HBAR to and from contracts using the SDKs: For most, this is the simplest method as it only involves doing a TransferTransaction() Transferring HBAR to a contract: Does not require having: payable contracts or functions receive() or fallback() functions Keep in mind that if your contract has a fallback() function, this approach does not invoke it (so that code won’t execute) Transferring HBAR from a contract: The contract sending the HBAR must have an admin key to sign the TransferTransaction() Example This example has three entities: the operator, Alice, and the contract. Your testnet credentials should be used for the operator variables, which are used to initialize the Hedera client that submits transactions to the network and gets confirmations. Create Alice’s account with an initial balance of 100 HBAR, and then Alice will transfer 10 HBAR to the smart contract using the TransferTransaction() module in the SDK. Below is the Solidity code for the contract. You can get the bytecode from Codesandbox, the GitHub repository, or by compiling the code. // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract hbar2Contract{ function getBalance() public view returns (uint) { return address(this).balance; } } Copy 1. Create Accounts Generate a private key for Alice. Hedera supports ED25519 and ECDSA keys. const aliceKey = PrivateKey.generateECDSA(); Copy Create Alice’s account with a balance of 100 HBAR. The function accountCreatorFcn simplifies the account creation process and is reusable in case you need to create more accounts in the future. This function uses the AccountCreateTransaction() module. We’ll use this modular approach throughout the article. // Create additional accounts needed const initialBalance = 100; const [accStatus, aliceId] = await accountCreatorFcn(aliceKey, initialBalance); console.log( `\n- Created Alice's account with initial balance of ${initialBalance} hbar: ${accStatus}` ); Copy async function accountCreatorFcn(pvKey, iBal) { const response = await new AccountCreateTransaction() .setInitialBalance(new Hbar(iBal)) .setKey(pvKey.publicKey) .setAlias(pvKey.publicKey.toEvmAddress()) .execute(client); const receipt = await response.getReceipt(client); return [receipt.status, receipt.accountId]; } Copy Console Output: - Created Alice's account with initial balance of 100 hbar: SUCCESS 2. Deploy the Contract on Hedera The compiled contract bytecode is a binary contained in the variable contractBytecode. The function contractCreatorFcn uses the ContractCreateFlow() module and returns the contract ID and corresponding Solidity address for the contract. // Import the compiled contract bytecode const contractBytecode = fs.readFileSync("transferHbar2Contract_sdk_sol_hbar2Contract.bin"); // Deploy the contract on Hedera const [contractId, contractAddress] = await contractCreatorFcn(contractBytecode); console.log(`\n- The smart contract ID is: ${contractId}`); console.log(`- The smart contract ID in Solidity format is: ${contractAddress}`); Copy ContractCreateFlow() stores the bytecode and deploys the contract on Hedera. This single call handles for you the operations FileCreateTransaction(), FileAppendTransaction(), and ContractCreateTransaction(). Set a gas value that is enough to execute the transaction; otherwise, you'll get the error CONTRACT_REVERT_EXECUTED. async function contractCreatorFcn(contractBytecode) { const contractDeployTx = await new ContractCreateFlow() .setBytecode(contractBytecode) .setGas(100000) .execute(client); const contractDeployRx = await contractDeployTx.getReceipt(client); const contractId = contractDeployRx.contractId; const contractAddress = contractId.toSolidityAddress(); return [contractId, contractAddress]; } Copy Console Output: - The smart contract ID is: 0.0.47716894 - The smart contract ID in Solidity format is: 0000000000000000000000000000000002d81a1e 3. Transfer HBAR to the Contract Transfer 10 HBAR to the contract from Alice’s account using the function hbarTransferFcn. // Transfer HBAR to smart contract using TransferTransaction() const hbarAmount = 10; const transferRx = await hbarTransferFcn(aliceId, contractId, hbarAmount); console.log(`\n- Transfer ${hbarAmount} HBAR from Alice to contract: ${transferRx.status}`); Copy Use the TransferTransaction() module to transfer the HBAR. Remember that the account for which the balance is deducted must sign the transfer transaction (Alice in this case). async function hbarTransferFcn(sender, receiver, amount) { const transferTx = new TransferTransaction() .addHbarTransfer(sender, -amount) .addHbarTransfer(receiver, amount) .freezeWith(client); const transferSign = await transferTx.sign(aliceKey); const transferSubmit = await transferSign.execute(client); const transferRx = await transferSubmit.getReceipt(client); return transferRx; } Copy Console Output: - Transfer 10 HBAR from Alice to contract: SUCCESS 4. Check the Balance of the Contract Finally, use the function contractBalanceCheckerFcn to check the HBAR balance of the contract. This function checks the balance in two ways: 1) calling the getBalance function in the contract via a ContractCallQuery(), and 2) using the ContractInfoQuery() module of the SDK. // Query the contract balance const [fromCallQuery, fromInfoQuery] = await contractBalanceCheckerFcn(contractId); console.log(`\n- Contract balance (from getBalance fcn): ${fromCallQuery} tinybars`); console.log(`- Contract balance (from ContractInfoQuery): ${fromInfoQuery.balance.toString()}`); Copy async function contractBalanceCheckerFcn(contractId) { const contractQueryTx = new ContractCallQuery() .setContractId(contractId) .setGas(100000) .setFunction("getBalance"); const contractQuerySubmit = await contractQueryTx.execute(client); const contractQueryResult = contractQuerySubmit.getUint256(0); const cCheck = await new ContractInfoQuery().setContractId(contractId).execute(client); return [contractQueryResult, cCheck]; } Copy Console Output: - Contract balance (from getBalance fcn): 1000000000 tinybars - Contract balance (from ContractInfoQuery): 10 ℏ Summary Now you know how to send HBAR to a contract on Hedera using the TransferTransaction() module of the SDK. You can also send HBAR from a contract using the SDK. However, the contract sending the HBAR must have an admin key to sign the TransferTransaction(). For contracts without admin keys, be sure to read Part 2. There you’ll learn how to transfer HBAR to/from contracts using Solidity. Continue Learning Open a Testnet Account Try Examples and Tutorials Join the Developer Discord Read the Learning Center Share This Back to blog What is gRPC, gRPC-Web, and Proxies? Ed Marquez Pragmatic Blockchain Design Patterns – Integrating Blockchain into Business Processes Michiel Mulders Zero Cost EthereumTransaction on Success: Hedera's New Fee Model for Relay Operators Oliver Thorn Hedera Adopts Chainlink Standard for Cross-Chain Interoperability To Accelerate Ecosystem Adoption Hedera Team Hedera Developer Highlights March 2025 Michiel Mulders Hedera Release Cycle Overview Ed Marquez View All Posts Sign up for the newsletter CONNECT WITH US Transparency Open Source Audits & Standards Sustainability Commitment Carbon Offsets Governance Hedera Council Public Policy Treasury Management Meeting Minutes LLC Agreement Node Requirements Community Events Meetups HBAR Telegram Developer Discord Twitter Community Support FAQ Network Status Developer Discord StackOverflow Brand Brand Guidelines Built on Hedera Logo Hedera Store About Team Partners Journey Roadmap Careers Contact General Inquiry Public Relations © 2018-2025 Hedera Hashgraph, LLC. All trademarks and company names are the property of their respective owners. All rights in the Deutsche Telekom mark are protected by Deutsche Telekom AG. All rights reserved. Hedera uses the third party marks with permission. Terms of Use  |  Privacy Policy