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 Upgrade an ERC-721 Token with OpenZeppelin UUPS Proxies and Hardhat (Part 3)
      • 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 Studio on Hedera
      • ElizaOS Plugin for Hedera
      • Hedera AI Agent Kit
      • MCP Server
      • OpenConvAI
    • AI Tools for Developers
      • 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 Contract Builder
    • Hedera Custodians Library
      • How to use it
    • Hedera Developers Code Repository
    • 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
  • Summary
  • Prerequisites
  • Step 1: Setup and Account Creation
  • Step 2: Create a New Token
  • Step 3: Airdrop Tokens with Frictionless Airdrop
  • Step 4: Charlie Claims the Airdrop
  • Step 5: Airdrop NFTs to Alice, Bob, and Charlie
  • Step 6: Cancel Airdrop for Charlie
  • Step 7: Token Reject Already Received Airdrop
  • Concluding Notes on Transaction Costs
  • Code Check ✅
  • Additional Resources

Was this helpful?

Edit on GitHub
  1. Tutorials
  2. Tokens

Create Your First Frictionless Airdrop Campaign

PreviousHedera Token Service - Part 3: How to Pause, Freeze, Wipe, and Delete NFTsNextLocal Node

Last updated 4 months ago

Was this helpful?

Summary

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:

  • : 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.

  • : 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.

  • : 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.

  • : 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.

  • Get a .

  • Set up your environment .

  • .env file with this additional variable added:

    • HEDERA_NETWORK=testnet

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();

async function main() {
    if (
        process.env.MY_ACCOUNT_ID == null ||
        process.env.MY_PRIVATE_KEY == null ||
        process.env.HEDERA_NETWORK == null
    ) {
        throw new Error(
            "Environment variables MY_ACCOUNT_ID, HEDERA_NETWORK, and MY_PRIVATE_KEY are required.",
        );
    }

    const client = 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
     */
    const alicePrivateKey = PrivateKey.generateECDSA();
    const alicePublicKey = alicePrivateKey.publicKey;
    const { accountId: aliceId } = await (
        await new AccountCreateTransaction()
            .setKey(alicePublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(alicePublicKey.toEvmAddress())
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(-1) // unlimited associations
            .execute(client)
    ).getReceipt(client);

    const bobPrivateKey = PrivateKey.generateECDSA();
    const bobPublicKey = bobPrivateKey.publicKey;
    const { accountId: bobId } = await (
        await new AccountCreateTransaction()
            .setKey(bobPublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(bobPublicKey.toEvmAddress())
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(1) // 1 association
            .execute(client)
    ).getReceipt(client);

 
    const charliePrivateKey = PrivateKey.generateECDSA();
    const charliePublicKey = charliePrivateKey.publicKey;
    const { accountId: charlieId } = await (
        await new AccountCreateTransaction()
            .setKey(charliePublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(charliePublicKey.toEvmAddress())
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(0) // no association slots
            .execute(client)
    ).getReceipt(client);

    // treasury account for tokens
    const treasuryKey = PrivateKey.generateECDSA();
    const treasuryPublicKey = treasuryKey.publicKey;
    const { accountId: treasuryAccount } = await (
        await new AccountCreateTransaction()
            .setKey(treasuryPublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(treasuryPublicKey.toEvmAddress()
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(-1)
            .execute(client)
    ).getReceipt(client);
package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/hashgraph/hedera-sdk-go/v2"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load(".env")
	if err != nil {
		panic(fmt.Errorf("Unable to load environment variables from .env file. Error:\n%v\n", err))
	}

	myAccountId, err := hedera.AccountIDFromString(os.Getenv("MY_ACCOUNT_ID"))
	if err != nil {
		panic(err)
	}

	myPrivateKey, err := hedera.PrivateKeyFromString(os.Getenv("MY_PRIVATE_KEY"))
	if err != nil {
		panic(err)
	}

	client := hedera.ClientForTestnet()
	client.SetOperator(myAccountId, myPrivateKey)
	client.SetDefaultMaxTransactionFee(hedera.HbarFrom(100, hedera.HbarUnits.Hbar))
	client.SetDefaultMaxQueryPayment(hedera.HbarFrom(50, hedera.HbarUnits.Hbar))

	// Step 1: Create 4 accounts
	alicePrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Alice: %v", err)
	}
	aliceId := createAccount(client, alicePrivateKey, 10, -1) // Unlimited associations

	bobPrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Bob: %v", err)
	}
	bobId := createAccount(client, bobPrivateKey, 10, 1) // 1 association

	charliePrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Charlie: %v", err)
	}
	charlieId := createAccount(client, charliePrivateKey, 10, 0) // No associations

	treasuryPrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Treasury: %v", err)
	}
	treasuryAccount := createAccount(client, treasuryPrivateKey, 10, -1) // Unlimited associations

	fmt.Printf("Alice Account ID: %v\n", aliceId)
	fmt.Printf("Bob Account ID: %v\n", bobId)
	fmt.Printf("Charlie Account ID: %v\n", charlieId)
	fmt.Printf("Treasury Account ID: %v\n", treasuryAccount)
	// ...
}

// Helper function to generate a new Hedera account
func createAccount(client *hedera.Client, newAccountPrivateKey hedera.PrivateKey, initialBalance float64, maxAssociations int32) hedera.AccountID {
	newAccountPublicKey := newAccountPrivateKey.PublicKey()

	// Create the new account with the generated public key
	newAccountTx, err := hedera.NewAccountCreateTransaction().
		SetKey(newAccountPublicKey).
		SetInitialBalance(hedera.HbarFrom(initialBalance, hedera.HbarUnits.Hbar)).
		SetMaxAutomaticTokenAssociations(maxAssociations).
		Execute(client)

	if err != nil {
		log.Fatalf("Error creating new account: %v", err)
	}

	receipt, err := newAccountTx.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for account creation: %v", err)
	}

	newAccountId := *receipt.AccountID

	return newAccountId
}

