In use cases like DeFi, contracts often need to mint, burn, or transfer 0 units of a token due to integer rounding. The implementation of HIP-564 in release 0.31 of Hedera Services enables smart contract developers to specify a zero value for contract functions performing token operations.
The benefit is that transactions with 0 tokens go through successfully without having to implement if statements or qualification logic to check for 0 values. This also facilitates migrating existing applications to Hedera even more as the behavior when passing 0 tokens to contract functions is the same as that of other chains. Previously, passing 0 units of a token to a contract function was not possible. Those transactions would fail while reporting an invalid token amount.
In this article, you will learn how to pass zero token values to smart contract operations on Hedera.
Example: Transfer, Mint, and Wipe a Total of 0 Tokens
This example guides you through the following steps:
Creating an additional Hedera account (Alice), a contract, and a fungible HTS token
Executing a contract function to transfer 0 tokens from the contract to Alice
Executing a contract function to mint (or burn) 0 tokens
Executing a contract function to wipe 0 tokens
After completing all steps, your console should look something like this:
1. Create Accounts, Contract, and Fungible Token
There are four entities in this scenario: Operator, Alice, a contract, and a fungible HTS token. Your testnet credentials from the Hedera portal 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 a new account for Alice. Start by specifying the initial balance of the new account (initBalance) to be 10 HBAR
Generate and record the private key for the account. Hedera supports ED25519
and ECDSA
keys
Use the helper function accountCreateFcn
to create the new account
The function returns the status of the transaction (aliceSt) and the new account ID (aliceId)
The inputs are the newly generated private key (aliceKey), initBalance, and the client object
Output to the console a link to the mirror node explorer, HashScan, showing information about the new accounts
Deploy the contract ZeroTokenOperations
– see the Solidity code in the second tab.
Set the gas limit (gasLim) to be 4,000,000 and define the contract bytecode
Use ContractFunctionParameters()
from the SDK to specify the parameters for the contract constructor. Pass the Operator’s and Alice’s account IDs in Solidity format
Deploy the contract using the helper function contracts.deployContractFcn.
The function returns the contractId
in Hedera format and contractAddress in Solidity format
The inputs are the bytecode, constructorParams, gasLim, and client
Output to the console contractId and contractAddress
Create a fungible HTS token using the function contracts.executeContractPayableFcn
The function outputs the record for the token creation operation (tokenCreateRec)
The inputs are the contractId, the name of the contract function to execute (createHtsToken), gasLim, and client
Query a mirror node using the function queries.mirrorTxQueryFcn to get information from the network about the token creation transaction and a URL to check the transaction in HashScan
The query takes in the ID of the transaction, tokenCreateRec.transactionId
Output to the console the token ID and the HashScan URL for the transaction
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.5.0 <0.9.0;
pragma experimental ABIEncoderV2;
import "../hts-precompiles/ExpiryHelper.sol";
// To alter the behavior of the SolidityPrecompileExample, re-compile this solidity file
// (you will also need the other files in this directory)
// and copy the outputted json file to ./PrecompileExample.json
contract ZeroTokenOperations is ExpiryHelper {
address payable owner;
address payable aliceAccount;
address fungibleToken;
address nftToken;
constructor(address payable _owner, address payable _aliceAccount) {
owner = _owner;
aliceAccount = _aliceAccount;
}
// In order for some functions (such as createFungibleToken) to work, the contract must possess the funds for
// the function call. We are using ContractExecuteTransaction.setPayableAmount() to transfer some Hbar
// to the contract's account at each step (which means this function must be payable), and then transferring
// the excess Hbar back to the owner at the end of each step.
function createHtsToken() external payable returns (int responseCode) {
require(msg.sender == owner);
IHederaTokenService.TokenKey[]
memory keys = new IHederaTokenService.TokenKey[](1);
// Set the admin key, supply key, pause key, and freeze key to the key of the account that executed function (INHERIT_ACCOUNT_KEY).
keys[0] = createSingleKey(
ADMIN_KEY_TYPE |
SUPPLY_KEY_TYPE |
PAUSE_KEY_TYPE |
FREEZE_KEY_TYPE |
WIPE_KEY_TYPE,
INHERIT_ACCOUNT_KEY,
bytes("")
);
(responseCode, fungibleToken) = createFungibleToken(
IHederaTokenService.HederaToken(
"Example Fungible token", // name
"E", // symbol
address(this), // treasury
"memo",
true, // supply type, false -> INFINITE, true -> FINITE
1000, // max supply
false, // freeze default (setting to false means that this token will not be initially frozen on creation)
keys, // the keys for the new token
// auto-renew fee paid by aliceAccount every 7,000,000 seconds (approx. 81 days).
// This is the minimum auto renew period.
createAutoRenewExpiry(aliceAccount, 7000000)
),
100, // initial supply
0 // decimals
);
// send any excess Hbar back to the owner
owner.transfer(address(this).balance);
}
function associateHtsToken() external returns (int responseCode) {
require(msg.sender == owner);
responseCode = associateToken(aliceAccount, fungibleToken);
}
function transferHtsToken() external returns (int responseCode) {
require(msg.sender == owner);
responseCode = transferToken(
fungibleToken,
address(this), // sender
aliceAccount, // receiver
0 // amount to transfer
);
}
function mintHtsToken() external returns (int responseCode) {
require(msg.sender == owner);
uint64 newTotalSupply;
int64[] memory mintedSerials; // applicable to NFT tokens only
(responseCode, newTotalSupply, mintedSerials) = mintToken(
fungibleToken,
0, // amount (applicable to fungible tokens only)
new bytes[](0) // metadatas (applicable to NFT tokens only)
);
require(newTotalSupply == 100 + 0);
}
function burnHtsToken() external returns (int responseCode) {
require(msg.sender == owner);
uint64 newTotalSupply;
int64[] memory mintedSerials; // applicable to NFT tokens only
(responseCode, newTotalSupply) = burnToken(
fungibleToken,
0, // amount (applicable to fungible tokens only)
mintedSerials // metadatas (applicable to NFT tokens only)
);
require(newTotalSupply == 100 + 0);
}
function wipeHtsToken() external returns (int responseCode) {
require(msg.sender == owner);
responseCode = wipeTokenAccount(
fungibleToken,
aliceAccount, // owner of tokens to wipe from
0 // amount to transfer
);
}
}
Helper Functions
Using accountCreateFcn simplifies the account creation process and is reusable in case you need to create more accounts in the future. This function uses the AccountCreateTransaction()
class of the SDK. We’ll use this modular approach throughout the article.
Keep in mind that on Hedera an account and a token must be associated with each other before that account can transact the token. Notice that during creation, the account is set to have 10 automatic token associations. This way, no manual association is needed for the first 10 tokens the account wishes to transact. Visit this documentation page to learn more about token associations.
The function contracts.executeContractPayableFcn
uses ContractExecuteTransaction()
in the SDK to call the specified contract function. Note that specifying .setPayableAmount()
to 20 HBAR provides sufficient funds to the contract to complete some operations like creating a fungible HTS token.
Lastly, the helper function queries.mirrorTxQueryFcn gets transaction information for the mirror nodes. The function introduces a delay of 10 seconds to allow for the propagation of information to the mirror nodes. It then formats the transaction ID and performs string operations to return a mirror REST API query and a mirror node explorer URL.
2. Execute a Contract Function to Transfer 0 Tokens
From the Solidity code in the previous step, the fungible token created has an initial supply of 100 units and the contract is the treasury for the token.
Use the helper function contracts.executeContractFcn
to execute the contract function transferHtsToken
In the Solidity code, the contract function transferHtsToken
transfers 0 units of the token from the contract to Alice and the transaction still goes through successfully as expected
The helper function returns the record object of the transaction (transferFtRec), which is used to obtain the status and ID of the transaction
The inputs are the contract ID (contractId), the contract function to execute, gasLim, and client
Output to the console:
The status of the contract call
The mirror node explorer URL with more details about the transaction (after using the helper function queries.mirrorTxQueryFcn)
// STEP 2 ===================================
console.log(`\nSTEP 2 ===================================\n`);
console.log(`- Transferring zero tokens from contract to Alice...\n`);
const transferFtRec = await contracts.executeContractFcn(contractId, "transferHtsToken", gasLim, client);
console.log(`- Contract call for token transfer: ${transferFtRec.receipt.status} \n`);
const [transferFtInfo, transferExpUrl] = await queries.mirrorTxQueryFcn(transferFtRec.transactionId);
console.log(`- See details: ${transferExpUrl}`);
Helper Functions
The function contracts.executeContractFcn also uses ContractExecuteTransaction() in the SDK to call the specified contract function. However, this helper function does not set a payable amount of HBAR.
3. Execute a Contract Function to Mint or Burn 0 Tokens
In this step:
Use the helper function contracts.executeContractFcn
again to execute the contract function mintHtsToken (or burnHtsToken)
As seen in the Solidity code in the first step, this contract function adds (or removes) 0 units to the existing token supply and the transaction completes successfully as expected
The helper function returns the record object of the transaction (mintFtRec orburnFtRec)
Output to the console:
The status of the contract call
The mirror node explorer URL with more details about the transaction (after using the helper function queries.mirrorTxQueryFcn)
Use the helper function contracts.executeContractFcn
one more time to execute the contract function wipeHtsToken
As shown in the Solidity code, this contract function wipes 0 units of the fungible token from Alice’s account and the transaction completes successfully as expected
The helper function returns the record object of the transaction (wipeFtRec)
Output to the console:
The status of the contract call
The mirror node explorer URL with more details about the transaction (after using the helper function queries.mirrorTxQueryFcn)
Now you know how to perform contract actions with zero token units on Hedera using the JavaScript SDK and Solidity. You can try this example with the other officially supported SDKs for Java, Go, and Swift.
Keep in mind that zero token operations can also be performed with the SDK. For instance, a token transfer as follows completes successfully: