Hedera
  • Welcome to Hedera β€” let’s build the future
  • Getting Started
    • Environment Setup
    • Web2 Developers
      • Transfer HBAR
      • Create a Token
      • Create a Topic
    • EVM Developers
      • Deploy a Contract
  • Tutorials
    • Smart Contracts
      • How to Mint & Burn an ERC-721 Token Using Hardhat and Ethers (Part 1)
      • How to Set Access Control, a Token URI, Pause, and Transfer an ERC-721 Token Using Hardhat (Part 2)
      • How to Verify a Smart Contract on HashScan
      • Deploy a Smart Contract Using Remix
      • Deploy a Smart Contract Using Hardhat and Hiero JSON-RPC Relay
      • Deploy Your First Smart Contract
      • Deploy a Contract Using the Hedera Token Service
      • Send and Receive HBAR Using Solidity Smart Contracts
      • Deploy By Leveraging Ethereum Developer Tools On Hedera
      • Deploy a Subgraph Using The Graph and Hedera JSON-RPC Relay
      • Deploy Smart Contracts on Hedera Using Truffle
      • The Power of Native Hedera Tokens as ERC-20 Tokens: A step-by-step guide
      • HTS x EVM - Part 1: How to Mint NFTs
      • HTS x EVM - Part 2: KYC & Update
      • HTS x EVM - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Hedera Smart Contracts Workshop
        • Setup
        • Solidity
        • Hedera SDK JS
        • Hardhat and EthersJs
        • Outro
      • Foundry
        • How to Setup Foundry and Write a Basic Unit Test
        • How to Deploy and Verify a Hedera Smart Contract with Foundry
        • How to Test A Solidity Event
        • How to Fork Testnet on Latest Block
    • Consensus
      • Submit Your First Message
      • Submit Message to Private Topic
      • Query Messages with Mirror Node
    • Tokens
      • Create and Transfer Your First NFT
      • Create and Transfer Your First Fungible Token
      • Create and Transfer an NFT using a Solidity Contract
      • Structure Your Token Metadata Using JSON Schema V2
      • Hedera Token Service - Part 1: How to Mint NFTs
      • Hedera Token Service - Part 2: KYC, Update, and Scheduled Transactions
      • Hedera Token Service - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Create Your First Frictionless Airdrop Campaign
    • Local Node
      • How to Run Hedera Local Node in a Cloud Development Environment (CDE)
        • Run a Local Node in Gitpod
        • Run a Local Node in Codespaces
      • How to Set Up a Hedera Local Node
      • Set Up a Hedera Local Node using the NPM CLI
    • More Tutorials
      • Create and Fund Your Hedera Testnet Account
      • How to Create a Personal Access Token (API Key) on the Hedera Portal
      • How to Auto-Create Hedera Accounts with HBAR and Token Transfers
      • How to Configure a Mirror Node and Query Data
      • How to Generate a Random Number on Hedera
      • Get Started with the Hedera Consensus Service Fabric Plugin
        • Virtual Environment Setup
      • Schedule Your First Transaction
      • How to Connect to Hedera Networks Over RPC
        • Configuring Hashio RPC endpoints
        • Configuring Hiero JSON-RPC Relay endpoints
        • Configuring Validation Cloud RPC endpoints
      • JavaScript Testing
      • Create a Hedera DApp Integrated with WalletConnect
      • How to Connect MetaMask to Hedera
    • Demo Applications
    • Starter Projects
    • Building on Hedera (course)
  • Networks
    • Mainnet
      • Mainnet Accounts
      • Mainnet Consensus Nodes
        • Node Requirements
          • FAQ
      • Fees
        • Transaction Records
    • Testnets
      • Testnet Accounts
      • Testnet Consensus Nodes
    • Localnet
      • Single Node Configuration
      • Multinode Configuration
    • Network Explorers and Tools
    • Release Notes
      • Consensus Node
      • Hedera Mirror Node
  • Core Concepts
    • Accounts
      • Account Creation
      • Auto Account Creation
      • Account Properties
    • Keys and Signatures
    • Schedule Transaction
    • Smart Contracts
      • Understanding Hedera's EVM Differences and Compatibility
        • For EVM Developers Migrating to Hedera
          • Accounts, Signature Verification & Keys (ECDSA vs. ED25519)
          • JSON-RPC Relay and EVM Tooling
          • Token Management with Hedera Token Service
          • Decimal Handling (8 vs. 18 Decimals)
          • Handling HBAR Transfers in Contracts
        • For Hedera-Native Developers Adding Smart Contract Functionality
          • Integrating ED25519 Accounts and Advanced Features Into Smart Contracts
          • JSON-RPC Relay and State Queries
          • Extending Token Management with Smart Contracts
      • Creating Smart Contracts
      • Compiling Smart Contracts
      • System Smart Contracts
        • Hedera Account Service
        • Hedera Schedule Service
      • Gas and Fees
      • JSON-RPC Relay
      • Deploying Smart Contracts
      • Smart Contract Addresses
      • Verifying Smart Contracts
      • Smart Contract Traceability
      • Tokens Managed by Smart Contracts
        • ERC-20 (Fungible Tokens)
        • ERC-721 (Non-Fungible Token)
        • ERC-3643 Real World Assets (RWA)
        • ERC-1363 (Payable Tokens)
        • Hedera Token Service System Contract
      • Wrapped HBAR (WHBAR)
      • Smart Contract Rent
      • Smart Contract Security
      • EVM Archive Node Queries
    • Tokens
      • Tokenization on Hedera
      • Hedera Token Service (HTS) Native Tokenization
        • Token Types and ID Formats
        • Token Properties
        • Token Creation
        • Custom Fee Schedule
        • Token Airdrops
      • ERC/EVM-Compatible Tokenization
      • Hybrid (HTS + EVM ) Tokenization
    • Staking
      • Staking Program
      • Stake HBAR
    • Hashgraph Consensus Algorithm
      • Gossip About Gossip
      • Virtual Voting
    • Transactions and Queries
      • Transaction Properties
    • State and History
    • Mirror Nodes
      • Hedera Mirror Node
      • One Click Mirror Node Deployment
      • Run Your Own Mirror Node
        • Run Your Own Mirror Node with Google Cloud Storage (GCS)
        • Run Your Mirror Node with Amazon Web Services S3 (AWS)
  • Open Source Solutions and Integrations
    • AI Tools for Developers
      • Hedera AI Agent Kit
      • ElizaOS Plugin for Hedera
      • Hedera Hivemind
      • Kapa AI
    • Asset Tokenization Studio (ATS)
      • Web User Interface (UI)
      • Frequently Asked Questions (FAQs)
    • HashioDAO
      • Governance Token DAO
      • NFT DAO
      • Multisig DAO
      • DAO Proposals
      • Local Environment Setup
    • Hedera CLI
    • Hedera Custodians Library
      • How to use it
    • Hedera Developer Playground
    • Hedera Wallet Snap By MetaMask
      • Hedera Wallet Snap Documentation
      • Tutorial: MetaMask Snaps – What Are They and How to Use Them
    • Interoperability and Bridging
      • LayerZero
    • NFT Studio
      • Airdrop List Verifier
      • Metadata Validator
      • NFT Rarity Inspector
      • NFT Token Holders List Builder
      • NFT Risk Calculator
      • Token Balance Snapshot
      • Hedera NFT SDK
    • Oracle Networks
      • Chainlink Oracles
      • Pyth Oracles
      • Supra Oracles
    • Stablecoin Studio
      • Core Concepts
      • Web UI Application
      • CLI Management
      • TypeScript SDK
    • Hedera Guardian
    • Hedera WalletConnect
  • SDKs & APIs
    • SDKs
      • Build Your Hedera Client
      • Set Up Your Local Network
      • Network Address Book
      • Keys
        • Generate a new key pair
        • Import an existing key
        • Create a key list
        • Create a threshold key
        • Generate a mnemonic phrase
        • Recover keys from a mnemonic phrase
      • HBAR
      • Specialized Types
      • Pseudorandom Number Generator
      • Transactions
        • Create a Batch Transaction
        • Transaction ID
        • Modify transaction fields
        • Create an unsigned transaction
        • Manually sign a transaction
        • Submit a transaction
        • Sign a multisignature transaction
        • Get a transaction receipt
        • Get a transaction record
      • Schedule Transaction
        • Schedule ID
        • Create a schedule transaction
        • Sign a scheduled transaction
        • Delete a schedule transaction
        • Get schedule info
        • Network Response Messages
      • Queries
      • General Network Response Messages
      • Accounts and HBAR
        • Create an account
        • Update an account
        • Transfer cryptocurrency
        • Approve an allowance
        • Delete an allowance
        • Delete an account
        • Get account balance
        • Get account info
        • Network Response Messages
      • Consensus Service
        • Create a topic
        • Update a topic
        • Submit a message
        • Delete a topic
        • Get topic messages
        • Get topic info
        • Network Response
      • Token Service
        • Token ID
        • NFT ID
        • Token types
        • Create a token
        • Custom token fees
        • Update a token
        • Update token custom fees
        • Update NFT metadata
        • Transfer tokens
        • Airdrop a token
        • Claim a token
        • Cancel a token
        • Reject a token
        • Delete a token
        • Mint a token
        • Burn a token
        • Freeze an account
        • Unfreeze an account
        • Enable KYC account flag
        • Disable KYC account flag
        • Associate tokens to an account
        • Dissociate tokens from an account
        • Pause a token
        • Unpause a token
        • Wipe a token
        • Atomic swaps
        • Get account token balance
        • Get token info
        • Get NFT info
        • Network Response Messages
      • File Service
        • Create a file
        • Append to a file
        • Update a file
        • Delete a file
        • Get file contents
        • Get file info
        • Network Response Messages
      • Smart Contract Service
        • Delegate Contract ID
        • Create a smart contract
        • Update a smart contract
        • Delete a smart contract
        • Call a smart contract function
        • Ethereum transaction
        • Get a smart contract function
        • Get smart contract bytecode
        • Get smart contract info
        • Hedera Service Solidity Libraries
        • Network Response Messages
      • Signature Provider
        • Provider
        • Signer
        • Wallet
        • Local Provider
    • Mirror Node REST API
      • Accounts
      • Balances
      • Blocks
      • Schedule Transactions
      • Smart Contracts
      • Tokens
      • Topics
      • Transactions
      • Network
    • Hedera Consensus Service gRPC API
    • Hedera APIs
      • Basic Types
        • AccountAmount
        • AccountID
        • ContractID
        • CryptoAllowance
        • CurrentAndNextFeeSchedule
        • FeeComponents
        • FeeData
        • FeeSchedule
        • FileID
        • Fraction
        • HederaFunctionality
        • Key
        • KeyList
        • NftAllowance
        • NftTransfer
        • NodeAddress
        • NodeAddressBook
        • RealmID
        • ScheduleID
        • SemanticVersion
        • ServicesConfigurationList
        • ServiceEndpoint
        • Setting
        • ShardID
        • Signature
        • SignatureList
        • SignatureMap
        • SignaturePair
        • SubType
        • TransferList
        • TransactionID
        • ThresholdKey
        • ThresholdSignature
        • TokenAllowance
        • TokenBalance
        • TokenBalances
        • TokenFreezeStatus
        • TokenPauseStatus
        • TokenID
        • TokenKycStatus
        • TokenRelationship
        • TokenTransferList
        • TokenType
        • TokenSupplyType
        • TopicID
        • TransactionFeeSchedule
      • Cryptocurrency Accounts
        • CryptoService
        • CryptApproveAllowance
        • CryptoDeleteAllowance
        • CryptoCreate
        • CryptoTransfer
        • CryptoUpdate
        • CryptoDelete
        • CryptoGetAccountBalance
        • CryptoGetAccountRecords
        • CryptoGetInfo
        • CryptoGetStakers
      • Consensus Service
        • Consensus Service
        • ConsensusCreateTopic
        • ConsensusUpdateTopic
        • ConsensusSubmitMessage
        • ConsensusDeleteTopic
        • ConsensusTopicInfo
        • ConsensusGetTopicInfo
      • Schedule Service
        • ScheduleService
        • SchedulableTransactionBody
        • ScheduleCreate
        • ScheduleDelete
        • ScheduleSign
        • ScheduleGetInfo
      • Token Service
        • TokenService
        • CustomFees
          • AssessedCustomFee
          • CustomFee
          • FractionalFee
          • FixedFee
          • RoyaltyFee
        • TokenCreate
        • TokenUpdate
        • TokenFeeScheduleUpdate
        • TokenDelete
        • TokenMint
        • TokenBurn
        • TokenFreezeAccount
        • TokenUnfreezeAccount
        • TokenGrantKyc
        • TokenRevokeKyc
        • TokenAssociate
        • TokenDissociate
        • TokenWipeAccount
        • TokenPause
        • TokenUnpause
        • TokenGetInfo
        • TokenGetNftInfo
        • TokenGetNftInfos
        • TokenGetAccountNftInfo
      • File Service
        • FileService
        • FileCreate
        • FileAppend
        • FileUpdate
        • FileDelete
        • FileGetContents
        • FileGetInfo
      • Smart Contracts
        • SmartContractService
        • ContractCall
        • ContractCallLocal
        • ContractCreate
        • ContractUpdate
        • ContractDelete
        • ContractGetByteCode
        • ContractGetInfo
        • ContractGetRecords
      • Miscellaneous
        • Duration
        • ExchangeRate
        • Freeze
        • FreezeType
        • GetByKey
        • GetBySolidityID
        • NetworkGetVersionInfo
        • NetworkService
        • Query
        • QueryHeader
        • Response
        • ResponseCode
        • ResponseHeader
        • SystemDelete
        • SystemUndelete
        • TimeStamp
        • Transaction
        • TransactionBody
        • TransactionContents
        • TransactionGetFastRecord
        • TransactionGetReceipt
        • TransactionGetRecord
        • TransactionReceipt
        • TransactionRecord
        • TransactionResponse
        • UncheckedSubmit
    • Hedera Status API
  • Support & Community
    • Glossary
    • Contributing to Hedera documentation
      • Contribution Guidelines
        • Creating Issues
        • Creating Pull Requests
        • Hedera Improvement Proposal (HIP)
        • Submit Demo Applications
      • Style Guide
        • Understanding different types of documentation
        • Use of HBAR and tinybars
        • Use of web2 and web3
        • Language and grammar
        • Formatting
        • Punctuation
        • GitBook Markdown Syntax
    • Discord
    • GitHub
    • Stack Overflow
    • Hedera Blog
    • Bug Bounty
    • Hedera Help
    • Documentation Survey
    • Meetups
    • Brand Guidelines
    • Status Page
Powered by GitBook
LogoLogo

INTRODUCTION

  • Fees
  • Core Concepts
  • Network Information

TOOLS

  • Bridge
  • Oracles
  • Explorers
  • Developer Portal & Faucet

RESOURCES

  • Status
  • Bug Bounty
  • Build on Hedera (course)
  • Documentation Survey
On this page
  • Prerequisites
  • Table of Contents
  • Create Accounts and Deploy a Contract
  • Getting HBAR to the Contract
  • The _receive/fallback_** Functions**
  • Executing a Payable Function
  • Using _TransferTransaction_** in the SDK**
  • Getting HBAR from the Contract
  • Contract Transfers HBAR to Alice
  • Contract Sends HBAR to Alice
  • Contract Calls HBAR to Alice
  • Summary
  • Additional Resources

Was this helpful?

Edit on GitHub
  1. Tutorials
  2. Smart Contracts

Send and Receive HBAR Using Solidity Smart Contracts

PreviousDeploy a Contract Using the Hedera Token ServiceNextDeploy By Leveraging Ethereum Developer Tools On Hedera

Last updated 4 months ago

Was this helpful?

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.

Let’s learn how to send and receive HBAR to and from Hedera contracts. of the series focused on using the Hedera SDKs. This second part goes over transferring HBAR to and from contracts using Solidity.

