In this tutorial, we’ll guide you through Hedera’s Frictionless Airdrop flow, which streamlines token distribution while giving recipients greater control over the tokens they receive. Throughout the tutorial, you’ll work with four new transaction types designed to simplify the airdrop process and safeguard users' token holdings. Each transaction type plays a unique role in enabling frictionless, user-friendly airdrops.
Before diving into the step-by-step guide, here’s a quick overview of the transaction types you’ll encounter:
TokenAirdropTransaction: This transaction allows you to distribute tokens to multiple recipients in a single transaction, even if the receiving accounts haven’t pre-associated with the token. It also supports pending transfers when accounts don’t have the necessary token associations.
TokenClaimAirdropTransaction: When a recipient doesn’t have available token associations, this transaction allows them to claim their tokens from a pending airdrop, ensuring full control over which tokens they want to accept.
TokenRejectTransaction: If a user receives unwanted tokens, they can use this transaction to transfer them back to the token’s treasury without incurring any custom fees or royalties.
TokenCancelAirdropTransaction: This transaction allows the sender to cancel a pending airdrop if the recipient hasn’t claimed it yet. It gives the sender flexibility to manage unclaimed token transfers.
Now that we have a basic understanding of the transaction types, let’s move on to the step-by-step implementation of a Frictionless Airdrop on Hedera. The full code solution is provided at the end of the tutorial if you want to see it.
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.
In this tutorial, we would like to airdrop a fungible token, "GameGold," and a non-fungible token to our gaming community. We would like to send an equal amount of tokens to the top three players in our community without them knowing about the upcoming airdrop. Let's learn!
Step 1: Setup and Account Creation
First, we need to create the three accounts that will receive our airdrop and a treasury account. Each account will have a different configuration for automatic token association slots:
Alice: Unlimited token association slots by setting the value to -1 which means she can receive as many tokens as she wants, and they will be automatically associated with her account.
Bob: Only has 1 free token association slot.
Charlie: Has no free token association slots.
Treasury: This account will send the airdrop as it controls the treasury of our token collections.
The setup code imports the required functions from the Hedera SDK and the dotenv package to load the required environment variables. Further, it creates the accounts for Alice, Bob, and Charlie.
import { Client, PrivateKey, AccountId, AccountCreateTransaction, Hbar, NftId, TokenCreateTransaction, TokenType, TokenMintTransaction, AccountBalanceQuery, TokenAirdropTransaction, TokenClaimAirdropTransaction, TokenCancelAirdropTransaction, TokenRejectTransaction,} from"@hashgraph/sdk";import dotenv from"dotenv";dotenv.config();asyncfunctionmain() {if (process.env.MY_ACCOUNT_ID==null||process.env.MY_PRIVATE_KEY==null||process.env.HEDERA_NETWORK==null ) {thrownewError("Environment variables MY_ACCOUNT_ID, HEDERA_NETWORK, and MY_PRIVATE_KEY are required.", ); }constclient=Client.forName(process.env.HEDERA_NETWORK).setOperator(AccountId.fromString(process.env.MY_ACCOUNT_ID),PrivateKey.fromStringDer(process.env.MY_PRIVATE_KEY), );/** * Step 1: Create 4 accounts */constalicePrivateKey=PrivateKey.generateECDSA();constalicePublicKey=alicePrivateKey.publicKey;const { accountId: aliceId } =await (awaitnewAccountCreateTransaction().setKey(alicePublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(alicePublicKey.toEvmAddress()).setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(-1) // unlimited associations.execute(client) ).getReceipt(client);constbobPrivateKey=PrivateKey.generateECDSA();constbobPublicKey=bobPrivateKey.publicKey;const { accountId: bobId } =await (awaitnewAccountCreateTransaction().setKey(bobPublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(bobPublicKey.toEvmAddress()).setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(1) // 1 association.execute(client) ).getReceipt(client);constcharliePrivateKey=PrivateKey.generateECDSA();constcharliePublicKey=charliePrivateKey.publicKey;const { accountId: charlieId } =await (awaitnewAccountCreateTransaction().setKey(charliePublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(charliePublicKey.toEvmAddress()).setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(0) // no association slots.execute(client) ).getReceipt(client);// treasury account for tokensconsttreasuryKey=PrivateKey.generateECDSA();consttreasuryPublicKey=treasuryKey.publicKey;const { accountId: treasuryAccount } =await (awaitnewAccountCreateTransaction().setKey(treasuryPublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(treasuryPublicKey.toEvmAddress().setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(-1).execute(client) ).getReceipt(client);
Let's create a new token called "GameGold" that we will airdrop to our gaming community. We’ll mint 300 tokens in total and distribute them equally among our top three players, Alice, Bob, and Charlie, with each player receiving 100 tokens.
/** * Step 2: Create FT and NFT mint */constINITIAL_SUPPLY=300;consttokenCreateTx=awaitnewTokenCreateTransaction().setTokenName("GameGold").setTokenSymbol("GG").setDecimals(3).setInitialSupply(INITIAL_SUPPLY).setTreasuryAccountId(treasuryAccount).setAdminKey(client.operatorPublicKey).setFreezeKey(client.operatorPublicKey).setSupplyKey(client.operatorPublicKey).setMetadataKey(client.operatorPublicKey).setPauseKey(client.operatorPublicKey).freezeWith(client).sign(treasuryKey);const { tokenId } =await (awaittokenCreateTx.execute(client) ).getReceipt(client);
Ok, we are ready to airdrop the GameGold token to the top 3 players Alice, Bob, and Charlie. Each of them receives 100 tokens. The code should print one pending airdrop for Charlie because Alice and Bob had free token association slots. Only Charlie didn't have any free slots, so he had to claim the token himself.
/** * Step 3: Airdrop fungible tokens to 3 accounts */constAIRDROP_SUPPLY_PER_ACCOUNT=INITIAL_SUPPLY/3;constairdropRecord=await (await (awaitnewTokenAirdropTransaction().addTokenTransfer( tokenId, treasuryAccount,-AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, aliceId,AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, treasuryAccount,-AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, bobId,AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, treasuryAccount,-AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, charlieId,AIRDROP_SUPPLY_PER_ACCOUNT, ).freezeWith(client).sign(treasuryKey) ).execute(client) ).getRecord(client);// Get the transaction record and see the pending airdropsconst { newPendingAirdrops } = airdropRecord;console.log("Pending airdrop", newPendingAirdrops[0]);// Query to verify Alice and Bob have received the airdrops and Charlie has notlet aliceBalance =awaitnewAccountBalanceQuery().setAccountId(aliceId).execute(client);let bobBalance =awaitnewAccountBalanceQuery().setAccountId(bobId).execute(client);let charlieBalance =awaitnewAccountBalanceQuery().setAccountId(charlieId).execute(client);console.log("Alice balance after airdrop: ",aliceBalance.tokens.get(tokenId).toInt(), );console.log("Bob balance after airdrop: ",bobBalance.tokens.get(tokenId).toInt(), );console.log("Charlie balance after airdrop: ",charlieBalance.tokens.get(tokenId), );
The output we expect here is that Alice and Bob have received 100 units of our token, and the balance for Charlie shows null.
Step 4: Charlie Claims the Airdrop
Alright, Charlie still needs to claim his tokens. Let's do this first using the TokenClaimAirdropTransaction and verify its balance to ensure he has received the 100 units of our GameGold token.
/** * Step 4: Claim the airdrop for Charlie's account */console.log("Pending airdrop ID: ", newPendingAirdrops[0].airdropId);consttokenClaimTx=awaitnewTokenClaimAirdropTransaction().addPendingAirdropId(newPendingAirdrops[0].airdropId).freezeWith(client).sign(charliePrivateKey);consttokenClaimTxResponse=awaittokenClaimTx.execute(client);consttokenClaimTxReceipt=awaittokenClaimTxResponse.getReceipt(client);console.log(`Status of token claim airdrop transaction: ${tokenClaimTxReceipt.status.toString()}`, );constcharlieBalanceAfterClaim=awaitnewAccountBalanceQuery().setAccountId(charlieId).execute(client);console.log("Charlie balance after airdrop claim",charlieBalanceAfterClaim.tokens.get(tokenId).toInt(), );
We would like to airdrop Game NFTs to Alice, Bob, and Charlie in this step. Bob has already used his free association slot, and Charlie also doesn't have any free association slots. This part of the tutorial will teach you how to use the TokenCancelAirdropTransaction and TokenRejectTransaction.
First, we need to create the NFT collection and mint new NFts. Then, we can airdrop the NFTs. Two pending airdrops should be created for Bob and Charlie as they don't have free auto association slots available.
/** * Step 5: Airdrop the NFTs to Alice, Bob, and Charlie */constCID= ["QmNPCiNA3Dsu3K5FxDPMG5Q3fZRwVTg14EXA92uqEeSRXn","QmZ4dgAgt8owvnULxnKxNe8YqpavtVCXmc1Lt2XajFpJs9","QmPzY5GxevjyfMUF5vEAjtyRoigzWp47MiKAtLBduLMC1T","Qmd3kGgSrAwwSrhesYcY7K54f3qD7MDo38r7Po2dChtQx5","QmWgkKz3ozgqtnvbCLeh7EaR1H8u5Sshx3ZJzxkcrT3jbw", ];// Create Game NFTconst { tokenId: nftId } =await (await (awaitnewTokenCreateTransaction().setTokenName("Game NFT").setTokenSymbol("GNFT").setTokenType(TokenType.NonFungibleUnique).setTreasuryAccountId(treasuryAccount).setAdminKey(client.operatorPublicKey).setFreezeKey(client.operatorPublicKey).setSupplyKey(client.operatorPublicKey).setMetadataKey(client.operatorPublicKey).setPauseKey(client.operatorPublicKey).freezeWith(client).sign(treasuryKey) ).execute(client) ).getReceipt(client);let serialsNfts = [];for (let i =0; i <CID.length; i++) {const { serials } =await (awaitnewTokenMintTransaction().setTokenId(nftId).addMetadata(Buffer.from("-")).execute(client) ).getReceipt(client);serialsNfts.push(serials[0]); }// Airdrop NFTsconst { newPendingAirdrops: newPendingAirdropsNfts } =await (await (awaitnewTokenAirdropTransaction().addNftTransfer( nftId, serialsNfts[0], treasuryAccount, aliceId, ).addNftTransfer( nftId, serialsNfts[1], treasuryAccount, bobId, ).addNftTransfer( nftId, serialsNfts[2], treasuryAccount, charlieId, ).freezeWith(client).sign(treasuryKey) ).execute(client) ).getRecord(client);// Get the tx record and verify two pending airdrops (for Bob and Charlie)console.log("Pending airdrops length",newPendingAirdropsNfts.length);console.log("Pending airdrop for Bob:", newPendingAirdropsNfts[0]);console.log("Pending airdrop for Charlie:", newPendingAirdropsNfts[1]);
When airdropping the NFTs, we realized we made a mistake: Charlie is not actually our third-best player, but Greg is. To fix this, we need to cancel the pending airdrop to Charlie so that the NFT returns to our treasury account. Once the NFT is back, we can airdrop it to Greg, who is the rightful recipient. Let's learn how to use the TokenCancelAirdropTransaction to cancel an airdrop for a specific account.
/** * Step 6: Cancel the airdrop for Charlie * No signature is needed as the operator account is the admin of the token */awaitnewTokenCancelAirdropTransaction().addPendingAirdropId(newPendingAirdropsNfts[1].airdropId) // Charlie's airdrop.execute(client);
// Step 6: Cancel Airdrop for Charlie hedera.NewTokenCancelAirdropTransaction().AddPendingAirdropId(nftAirdropTxRecord.PendingAirdropRecords[1].GetPendingAirdropId()).Execute(client)
Step 7: Token Reject Already Received Airdrop
And lastly, as Charlie is not the rightful owner of the received fungible token, we've asked him if he wants to return the 100 units of our GameGold token. Charlie has agreed and can return the token without paying any fees or royalties using the TokenRejectTransaction.
The reject functionality can be used to return an already claimed or a successful airdrop into your account. It can't be used to reject a pending airdrop.
Here's the code for step 7. The rejected GameGold tokens will be returned to the treasury account.
/** * Step 7: Reject the fungible tokens for Charlie */await (await (awaitnewTokenRejectTransaction().setOwnerId(charlieId).addTokenId(tokenId).freezeWith(client).sign(charliePrivateKey) ).execute(client) ).getReceipt(client); charlieBalance =awaitnewAccountBalanceQuery().setAccountId(charlieId).execute(client);console.log("Charlie's balance after reject: ",charlieBalance.tokens.get(tokenId).toInt(), );client.close();}voidmain();
And that's it. The next section examines the fees for each of the parties involved a bit more thoroughly.
Concluding Notes on Transaction Costs
When working with Frictionless Airdrops on Hedera, it’s important to consider the transaction costs associated with each step. Here are some key points to keep in mind:
TokenAirdropTransaction Costs: The sender pays all fees for distributing tokens, including fees for token association and the first auto-renewal period for newly created associations. This makes it easier and less costly for recipients, as they don’t need to pre-associate tokens or cover those fees themselves.
TokenClaimAirdropTransaction Costs: When a recipient claims tokens from a pending airdrop, they only need to cover the transaction cost for claiming. The sender still covers token association costs, ensuring the user experience remains frictionless.
TokenRejectTransaction Costs: Rejecting unwanted tokens is free from custom fees or royalties. This ensures users can easily clean up their accounts without worrying about incurring additional costs for getting rid of spam or unwanted tokens.
TokenCancelAirdropTransaction Costs: Canceling a pending airdrop comes with a nominal fee for the sender, incentivizing mindful use of the airdrop system. It provides flexibility for managing unclaimed tokens but also discourages excessive or careless airdrops.
By understanding these costs and who is responsible for them, you can build efficient, user-friendly token distribution systems while maintaining cost efficiency for both developers and end-users.
import { Client, PrivateKey, AccountId, AccountCreateTransaction, Hbar, NftId, TokenCreateTransaction, TokenType, TokenMintTransaction, AccountBalanceQuery, TokenAirdropTransaction, TokenClaimAirdropTransaction, TokenCancelAirdropTransaction, TokenRejectTransaction,} from"@hashgraph/sdk";import dotenv from"dotenv";dotenv.config();asyncfunctionmain() {if (process.env.MY_ACCOUNT_ID==null||process.env.MY_PRIVATE_KEY==null||process.env.HEDERA_NETWORK==null ) {thrownewError("Environment variables MY_ACCOUNT_ID, HEDERA_NETWORK, and MY_PRIVATE_KEY are required.", ); }constclient=Client.forName(process.env.HEDERA_NETWORK).setOperator(AccountId.fromString(process.env.MY_ACCOUNT_ID),PrivateKey.fromStringDer(process.env.MY_PRIVATE_KEY), );/** * Step 1: Create 4 accounts */constalicePrivateKey=PrivateKey.generateECDSA();constalicePublicKey=alicePrivateKey.publicKey;const { accountId: aliceId } =await (awaitnewAccountCreateTransaction().setKey(alicePublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(alicePublicKey.toEvmAddress()).setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(-1) // unlimited associations.execute(client) ).getReceipt(client);constbobPrivateKey=PrivateKey.generateECDSA();constbobPublicKey=bobPrivateKey.publicKey;const { accountId: bobId } =await (awaitnewAccountCreateTransaction().setKey(bobPublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(alicePublicKey.toEvmAddress()).setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(1) // 1 association.execute(client) ).getReceipt(client);constcharliePrivateKey=PrivateKey.generateECDSA();constcharliePublicKey=charliePrivateKey.publicKey;const { accountId: charlieId } =await (awaitnewAccountCreateTransaction().setKey(charliePublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(charliePublicKey.toEvmAddress()).setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(0) // no association slots.execute(client) ).getReceipt(client);// treasury account for tokensconsttreasuryKey=PrivateKey.generateECDSA();consttreasuryPublicKey=treasuryKey.publicKey;const { accountId: treasuryAccount } =await (awaitnewAccountCreateTransaction().setKey(treasuryPublicKey)//Do NOT set an alias if you need to update/rotate keys in the future.setAlias(treasuryPublicKey.toEvmAddress()).setInitialBalance(newHbar(10)).setMaxAutomaticTokenAssociations(-1).execute(client) ).getReceipt(client);/** * Step 2: Create FT and NFT mint */constINITIAL_SUPPLY=300;consttokenCreateTx=awaitnewTokenCreateTransaction().setTokenName("GameGold").setTokenSymbol("GG").setDecimals(3).setInitialSupply(INITIAL_SUPPLY).setTreasuryAccountId(treasuryAccount).setAdminKey(client.operatorPublicKey).setFreezeKey(client.operatorPublicKey).setSupplyKey(client.operatorPublicKey).setMetadataKey(client.operatorPublicKey).setPauseKey(client.operatorPublicKey).freezeWith(client).sign(treasuryKey);const { tokenId } =await (awaittokenCreateTx.execute(client) ).getReceipt(client);/** * Step 3: Airdrop fungible tokens to 3 accounts */constAIRDROP_SUPPLY_PER_ACCOUNT=INITIAL_SUPPLY/3;constairdropRecord=await (await (awaitnewTokenAirdropTransaction().addTokenTransfer( tokenId, treasuryAccount,-AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, aliceId,AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, treasuryAccount,-AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, bobId,AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, treasuryAccount,-AIRDROP_SUPPLY_PER_ACCOUNT, ).addTokenTransfer( tokenId, charlieId,AIRDROP_SUPPLY_PER_ACCOUNT, ).freezeWith(client).sign(treasuryKey) ).execute(client) ).getRecord(client);// Get the transaction record and see the pending airdropsconst { newPendingAirdrops } = airdropRecord;console.log("Pending airdrop", newPendingAirdrops[0]);// Query to verify Alice and Bob have received the airdrops and Charlie has notlet aliceBalance =awaitnewAccountBalanceQuery().setAccountId(aliceId).execute(client);let bobBalance =awaitnewAccountBalanceQuery().setAccountId(bobId).execute(client);let charlieBalance =awaitnewAccountBalanceQuery().setAccountId(charlieId).execute(client);console.log("Alice balance after airdrop: ",aliceBalance.tokens.get(tokenId).toInt(), );console.log("Bob balance after airdrop: ",bobBalance.tokens.get(tokenId).toInt(), );console.log("Charlie balance after airdrop: ",charlieBalance.tokens.get(tokenId), );/** * Step 4: Claim the airdrop for Charlie's account */console.log("Pending airdrop ID: ", newPendingAirdrops[0].airdropId);consttokenClaimTx=awaitnewTokenClaimAirdropTransaction().addPendingAirdropId(newPendingAirdrops[0].airdropId).freezeWith(client).sign(charliePrivateKey);consttokenClaimTxResponse=awaittokenClaimTx.execute(client);consttokenClaimTxReceipt=awaittokenClaimTxResponse.getReceipt(client);console.log(`Status of token claim airdrop transaction: ${tokenClaimTxReceipt.status.toString()}`, );constcharlieBalanceAfterClaim=awaitnewAccountBalanceQuery().setAccountId(charlieId).execute(client);console.log("Charlie balance after airdrop claim",charlieBalanceAfterClaim.tokens.get(tokenId).toInt(), );/** * Step 5: Airdrop the NFTs to Alice, Bob, and Charlie */constCID= ["QmNPCiNA3Dsu3K5FxDPMG5Q3fZRwVTg14EXA92uqEeSRXn","QmZ4dgAgt8owvnULxnKxNe8YqpavtVCXmc1Lt2XajFpJs9","QmPzY5GxevjyfMUF5vEAjtyRoigzWp47MiKAtLBduLMC1T","Qmd3kGgSrAwwSrhesYcY7K54f3qD7MDo38r7Po2dChtQx5","QmWgkKz3ozgqtnvbCLeh7EaR1H8u5Sshx3ZJzxkcrT3jbw", ];// Create Game NFTconst { tokenId: nftId } =await (await (awaitnewTokenCreateTransaction().setTokenName("Game NFT").setTokenSymbol("GNFT").setTokenType(TokenType.NonFungibleUnique).setTreasuryAccountId(treasuryAccount).setAdminKey(client.operatorPublicKey).setFreezeKey(client.operatorPublicKey).setSupplyKey(client.operatorPublicKey).setMetadataKey(client.operatorPublicKey).setPauseKey(client.operatorPublicKey).freezeWith(client).sign(treasuryKey) ).execute(client) ).getReceipt(client);let serialsNfts = [];for (let i =0; i <CID.length; i++) {const { serials } =await (awaitnewTokenMintTransaction().setTokenId(nftId).addMetadata(Buffer.from("-")).execute(client) ).getReceipt(client);serialsNfts.push(serials[0]); }// Airdrop NFTsconst { newPendingAirdrops: newPendingAirdropsNfts } =await (await (awaitnewTokenAirdropTransaction().addNftTransfer( nftId, serialsNfts[0], treasuryAccount, aliceId, ).addNftTransfer( nftId, serialsNfts[1], treasuryAccount, bobId, ).addNftTransfer( nftId, serialsNfts[2], treasuryAccount, charlieId, ).freezeWith(client).sign(treasuryKey) ).execute(client) ).getRecord(client);// Get the tx record and verify two pending airdrops (for Bob and Charlie)console.log("Pending airdrops length",newPendingAirdropsNfts.length);console.log("Pending airdrop for Bob:", newPendingAirdropsNfts[0]);console.log("Pending airdrop for Charlie:", newPendingAirdropsNfts[1]);/** * Step 6: Cancel the airdrop for Charlie * No signature is needed as the operator account is the admin of the token */awaitnewTokenCancelAirdropTransaction().addPendingAirdropId(newPendingAirdropsNfts[1].airdropId) // Charlie's airdrop.execute(client);/** * Step 7: Reject the fungible tokens for Charlie */await (await (awaitnewTokenRejectTransaction().setOwnerId(charlieId).addTokenId(tokenId).freezeWith(client).sign(charliePrivateKey) ).execute(client) ).getReceipt(client); charlieBalance =awaitnewAccountBalanceQuery().setAccountId(charlieId).execute(client);console.log("Charlie balance after reject: ",charlieBalance.tokens.get(tokenId).toInt(), );client.close();}voidmain();