Step 2: Create a New Token

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
     */
    const INITIAL_SUPPLY = 300;
    const tokenCreateTx = await new TokenCreateTransaction()
        .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 (
        await tokenCreateTx.execute(client)
    ).getReceipt(client);
	// Step 2: Create FT and mint
	tokenCreateTx, err := hedera.NewTokenCreateTransaction().
		SetTokenName("GameGold").
		SetTokenSymbol("GG").
		SetDecimals(3).
		SetInitialSupply(300).
		SetTreasuryAccountID(treasuryAccount).
		SetAdminKey(client.GetOperatorPublicKey()).
		SetFreezeKey(client.GetOperatorPublicKey()).
		SetSupplyKey(client.GetOperatorPublicKey()).
		SetMetadataKey(client.GetOperatorPublicKey()).
		FreezeWith(client)

	if err != nil {
		log.Fatalf("Error creating fungible token transaction: %v", err)
	}

	tokenCreateTxSigned := tokenCreateTx.Sign(treasuryPrivateKey)
	tokenCreateTxReceipt, err := tokenCreateTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing fungible token transaction: %v", err)
	}

	receipt, err := tokenCreateTxReceipt.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for fungible token: %v", err)
	}

	tokenId := *receipt.TokenID
	fmt.Printf("Created fungible token with ID: %v\n", tokenId.String())