Follow these main 3 steps:

  1. Create the Hedera accounts needed for testing and deploy a smart contract on the Testnet

  2. Move HBAR to the contract using fallback and receive functions, a payable function, and the SDK

  3. Move HBAR from the contract to Alice using the transfer, send, and call methods

Throughout the tutorial, you also learn how to check the HBAR balance of the contract by calling a function of the contract itself and by using the SDK query. The last step is to review the transaction history for the contract and the operator account in a mirror node explorer, like .


Prerequisites

We recommend you complete the following introduction to get a basic understanding of Hedera transactions. This example does not build upon the previous examples.

  • Get a .

  • Set up your environment .


Table of Contents


Create Accounts and Deploy a Contract

A portion of the application file (index.js) and the entire Solidity contract (hbarToAndFromContract.sol) are shown in the tabs below.

The Solidity file has functions for getting HBAR to the contract (receive, fallback, tokenAssociate), getting HBAR from the contract (transferHbar, sendHbar, callHbar), and checking the HBAR balance of the contract (getBalance).

This portion of index.js configures and creates the accounts, deploys the contract, and stores the HTS token ID. The functions accountCreatorFcn and contractDeployFcn create new accounts and deploy the contract to the network, respectively. These functions simplify the account creation and contract deployment process and are reusable in case you need them in the future. This modular approach is used throughout the tutorial.

