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.
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;
}
}
1. Create Accounts
Generate a private key for Alice. Hedera supports ED25519
and ECDSA
keys.
const aliceKey = PrivateKey.generateED25519();
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}`
);
- 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}`);
- 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}`);
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).
- Transfer 10 HBAR from Alice to contract: SUCCESS
4. Check the Balance of the Contract
Finally, use the function contractBalanceCheckerFcnto 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.