Step 3: Airdrop Tokens with Frictionless Airdrop

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
     */
    const AIRDROP_SUPPLY_PER_ACCOUNT = INITIAL_SUPPLY / 3;
    const airdropRecord = await (
        await (
            await new TokenAirdropTransaction()
                .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 airdrops
    const { newPendingAirdrops } = airdropRecord;
    console.log("Pending airdrop", newPendingAirdrops[0]);

    // Query to verify Alice and Bob have received the airdrops and Charlie has not
    let aliceBalance = await new AccountBalanceQuery()
        .setAccountId(aliceId)
        .execute(client);

    let bobBalance = await new AccountBalanceQuery()
        .setAccountId(bobId)
        .execute(client);

    let charlieBalance = await new AccountBalanceQuery()
        .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 3: Airdrop 100 tokens each to 3 accounts
	airdropTx, err := hedera.NewTokenAirdropTransaction().
		AddTokenTransfer(tokenId, treasuryAccount, -100).
		AddTokenTransfer(tokenId, aliceId, 100).
		AddTokenTransfer(tokenId, treasuryAccount, -100).
		AddTokenTransfer(tokenId, bobId, 100).
		AddTokenTransfer(tokenId, treasuryAccount, -100).
		AddTokenTransfer(tokenId, charlieId, 100).
		FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating token airdrop transaction: %v", err)
	}

	airdropTxSigned := airdropTx.Sign(treasuryPrivateKey)
	airdropTxReceipt, err := airdropTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing token airdrop transaction: %v", err)
	}
	airdropTxRecord, err := airdropTxReceipt.GetRecord(client)
	if err != nil {
		log.Fatalf("Error getting record for token airdrop transaction: %v", err)
	}
	fmt.Println("Pending airdrop: ", airdropTxRecord.PendingAirdropRecords[0].String())
	fmt.Println("Airdropped fungible tokens")

	aliceBalance, _ := hedera.NewAccountBalanceQuery().SetAccountID(aliceId).Execute(client)
	fmt.Println("Alice's balance: ", aliceBalance.Tokens.Get(tokenId))
	bobBalance, _ := hedera.NewAccountBalanceQuery().SetAccountID(bobId).Execute(client)
	fmt.Println("Bob's balance: ", bobBalance.Tokens.Get(tokenId))
	charlieBalance, _ := hedera.NewAccountBalanceQuery().SetAccountID(charlieId).Execute(client)
	fmt.Println("Charlie's balance: ", 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);
    const tokenClaimTx = await new TokenClaimAirdropTransaction()
        .addPendingAirdropId(newPendingAirdrops[0].airdropId)
        .freezeWith(client)
        .sign(charliePrivateKey);
    const tokenClaimTxResponse = await tokenClaimTx.execute(client);
    const tokenClaimTxReceipt = await tokenClaimTxResponse.getReceipt(client);

    console.log(
        `Status of token claim airdrop transaction: ${tokenClaimTxReceipt.status.toString()}`,
    );

    const charlieBalanceAfterClaim = await new AccountBalanceQuery()
        .setAccountId(charlieId)
        .execute(client);

    console.log(
        "Charlie balance after airdrop claim",
        charlieBalanceAfterClaim.tokens.get(tokenId).toInt(),
    );
	// Step 4: Claim the airdrop for Charlie's account
	tokenClaimTx, err := hedera.NewTokenClaimAirdropTransaction().AddPendingAirdropId(airdropTxRecord.PendingAirdropRecords[0].GetPendingAirdropId()).FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating token claim airdrop transaction: %v", err)
	}
	tokenClaimTxSigned := tokenClaimTx.Sign(charliePrivateKey)

	_, err = tokenClaimTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing token claim airdrop transaction: %v", err)
	}
	fmt.Println("Claimed airdrop for Charlie's account")
	time.Sleep(4 * time.Second)
	charlieBalance, _ = hedera.NewAccountBalanceQuery().SetAccountID(charlieId).Execute(client)
	fmt.Println("Charlie's balance: ", charlieBalance.Tokens.Get(tokenId))