// Configure accounts and client
const operatorId = AccountId.fromString(process.env.OPERATOR_ID);
const operatorKey = PrivateKey.fromString(process.env.OPERATOR_PVKEY);
const client = Client.forTestnet().setOperator(operatorId, operatorKey);

async function main() {
  // Create other necessary accounts
  console.log(`\n- Creating accounts...`);
  const initBalance = 100;
  const treasuryKey = PrivateKey.generateECDSA();
  const [treasuryAccSt, treasuryId] = await accountCreatorFcn(
    treasuryKey,
    initBalance
  );
  console.log(
    `- Created Treasury account ${treasuryId} that has a balance of ${initBalance} ℏ`
  );

  const aliceKey = PrivateKey.generateECDSA();
  const [aliceAccSt, aliceId] = await accountCreatorFcn(aliceKey, initBalance);
  console.log(
    `- Created Alice's account ${aliceId} that has a balance of ${initBalance} ℏ`
  );

  // Import the compiled contract bytecode
  const contractBytecode = fs.readFileSync("hbarToAndFromContract.bin");

  // Deploy the smart contract on Hedera
  console.log(`\n- Deploying contract...`);
  let gasLimit = 100000;

  const [contractId, contractAddress] = await contractDeployFcn(
    contractBytecode,
    gasLimit
  );
  console.log(`- The smart contract ID is: ${contractId}`);
  console.log(
    `- The smart contract ID in Solidity format is: ${contractAddress}`
  );

  const tokenId = AccountId.fromString("0.0.47931765");
  console.log(`\n- Token ID (for association with contract later): ${tokenId}`);
}

main();
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

// Compile with remix for remote imports to work - otherwise keep precompiles locally
import "https://github.com/hashgraph/hedera-smart-contracts/blob/main/contracts/system-contracts/hedera-token-service/HederaTokenService.sol";
import "https://github.com/hashgraph/hedera-smart-contracts/tree/main/contracts/system-contracts/HederaResponseCodes.sol";
 
contract hbarToAndFromContract is HederaTokenService{
    //============================================ 
    // GETTING HBAR TO THE CONTRACT
    //============================================ 
    receive() external payable {}

    fallback() external payable {}

    function tokenAssociate(address _account, address _htsToken) payable external {
        require(msg.value > 2000000000,"Send more HBAR");
        
        int response = HederaTokenService.associateToken(_account, _htsToken);
        if (response != HederaResponseCodes.SUCCESS) {
            revert ("Token association failed");
        }
    }
        
    //============================================ 
    // GETTING HBAR FROM THE CONTRACT
    //============================================ 
    function transferHbar(address payable _receiverAddress, uint _amount) public {
        _receiverAddress.transfer(_amount);
    }

    function sendHbar(address payable _receiverAddress, uint _amount) public {
        require(_receiverAddress.send(_amount), "Failed to send Hbar");
    }

    function callHbar(address payable _receiverAddress, uint _amount) public {
        (bool sent, ) = _receiverAddress.call{value:_amount}("");
        require(sent, "Failed to send Hbar");
    }
    
    //============================================ 
    // CHECKING THE HBAR BALANCE OF THE CONTRACT
    //============================================ 
    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
}

Helper Functions:

async function accountCreatorFcn(pvKey, iBal) {
    const response = await new AccountCreateTransaction()
        .setInitialBalance(new Hbar(iBal))
        .setKey(pvKey.publicKey)
        .execute(client);
    const receipt = await response.getReceipt(client);
    return [receipt.status, receipt.accountId];
}
async function contractDeployFcn(bytecode, gasLim) {
    const contractCreateTx = new ContractCreateFlow().setBytecode(bytecode).setGas(gasLim);
    const contractCreateSubmit = await contractCreateTx.execute(client);
    const contractCreateRx = await contractCreateSubmit.getReceipt(client);
    const contractId = contractCreateRx.contractId;
    const contractAddress = contractId.toSolidityAddress();
    return [contractId, contractAddress];
}
Console Output βœ…
  • Creating accounts...

  • Created Treasury account 0.0.47938602 that has a balance of 100 ℏ

  • Created Alice's account 0.0.47938603 that has a balance of 100 ℏ

  • Deploying contract...

  • The smart contract ID is: 0.0.47938605

  • The smart contract ID in Solidity format is: 0000000000000000000000000000000002db7c2d

  • Token ID (for association with contract later): 0.0.47931765


Getting HBAR to the Contract

The _receive/fallback_** Functions**

	console.log(`
====================================================
GETTING HBAR TO THE CONTRACT
====================================================`);

	// Transfer HBAR to the contract using .setPayableAmount WITHOUT specifying a function (fallback/receive triggered)
	let payableAmt = 10;
	console.log(`- Caller (Operator) PAYS ${payableAmt} ℏ to contract (fallback/receive)...`);
	const toContractRx = await contractExecuteNoFcn(contractId, gasLimit, payableAmt);

	// Get contract HBAR balance by calling the getBalance function in the contract AND/OR using ContractInfoQuery in the SDK
	await contractCallQueryFcn(contractId, gasLimit, "getBalance"); // Outputs the contract balance in the console

Helper Functions:

async function contractExecuteNoFcn(cId, gasLim, amountHbar) {
    const contractExecuteTx = new ContractExecuteTransaction()
        .setContractId(cId)
        .setGas(gasLim)
        .setPayableAmount(amountHbar);
    const contractExecuteSubmit = await contractExecuteTx.execute(client);
    const contractExecuteRx = await contractExecuteSubmit.getReceipt(client);
    return contractExecuteRx;
}
async function contractCallQueryFcn(cId, gasLim, fcnName) {
    const contractQueryTx = new ContractCallQuery()
        .setContractId(cId)
        .setGas(gasLim)
        .setFunction(fcnName);
    const contractQuerySubmit = await contractQueryTx.execute(client);
    const contractQueryResult = contractQuerySubmit.getUint256(0);
    console.log(`- Contract balance (getBalance fcn): ${contractQueryResult * 1e-8} ℏ`);
}
Console Output βœ…

====================================================

GETTING HBAR TO THE CONTRACT

====================================================

  • Caller (Operator) PAYS 10 ℏ to contract (fallback/receive)...

  • Contract balance (getBalance fcn): 10 ℏ

Executing a Payable Function

In this scenario, contractParamsBuilderFcn is used to build the parameters that will be passed to the contract function – that is, the contract and token IDs which are then converted to Solidity addresses.

From the Solidity code, note that the tokenAssociate function associates the contract to the HTS token from the first step, and requires more than 20 HBAR to execute (just for fun).

	// Transfer HBAR to the contract using .setPayableAmount SPECIFYING a contract function (tokenAssociate)
	payableAmt = 21;
	gasLimit = 800000;
	console.log(`\n- Caller (Operator) PAYS ${payableAmt} ℏ to contract (payable function)...`);
	const Params = await contractParamsBuilderFcn(contractId, [], 2, tokenId);
	const Rx = await contractExecuteFcn(contractId, gasLimit, "tokenAssociate", Params, payableAmt);

	gasLimit = 50000;
	await contractCallQueryFcn(contractId, gasLimit, "getBalance"); // Outputs the contract balance in the console