Step 5: Airdrop NFTs to Alice, Bob, and Charlie

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
     */
   const CID = [
        "QmNPCiNA3Dsu3K5FxDPMG5Q3fZRwVTg14EXA92uqEeSRXn",
        "QmZ4dgAgt8owvnULxnKxNe8YqpavtVCXmc1Lt2XajFpJs9",
        "QmPzY5GxevjyfMUF5vEAjtyRoigzWp47MiKAtLBduLMC1T",
        "Qmd3kGgSrAwwSrhesYcY7K54f3qD7MDo38r7Po2dChtQx5",
        "QmWgkKz3ozgqtnvbCLeh7EaR1H8u5Sshx3ZJzxkcrT3jbw",
    ];
    
    // Create Game NFT
    const { tokenId: nftId } = await (
        await (
            await new TokenCreateTransaction()
                .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 (
            await new TokenMintTransaction()
                .setTokenId(nftId)
                .addMetadata(Buffer.from("-"))
                .execute(client)
        ).getReceipt(client);

        serialsNfts.push(serials[0]);
    }
    
    // Airdrop NFTs
    const { newPendingAirdrops: newPendingAirdropsNfts } = await (
        await (
            await new TokenAirdropTransaction()
                .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 5: Airdrop the NFTs to Alice, Bob, and Charlie
	CID := [][]byte{
		[]byte("ipfs://bafyreiao6ajgsfji6qsgbqwdtjdu5gmul7tv2v3pd6kjgcw5o65b2ogst4/metadata.json"),
		[]byte("ipfs://bafyreic463uarchq4mlufp7pvfkfut7zeqsqmn3b2x3jjxwcjqx6b5pk7q/metadata.json"),
		[]byte("ipfs://bafyreihhja55q6h2rijscl3gra7a3ntiroyglz45z5wlyxdzs6kjh2dinu/metadata.json"),
		[]byte("ipfs://bafyreidb23oehkttjbff3gdi4vz7mjijcxjyxadwg32pngod4huozcwphu/metadata.json"),
		[]byte("ipfs://bafyreie7ftl6erd5etz5gscfwfiwjmht3b52cevdrf7hjwxx5ddns7zneu/metadata.json"),
	}
	nftCreate, err := hedera.NewTokenCreateTransaction().
		SetTokenName("Game NFT").
		SetTokenSymbol("GNFT").
		SetTokenType(hedera.TokenTypeNonFungibleUnique).
		SetTreasuryAccountID(treasuryAccount).
		SetSupplyKey(client.GetOperatorPublicKey()).
		SetAdminKey(client.GetOperatorPublicKey()).
		FreezeWith(client)

	nftCreateTxSign := nftCreate.Sign(treasuryPrivateKey)
	nftCreateSubmit, err := nftCreateTxSign.Execute(client)
	if err != nil {
		log.Fatalf("Error creating NFT: %v", err)
	}

	nftCreateReceipt, err := nftCreateSubmit.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for NFT creation: %v", err)
	}

	fmt.Println("Created NFT with ID: 0.0.", nftCreateReceipt.TokenID.Token)
	nftId := *nftCreateReceipt.TokenID
	var serialsNfts []int64
	mintTx, _ := hedera.NewTokenMintTransaction().
		SetTokenID(nftId).
		SetMetadatas(CID).
		FreezeWith(client)
	mintTxSign := mintTx.Sign(treasuryPrivateKey)
	mintTxSubmit, err := mintTxSign.Execute(client)
	if err != nil {
		log.Fatalf("Error minting NFTs: %v", err)
	}
	mintTxReceipt, err := mintTxSubmit.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for NFT minting: %v", err)
	}
	serialsNfts = mintTxReceipt.SerialNumbers
	fmt.Printf("Minted NFT serial numbers: %v\n", serialsNfts)

	// Airdrop NFTs
	nftAirdropTx, err := hedera.NewTokenAirdropTransaction().
		AddNftTransfer(hedera.NftID{TokenID: nftId, SerialNumber: 1}, treasuryAccount, aliceId).
		AddNftTransfer(hedera.NftID{TokenID: nftId, SerialNumber: 2}, treasuryAccount, bobId).
		AddNftTransfer(hedera.NftID{TokenID: nftId, SerialNumber: 3}, treasuryAccount, charlieId).
		FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating NFT airdrop transaction: %v", err)
	}

	nftAirdropTxSigned := nftAirdropTx.Sign(treasuryPrivateKey)
	nftAirdropTxSubmit, err := nftAirdropTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing NFT airdrop transaction: %v", err)
	}
	nftAirdropTxRecord, err := nftAirdropTxSubmit.GetRecord(client)
	if err != nil {
		log.Fatalf("Error getting record for NFT airdrop transaction: %v", err)
	}
	fmt.Println("Pending airdrops length: ", len(nftAirdropTxRecord.PendingAirdropRecords))
	fmt.Println("Pending airdrop for Bob: ", nftAirdropTxRecord.PendingAirdropRecords[0].String())
	fmt.Println("Pending airdrop for Charlie: ", nftAirdropTxRecord.PendingAirdropRecords[1].String())

Step 6: Cancel Airdrop for Charlie

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
     */
    await new TokenCancelAirdropTransaction()
        .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 (
            await new TokenRejectTransaction()
                .setOwnerId(charlieId)
                .addTokenId(tokenId)
                .freezeWith(client)
                .sign(charliePrivateKey)
        ).execute(client)
    ).getReceipt(client);

    charlieBalance = await new AccountBalanceQuery()
        .setAccountId(charlieId)
        .execute(client);

    console.log(
        "Charlie's balance after reject: ",
        charlieBalance.tokens.get(tokenId).toInt(),
    );
    
    client.close();
}

void main();
	// Step 7: Reject the fungible tokens for Charlie
	tokenRejectTx, err := hedera.NewTokenRejectTransaction().
		AddTokenID(tokenId).
		SetOwnerID(charlieId).
		FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating token reject transaction: %v", err)
	}
	tokenRejectTxSigned := tokenRejectTx.Sign(charliePrivateKey)
	_, err = tokenRejectTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing token reject transaction: %v", err)
	}
	fmt.Println("Rejected fungible tokens for Charlie")

	time.Sleep(4 * time.Second)
	charlieBalance, _ = hedera.NewAccountBalanceQuery().SetAccountID(charlieId).Execute(client)
	fmt.Println("Charlie's balance: ", charlieBalance.Tokens.Get(tokenId))
	client.Close()
}

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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

.env file example
MY_ACCOUNT_ID=0.0.1234
MY_PRIVATE_KEY=302e020100300506032b657004220420ed5a93073.....
HEDERA_NETWORK=testnet
JavaScript
import {
    Client, PrivateKey, AccountId, AccountCreateTransaction, Hbar, NftId, 
    TokenCreateTransaction, TokenType, TokenMintTransaction, AccountBalanceQuery,
    TokenAirdropTransaction,
    TokenClaimAirdropTransaction,
    TokenCancelAirdropTransaction,
    TokenRejectTransaction,
} from "@hashgraph/sdk";

import dotenv from "dotenv";
dotenv.config();

async function main() {
    if (
        process.env.MY_ACCOUNT_ID == null ||
        process.env.MY_PRIVATE_KEY == null ||
        process.env.HEDERA_NETWORK == null
    ) {
        throw new Error(
            "Environment variables MY_ACCOUNT_ID, HEDERA_NETWORK, and MY_PRIVATE_KEY are required.",
        );
    }

    const client = 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
     */
    const alicePrivateKey = PrivateKey.generateECDSA();
    const alicePublicKey = alicePrivateKey.publicKey;
    const { accountId: aliceId } = await (
        await new AccountCreateTransaction()
            .setKey(alicePublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(alicePublicKey.toEvmAddress())
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(-1) // unlimited associations
            .execute(client)
    ).getReceipt(client);

    const bobPrivateKey = PrivateKey.generateECDSA();
    const bobPublicKey = bobPrivateKey.publicKey;
    const { accountId: bobId } = await (
        await new AccountCreateTransaction()
            .setKey(bobPublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(alicePublicKey.toEvmAddress())
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(1) // 1 association
            .execute(client)
    ).getReceipt(client);

 
    const charliePrivateKey = PrivateKey.generateECDSA();
    const charliePublicKey = charliePrivateKey.publicKey;
    const { accountId: charlieId } = await (
        await new AccountCreateTransaction()
            .setKey(charliePublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(charliePublicKey.toEvmAddress())
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(0) // no association slots
            .execute(client)
    ).getReceipt(client);

    // treasury account for tokens
    const treasuryKey = PrivateKey.generateECDSA();
    const treasuryPublicKey = treasuryKey.publicKey;
    const { accountId: treasuryAccount } = await (
        await new AccountCreateTransaction()
            .setKey(treasuryPublicKey)
            //Do NOT set an alias if you need to update/rotate keys in the future
            .setAlias(treasuryPublicKey.toEvmAddress())
            .setInitialBalance(new Hbar(10))
            .setMaxAutomaticTokenAssociations(-1)
            .execute(client)
    ).getReceipt(client);
    
    /**
     * Step 2: Create FT and NFT mint
     */
    const INITIAL_SUPPLY = 300;
    const tokenCreateTx = await new TokenCreateTransaction()
        .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 (
        await tokenCreateTx.execute(client)
    ).getReceipt(client);
    
    /**
     * Step 3: Airdrop fungible tokens to 3 accounts
     */
    const AIRDROP_SUPPLY_PER_ACCOUNT = INITIAL_SUPPLY / 3;
    const airdropRecord = await (
        await (
            await new TokenAirdropTransaction()
                .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 airdrops
    const { newPendingAirdrops } = airdropRecord;
    console.log("Pending airdrop", newPendingAirdrops[0]);

    // Query to verify Alice and Bob have received the airdrops and Charlie has not
    let aliceBalance = await new AccountBalanceQuery()
        .setAccountId(aliceId)
        .execute(client);

    let bobBalance = await new AccountBalanceQuery()
        .setAccountId(bobId)
        .execute(client);

    let charlieBalance = await new AccountBalanceQuery()
        .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);
    const tokenClaimTx = await new TokenClaimAirdropTransaction()
        .addPendingAirdropId(newPendingAirdrops[0].airdropId)
        .freezeWith(client)
        .sign(charliePrivateKey);
    const tokenClaimTxResponse = await tokenClaimTx.execute(client);
    const tokenClaimTxReceipt = await tokenClaimTxResponse.getReceipt(client);

    console.log(
        `Status of token claim airdrop transaction: ${tokenClaimTxReceipt.status.toString()}`,
    );

    const charlieBalanceAfterClaim = await new AccountBalanceQuery()
        .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
     */
    const CID = [
        "QmNPCiNA3Dsu3K5FxDPMG5Q3fZRwVTg14EXA92uqEeSRXn",
        "QmZ4dgAgt8owvnULxnKxNe8YqpavtVCXmc1Lt2XajFpJs9",
        "QmPzY5GxevjyfMUF5vEAjtyRoigzWp47MiKAtLBduLMC1T",
        "Qmd3kGgSrAwwSrhesYcY7K54f3qD7MDo38r7Po2dChtQx5",
        "QmWgkKz3ozgqtnvbCLeh7EaR1H8u5Sshx3ZJzxkcrT3jbw",
    ];
    
    // Create Game NFT
    const { tokenId: nftId } = await (
        await (
            await new TokenCreateTransaction()
                .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 (
            await new TokenMintTransaction()
                .setTokenId(nftId)
                .addMetadata(Buffer.from("-"))
                .execute(client)
        ).getReceipt(client);

        serialsNfts.push(serials[0]);
    }
    
    // Airdrop NFTs
    const { newPendingAirdrops: newPendingAirdropsNfts } = await (
        await (
            await new TokenAirdropTransaction()
                .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
     */
    await new TokenCancelAirdropTransaction()
        .addPendingAirdropId(newPendingAirdropsNfts[1].airdropId) // Charlie's airdrop
        .execute(client);
        
    /**
     * Step 7: Reject the fungible tokens for Charlie
     */
    await (
        await (
            await new TokenRejectTransaction()
                .setOwnerId(charlieId)
                .addTokenId(tokenId)
                .freezeWith(client)
                .sign(charliePrivateKey)
        ).execute(client)
    ).getReceipt(client);

    charlieBalance = await new AccountBalanceQuery()
        .setAccountId(charlieId)
        .execute(client);

    console.log(
        "Charlie balance after reject: ",
        charlieBalance.tokens.get(tokenId).toInt(),
    );

    client.close();
}

void main();
Go
package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/hashgraph/hedera-sdk-go/v2"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load(".env")
	if err != nil {
		panic(fmt.Errorf("Unable to load environment variables from .env file. Error:\n%v\n", err))
	}

	myAccountId, err := hedera.AccountIDFromString(os.Getenv("MY_ACCOUNT_ID"))
	if err != nil {
		panic(err)
	}

	myPrivateKey, err := hedera.PrivateKeyFromString(os.Getenv("MY_PRIVATE_KEY"))
	if err != nil {
		panic(err)
	}

	client := hedera.ClientForTestnet()
	client.SetOperator(myAccountId, myPrivateKey)
	client.SetDefaultMaxTransactionFee(hedera.HbarFrom(100, hedera.HbarUnits.Hbar))
	client.SetDefaultMaxQueryPayment(hedera.HbarFrom(50, hedera.HbarUnits.Hbar))

	// Step 1: Create 4 accounts
	alicePrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Alice: %v", err)
	}
	aliceId := createAccount(client, alicePrivateKey, 10, -1) // Unlimited associations

	bobPrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Bob: %v", err)
	}
	bobId := createAccount(client, bobPrivateKey, 10, 1) // 1 association

	charliePrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Charlie: %v", err)
	}
	charlieId := createAccount(client, charliePrivateKey, 10, 0) // No associations

	treasuryPrivateKey, err := hedera.PrivateKeyGenerateEcdsa()
	if err != nil {
		log.Fatalf("Error generating private key for Treasury: %v", err)
	}
	treasuryAccount := createAccount(client, treasuryPrivateKey, 10, -1) // Unlimited associations

	fmt.Printf("Alice Account ID: %v\n", aliceId)
	fmt.Printf("Bob Account ID: %v\n", bobId)
	fmt.Printf("Charlie Account ID: %v\n", charlieId)
	fmt.Printf("Treasury Account ID: %v\n", treasuryAccount)

	// Step 2: Create FT and mint
	tokenCreateTx, err := hedera.NewTokenCreateTransaction().
		SetTokenName("GameGold").
		SetTokenSymbol("GG").
		SetDecimals(3).
		SetInitialSupply(300).
		SetTreasuryAccountID(treasuryAccount).
		SetAdminKey(client.GetOperatorPublicKey()).
		SetFreezeKey(client.GetOperatorPublicKey()).
		SetSupplyKey(client.GetOperatorPublicKey()).
		SetMetadataKey(client.GetOperatorPublicKey()).
		FreezeWith(client)

	if err != nil {
		log.Fatalf("Error creating fungible token transaction: %v", err)
	}

	tokenCreateTxSigned := tokenCreateTx.Sign(treasuryPrivateKey)
	tokenCreateTxReceipt, err := tokenCreateTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing fungible token transaction: %v", err)
	}

	receipt, err := tokenCreateTxReceipt.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for fungible token: %v", err)
	}

	tokenId := *receipt.TokenID
	fmt.Printf("Created fungible token with ID: %v\n", tokenId.String())

	// Step 3: Airdrop 100 tokens each to 3 accounts
	airdropTx, err := hedera.NewTokenAirdropTransaction().
		AddTokenTransfer(tokenId, treasuryAccount, -100).
		AddTokenTransfer(tokenId, aliceId, 100).
		AddTokenTransfer(tokenId, treasuryAccount, -100).
		AddTokenTransfer(tokenId, bobId, 100).
		AddTokenTransfer(tokenId, treasuryAccount, -100).
		AddTokenTransfer(tokenId, charlieId, 100).
		FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating token airdrop transaction: %v", err)
	}

	airdropTxSigned := airdropTx.Sign(treasuryPrivateKey)
	airdropTxReceipt, err := airdropTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing token airdrop transaction: %v", err)
	}
	airdropTxRecord, err := airdropTxReceipt.GetRecord(client)
	if err != nil {
		log.Fatalf("Error getting record for token airdrop transaction: %v", err)
	}
	fmt.Println("Pending airdrop: ", airdropTxRecord.PendingAirdropRecords[0].String())
	fmt.Println("Airdropped fungible tokens")

	aliceBalance, _ := hedera.NewAccountBalanceQuery().SetAccountID(aliceId).Execute(client)
	fmt.Println("Alice's balance: ", aliceBalance.Tokens.Get(tokenId))
	bobBalance, _ := hedera.NewAccountBalanceQuery().SetAccountID(bobId).Execute(client)
	fmt.Println("Bob's balance: ", bobBalance.Tokens.Get(tokenId))
	charlieBalance, _ := hedera.NewAccountBalanceQuery().SetAccountID(charlieId).Execute(client)
	fmt.Println("Charlie's balance: ", charlieBalance.Tokens.Get(tokenId))

	// Step 4: Claim the airdrop for Charlie's account
	tokenClaimTx, err := hedera.NewTokenClaimAirdropTransaction().AddPendingAirdropId(airdropTxRecord.PendingAirdropRecords[0].GetPendingAirdropId()).FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating token claim airdrop transaction: %v", err)
	}
	tokenClaimTxSigned := tokenClaimTx.Sign(charliePrivateKey)

	_, err = tokenClaimTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing token claim airdrop transaction: %v", err)
	}
	fmt.Println("Claimed airdrop for Charlie's account")
	time.Sleep(4 * time.Second)
	charlieBalance, _ = hedera.NewAccountBalanceQuery().SetAccountID(charlieId).Execute(client)
	fmt.Println("Charlie's balance: ", charlieBalance.Tokens.Get(tokenId))

	// Step 5: Airdrop the NFTs to Alice, Bob, and Charlie
	CID := [][]byte{
		[]byte("ipfs://bafyreiao6ajgsfji6qsgbqwdtjdu5gmul7tv2v3pd6kjgcw5o65b2ogst4/metadata.json"),
		[]byte("ipfs://bafyreic463uarchq4mlufp7pvfkfut7zeqsqmn3b2x3jjxwcjqx6b5pk7q/metadata.json"),
		[]byte("ipfs://bafyreihhja55q6h2rijscl3gra7a3ntiroyglz45z5wlyxdzs6kjh2dinu/metadata.json"),
		[]byte("ipfs://bafyreidb23oehkttjbff3gdi4vz7mjijcxjyxadwg32pngod4huozcwphu/metadata.json"),
		[]byte("ipfs://bafyreie7ftl6erd5etz5gscfwfiwjmht3b52cevdrf7hjwxx5ddns7zneu/metadata.json"),
	}
	nftCreate, err := hedera.NewTokenCreateTransaction().
		SetTokenName("Game NFT").
		SetTokenSymbol("GNFT").
		SetTokenType(hedera.TokenTypeNonFungibleUnique).
		SetTreasuryAccountID(treasuryAccount).
		SetSupplyKey(client.GetOperatorPublicKey()).
		SetAdminKey(client.GetOperatorPublicKey()).
		FreezeWith(client)

	nftCreateTxSign := nftCreate.Sign(treasuryPrivateKey)
	nftCreateSubmit, err := nftCreateTxSign.Execute(client)
	if err != nil {
		log.Fatalf("Error creating NFT: %v", err)
	}

	nftCreateReceipt, err := nftCreateSubmit.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for NFT creation: %v", err)
	}

	fmt.Println("Created NFT with ID: 0.0.", nftCreateReceipt.TokenID.Token)
	nftId := *nftCreateReceipt.TokenID
	var serialsNfts []int64
	mintTx, _ := hedera.NewTokenMintTransaction().
		SetTokenID(nftId).
		SetMetadatas(CID).
		FreezeWith(client)
	mintTxSign := mintTx.Sign(treasuryPrivateKey)
	mintTxSubmit, err := mintTxSign.Execute(client)
	if err != nil {
		log.Fatalf("Error minting NFTs: %v", err)
	}
	mintTxReceipt, err := mintTxSubmit.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for NFT minting: %v", err)
	}
	serialsNfts = mintTxReceipt.SerialNumbers
	fmt.Printf("Minted NFT serial numbers: %v\n", serialsNfts)

	// Airdrop NFTs
	nftAirdropTx, err := hedera.NewTokenAirdropTransaction().
		AddNftTransfer(hedera.NftID{TokenID: nftId, SerialNumber: 1}, treasuryAccount, aliceId).
		AddNftTransfer(hedera.NftID{TokenID: nftId, SerialNumber: 2}, treasuryAccount, bobId).
		AddNftTransfer(hedera.NftID{TokenID: nftId, SerialNumber: 3}, treasuryAccount, charlieId).
		FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating NFT airdrop transaction: %v", err)
	}

	nftAirdropTxSigned := nftAirdropTx.Sign(treasuryPrivateKey)
	nftAirdropTxSubmit, err := nftAirdropTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing NFT airdrop transaction: %v", err)
	}
	nftAirdropTxRecord, err := nftAirdropTxSubmit.GetRecord(client)
	if err != nil {
		log.Fatalf("Error getting record for NFT airdrop transaction: %v", err)
	}
	fmt.Println("Pending airdrops length: ", len(nftAirdropTxRecord.PendingAirdropRecords))
	fmt.Println("Pending airdrop for Bob: ", nftAirdropTxRecord.PendingAirdropRecords[0].String())
	fmt.Println("Pending airdrop for Charlie: ", nftAirdropTxRecord.PendingAirdropRecords[1].String())

	// Step 6: Cancel Airdrop for Charlie
	hedera.NewTokenCancelAirdropTransaction().
		AddPendingAirdropId(nftAirdropTxRecord.PendingAirdropRecords[1].GetPendingAirdropId()).
		Execute(client)

	// Step 7: Reject the fungible tokens for Charlie
	tokenRejectTx, err := hedera.NewTokenRejectTransaction().
		AddTokenID(tokenId).
		SetOwnerID(charlieId).
		FreezeWith(client)
	if err != nil {
		log.Fatalf("Error creating token reject transaction: %v", err)
	}
	tokenRejectTxSigned := tokenRejectTx.Sign(charliePrivateKey)
	_, err = tokenRejectTxSigned.Execute(client)
	if err != nil {
		log.Fatalf("Error executing token reject transaction: %v", err)
	}
	fmt.Println("Rejected fungible tokens for Charlie")

	time.Sleep(4 * time.Second)
	charlieBalance, _ = hedera.NewAccountBalanceQuery().SetAccountID(charlieId).Execute(client)
	fmt.Println("Charlie's balance: ", charlieBalance.Tokens.Get(tokenId))
	client.Close()
}