async function contractParamsBuilderFcn(aId, amountHbar, section, tId) {
    let builtParams = [];
    if (section === 2) {
        builtParams = new ContractFunctionParameters()
            .addAddress(aId.toSolidityAddress())
            .addAddress(tId.toSolidityAddress());
    } else if (section === 3) {
        builtParams = new ContractFunctionParameters()
            .addAddress(aId.toSolidityAddress())
            .addUint256(amountHbar * 1e8);
    } else {
    }
    return builtParams;
}
async function contractExecuteFcn(cId, gasLim, fcnName, params, amountHbar) {
    const contractExecuteTx = new ContractExecuteTransaction()
        .setContractId(cId)
        .setGas(gasLim)
        .setFunction(fcnName, params)
        .setPayableAmount(amountHbar);
    const contractExecuteSubmit = await contractExecuteTx.execute(client);
    const contractExecuteRx = await contractExecuteSubmit.getReceipt(client);
    return contractExecuteRx;
}
Console Output βœ…
  • Caller (Operator) PAYS 21 ℏ to contract (payable function)...

  • Contract balance (getBalance fcn): 31 ℏ

Using _TransferTransaction_** in the SDK**

	// Transfer HBAR from the Treasury to the contract deployed using the SDK
	let moveAmt = 30;
	const transferSdkRx = await hbar2ContractSdkFcn(treasuryId, contractId, moveAmt, treasuryKey);
	console.log(`\n- ${moveAmt} ℏ from Treasury to contract (via SDK): ${transferSdkRx.status}`);

	await contractCallQueryFcn(contractId, gasLimit, "getBalance"); // Outputs the contract balance in the console

Helper Functions:

async function hbar2ContractSdkFcn(sender, receiver, amount, pKey) {
    const transferTx = new TransferTransaction()
        .addHbarTransfer(sender, -amount)
        .addHbarTransfer(receiver, amount)
        .freezeWith(client);
    const transferSign = await transferTx.sign(pKey);
    const transferSubmit = await transferSign.execute(client);
    const transferRx = await transferSubmit.getReceipt(client);
    return transferRx;
}
Console Output βœ…
  • 30 ℏ from Treasury to contract (via SDK): SUCCESS

  • Contract balance (getBalance fcn): 61 ℏ


Getting HBAR from the Contract

In this section the contract transfers HBAR to Alice using three different methods: transfer, send, call. Each transfer is of 20 HBAR, so by the end the contract should have 1 HBAR left in its balance.

Contract Transfers HBAR to Alice

The helper function contractExecuteFcn executes the transferHbar function of the contract. The helper function contractParamsBuilderFcn now builds the contract function parameters from the receiver ID (Alice’s) and the amount of HBAR to be sent. Also note from the previous section that the contract function is executed with a gasLimit of only 50,000 gas.

	console.log(`
====================================================
GETTING HBAR FROM THE CONTRACT
====================================================`);

	payableAmt = 0;
	moveAmt = 20;

	console.log(`- Contract TRANSFERS ${moveAmt} ℏ to Alice...`);
	const tParams = await contractParamsBuilderFcn(aliceId, moveAmt, 3, []);
	const tRx = await contractExecuteFcn(contractId, gasLimit, "transferHbar", tParams, payableAmt);

	// Get contract HBAR balance by calling the getBalance function in the contract AND/OR using ContractInfoQuery in the SDK
	await showContractBalanceFcn(contractId); // Outputs the contract balance in the console

Helper Functions:

async function showContractBalanceFcn(cId) {
    const info = await new ContractInfoQuery().setContractId(cId).execute(client);
    console.log(`- Contract balance (ContractInfoQuery SDK): ${info.balance.toString()}`);
Console Output βœ…

====================================================

GETTING HBAR FROM THE CONTRACT

====================================================

  • Contract TRANSFERS 20 ℏ to Alice...

  • Contract balance (ContractInfoQuery SDK): 41 ℏ

Contract Sends HBAR to Alice

The same helper function from before now executes the sendHbar function of the contract.

	console.log(`\n- Contract SENDS ${moveAmt} ℏ to Alice...`);
	const sParams = await contractParamsBuilderFcn(aliceId, moveAmt, 3, []);
	const sRx = await contractExecuteFcn(contractId, gasLimit, "sendHbar", sParams, payableAmt);

	await showContractBalanceFcn(contractId); // Outputs the contract balance in the console
Console Output βœ…
  • Contract SENDS 20 ℏ to Alice...

  • Contract balance (ContractInfoQuery SDK): 21 ℏ

Contract Calls HBAR to Alice

Just like above, the helper function contractExecuteFcn executes the sendHbar function of the contract.

	console.log(`\n- Contract CALLS ${moveAmt} ℏ to Alice...`);
	const cParams = await contractParamsBuilderFcn(aliceId, moveAmt, 3, []);
	const cRx = await contractExecuteFcn(contractId, gasLimit, "callHbar", cParams, payableAmt);

	await showContractBalanceFcn(contractId); // Outputs the contract balance in the console

	console.log(`\n- SEE THE TRANSACTION HISTORY IN HASHSCAN (FOR CONTRACT AND OPERATOR): 
https://hashscan.io/#/testnet/contract/${contractId}
https://hashscan.io/#/testnet/account/${operatorId}`);

	console.log(`
====================================================
 THE END - NOW JOIN: https://hedera.com/discord
====================================================\n`);
}
Console Output βœ…
  • Contract CALLS 20 ℏ to Alice...

  • Contract balance (ContractInfoQuery SDK): 1 ℏ

  • SEE THE TRANSACTION HISTORY IN HASHSCAN (FOR CONTRACT AND OPERATOR):