// Helper function to generate a new Hedera account
func createAccount(client *hedera.Client, newAccountPrivateKey hedera.PrivateKey, initialBalance float64, maxAssociations int32) hedera.AccountID {
	newAccountPublicKey := newAccountPrivateKey.PublicKey()
	newAccountTx, err := hedera.NewAccountCreateTransaction().
		SetKey(newAccountPublicKey).
		SetInitialBalance(hedera.HbarFrom(initialBalance, hedera.HbarUnits.Hbar)).
		SetMaxAutomaticTokenAssociations(maxAssociations).
		Execute(client)

	if err != nil {
		log.Fatalf("Error creating new account: %v", err)
	}

	receipt, err := newAccountTx.GetReceipt(client)
	if err != nil {
		log.Fatalf("Error getting receipt for account creation: %v", err)
	}

	newAccountId := *receipt.AccountID

	return newAccountId
}

Additional Resources

When working with Frictionless Airdrops on Hedera, it’s important to consider the associated with each step. Here are some key points to keep in mind:

Code Check

TokenAirdropTransaction
TokenClaimAirdropTransaction
TokenRejectTransaction
TokenCancelAirdropTransaction
Hedera testnet account
here
✅
Airdrop List Verifier (NFT Studio)
Token Holders List Builder (NFT Studio)
transaction costs