Summary

If you run the entire example successfully, your console should look something like:


Additional Resources

This example involves 3 Hedera accounts, 1 contract, and 1 Hedera Token Service (HTS) token. The Operator account () is used to build the Hedera client to submit transactions to the Hedera network – that’s the first account. The Treasury and Alice are new accounts (created by the Operator) to represent additional parties in your test – those are the second and third accounts respectively.

These helper functions in index.js use the and classes of the Hedera SDK. stores the bytecode and deploys the contract on Hedera. This single call handles for you the operations , , and .

In this scenario, you (Operator) transfer 10 HBAR to the contract by triggering either the receive or fallback functions of the contract. As described in this page, the receive function is called when msg.data is empty, otherwise the fallback function is called.

In this case, the helper function contractExecuteNoFcn pays HBAR to the contract by using and specifying a .setPayableAmount() without calling any specific contract function – thus triggering fallback. Note from the Solidity code that receive and fallback are external and payable functions.

The helper function contractCallQueryFcn checks the HBAR balance of the contract by calling the getBalance function of the contract – this call is done using .

Now, you (Operator) transfer 21 HBAR to the contract by calling a specific contract function (tokenAssociate) that is payable using the class and specifying a .setPayableAmount(). This is done with the helper function contractExecuteFcn.

Lastly in this scenario, the Treasury transfers 30 HBAR to the contract using . This is done with the helper function hbar2ContractSdkFcn. This scenario is just a quick recap and reminder of , so be sure to give that a read for more details.

This tutorial focuses on implementation. For additional background and details of these Solidity methods, check out and – just remember that on Hedera, the native cryptocurrency transacted is HBAR, not ETH. One thing worth noting from those resources is that call is currently the recommended method to use.

Examine the transaction history for the contract and the operator in the mirror node explorer, . You can also obtain additional information of interest using the . Additional context for that API is provided in .

The last step is to

This tutorial used the Hedera JavaScript SDK. However, you can try this with the other officially supported for Java and Go.

Congratulations! πŸŽ‰ Now you know how to send HBAR to and from a contract on Hedera using both the SDK and Solidity! Feel free to reach out in if you have any questions!

➑

➑ Have a question? Ask on

your Testnet account credentials
AccountCreateTransaction()
ContractCreateFlow()
ContractCreateFlow()
FileCreateTransaction()
FileAppendTransaction()
ContractCreateTransaction()
Solidity by Example
ContractExecuteTransaction()
ContractCallQuery()
ContractExecuteTransaction()
TransferTransaction()
Part 1 of the series
Solidity by Example
this external article
HashScan
mirror node REST API
this blog post
join the Hedera Developer Discord!
https://hashscan.io/#/testnet/contract/0.0.47938605
https://hashscan.io/#/testnet/account/0.0.2520793
SDKs
Discord
Project Repository
StackOverflow
Part 1
HashScan
Hedera testnet account
here
Create Accounts and Deploy a Contract
Get HBAR to ➑ Contract
Get HBAR from β¬… Contract
Summary
Additional Resources

Writer: Ed, DevRel Engineer

Editor: Krystal, Technical Writer

|

|

GitHub
LinkedIn
GitHub
Hashnode