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

INTRODUCTION

  • Fees
  • Core Concepts
  • Network Information

TOOLS

  • Bridge
  • Oracles
  • Explorers
  • Developer Portal & Faucet

RESOURCES

  • Status
  • Bug Bounty
  • Build on Hedera (course)
  • Documentation Survey
On this page
  • Prerequisites
  • Table of Contents
  • Create Treasury Account
  • Create FTs and an NFT Collection
  • Create Bob's ECDSA Public Key Alias
  • Return New Account ID

Was this helpful?

Edit on GitHub
  1. Tutorials
  2. More Tutorials

How to Auto-Create Hedera Accounts with HBAR and Token Transfers

PreviousHow to Create a Personal Access Token (API Key) on the Hedera PortalNextHow to Configure a Mirror Node and Query Data

Last updated 4 months ago

Was this helpful?

introduced the ability to auto-create accounts when sending HBAR to an that does not exist on the network. When HBAR is sent to an alias that does not exist on the network, the account creation fee is deducted from the HBAR sent and the account is auto-created. The new account's initial balance is (sent HBAR - account creation fee). This new method of account creation allowed wallet providers to create free "accounts" to users. However, if a user sends fungible tokens or NFT's to an alias, it would result in an INVALID_ACCOUNT_ID error because the alias does not exist on the network. The auto-account creation flow could not deduct the account creation fee from an HTS token; the account creation fee must be paid in HBAR.

provides a solution to allow sending HTS tokens to an alias that does not exist on the network. This is achieved by charging the account creation fee to the transfer transaction payer. In addition, there will be one auto-association slot included in the transaction for the new account to associate with the HTS token. You won't have to first create the account, complete a token association, and then finally do a token transfer.

Furthermore, this change also applies to sending HBAR to an alias. Instead of deducting the creation fee from the sent HBAR, it will be deducted from the payer of the transfer transaction. The new account balance will receive the sent HBAR amount in full. Learn more .

The figure below highlights the transaction flow before HIP-542 and after.

In this tutorial, a treasury account will be created to transfer HTS tokens to Bob's ECDSA public key alias, involving a transfer of 10 FT and 1 NFT. The tutorial will also cover creating fungible tokens and an NFT collection (1000 FT / 5 NFT), creating Bob's ECDSA public key alias, and returning Bob's new account ID while confirming their ownership of the transferred tokens and NFT.


Prerequisites

Get the example code on GitHub:

Table of Contents


Create Treasury Account

We create the treasury account, which will be the holder of the fungible and non-fungible tokens. The treasury account will be created with an initial balance of 5 HBAR.

const [treasuryAccId, treasuryAccPvKey] = await createAccount(client, 5);

Set Up Helper Functions

We will create the functions necessary to create a new account, create fungible tokens, and create a new NFT collection. Use the tabs to see the helper functions.

const createAccount = async (client:  Client, initialBalance: number) => {
 const accountPrivateKey = PrivateKey.generateECDSA();
 const accountPublicKey = accountPrivateKey.publicKey;
 
 const response = await new AccountCreateTransaction()
   .setInitialBalance(new Hbar(initialBalance))
   .setKey(accountPublicKey)
   //Do NOT set an alias if you need to update/rotate keys in the future
   .setAlias(accountPublicKey.toEvmAddress())
   .execute(client);
 
 const receipt = await response.getReceipt(client);
 
 return [receipt.accountId, accountPrivateKey];
};
export const createFungibleToken = async (
 client: Client,
 treasureyAccId: string | AccountId,
 supplyKey: PrivateKey,
 treasuryAccPvKey: PrivateKey,
 initialSupply: number,
 tokenName: string,
 tokenSymbol: string,
): Promise<TokenId> => {
 /*
   * Create a transaction with token type fungible
   * Returns Fungible Token Id
 */
 const createTokenTxn = await new TokenCreateTransaction()
   .setTokenName(tokenName)
   .setTokenSymbol(tokenSymbol)
   .setTokenType(TokenType.FungibleCommon)
   .setInitialSupply(initialSupply)
   .setTreasuryAccountId(treasureyAccId)
   .setSupplyKey(supplyKey)
   .setMaxTransactionFee(new Hbar(30))
   .freezeWith(client); //freeze tx from from any further mods.
 
 const createTokenTxnSigned = await createTokenTxn.sign(treasuryAccPvKey);
 // submit txn to heder network
 const txnResponse = await createTokenTxnSigned.execute(client);
 // request receipt of txn
 const txnRx = await txnResponse.getReceipt(client);
 const txnStatus = txnRx.status.toString();
 const tokenId = txnRx.tokenId;
 if (tokenId === null) {
   throw new Error("Somehow tokenId is null");
 }
 
 console.log(
   `Token Type Creation was a ${txnStatus} and was created with token id: ${tokenId}`
 );
 
 return tokenId;
};
export const createNonFungibleToken = async (
 client: Client,
 treasureyAccId: string | AccountId,
 supplyKey: PrivateKey,
 treasuryAccPvKey: PrivateKey,
 initialSupply: number,
 tokenName: string,
 tokenSymbol: string,
): Promise<[TokenId | null, string]> => {
 /*
   * Create a transaction with token type fungible
   * Returns Fungible Token Id and Token Id in solidity format
 */
 const createTokenTxn = await new TokenCreateTransaction()
   .setTokenName(tokenName)
   .setTokenSymbol(tokenSymbol)
   .setTokenType(TokenType.NonFungibleUnique)
   .setDecimals(0)
   .setInitialSupply(initialSupply)
   .setTreasuryAccountId(treasureyAccId)
   .setSupplyKey(supplyKey)
   .setAdminKey(treasuryAccPvKey)
   .setMaxTransactionFee(new Hbar(30))
   .freezeWith(client); //freeze tx from from any further mods.
 
 const createTokenTxnSigned = await createTokenTxn.sign(treasuryAccPvKey);
 // submit txn to hedera network
 const txnResponse = await createTokenTxnSigned.execute(client);
 // request receipt of txn
 const txnRx = await txnResponse.getReceipt(client);
 const txnStatus = txnRx.status.toString();
 const tokenId = txnRx.tokenId;
 if (tokenId === null) { throw new Error("Somehow tokenId is null."); }
 
 const tokenIdInSolidityFormat = tokenId.toSolidityAddress();
 
 console.log(
   `Token Type Creation was a ${txnStatus} and was created with token id: ${tokenId}`
 );
 
 return [tokenId, tokenIdInSolidityFormat];
};
 const mintTokenTxn = new TokenMintTransaction()
   .setTokenId(tokenId)
   .setMetadata(metadatas)
   .freezeWith(client);
 
 const mintTokenTxnSigned = await mintTokenTxn.sign(supplyKey);
 
 // submit txn to hedera network
 const txnResponse = await mintTokenTxnSigned.execute(client);
 
 const mintTokenRx = await txnResponse.getReceipt(client);
 const mintTokenStatus = mintTokenRx.status.toString();
 
 console.log(`Token mint was a ${mintTokenStatus}`);
};

export const createNewNftCollection = async (
 client: Client,
 tokenName: string,
 tokenSymbol: string,
 metadataIPFSUrls: Buffer[], // already uploaded ipfs metadata json files
 treasuryAccountId: string | AccountId,
 treasuryAccountPrivateKey: PrivateKey,
): Promise<{
 tokenId: TokenId,
 supplyKey: PrivateKey,
}> => {
 // generate supply key
 const supplyKey = PrivateKey.generateECDSA();
 
 const [tokenId,] = await createNonFungibleToken(client, treasuryAccountId, supplyKey, treasuryAccountPrivateKey, 0, tokenName, tokenSymbol);
 if (tokenId === null || tokenId === undefined) {
   throw new Error("Somehow tokenId is null");
 }
 
 const metadatas: Uint8Array[] = metadataIPFSUrls.map(url => Buffer.from(url));
 
 // mint token
 await mintToken(client, tokenId, metadatas, supplyKey);
 return {
   tokenId: tokenId,
   supplyKey: supplyKey,
 };
}

Create FTs and an NFT Collection

Leverage the createFungibleToken helper function defined above to create 10000 "Hip-542 example" fungible tokens. Use the code tab switch on the upper left of the code block to see how we use createNewNftCollection to create our new NFT collection consisting of 5 NFTs.

const tokenId = await createFungibleToken(client, treasuryAccId, supplyKey, treasuryAccPvKey, 10000, 'HIP-542 Token', 'H542');
 // IPFS content identifiers for the NFT metadata
 const metadataIPFSUrls: Buffer[] = [
   Buffer.from("ipfs://bafkreiap62fsqxmo4hy45bmwiqolqqtkhtehghqauixvv5mcq7uofdpvt4"),
   Buffer.from("ipfs://bafkreibvluvlf36lilrqoaum54ga3nlumms34m4kab2x67f5piofmo5fsa"),
   Buffer.from("ipfs://bafkreidrqy67amvygjnvgr2mgdgqg2alaowoy34ljubot6qwf6bcf4yma4"),
   Buffer.from("ipfs://bafkreicoorrcx3d4foreggz72aedxhosuk3cjgumglstokuhw2cmz22n7u"),
   Buffer.from("ipfs://bafkreidv7k5vfn6gnj5mhahnrvhxep4okw75dwbt6o4r3rhe3ktraddf5a"),
 ];
 
 /**
  * Step 2
  * Create nft collection
 */
 const nftCreateTxnResponse = await createNewNftCollection(client, 'HIP-542 Example Collection', 'HIP-542', metadataIPFSUrls, treasuryAccId, treasuryAccPvKey);

Create Bob's ECDSA Public Key Alias

An alias is an initial public key that will convert into a Hedera account through auto-account creation. An alias consists of <shard>.<realm>.<bytes>.

 const privateKey = PrivateKey.generateECDSA();
 const publicKey = privateKey.publicKey;
 
 // Assuming that the target shard and realm are known.
 // For now they are virtually always 0 and 0.
 const aliasAccountId = publicKey.toAccountId(0, 0);
 
 console.log(`- New account ID: ${aliasAccountId.toString()}`);
 if (aliasAccountId.aliasKey === null) { throw new Error('alias key is empty') }
 console.log(`- Just the aliasKey: ${aliasAccountId.aliasKey.toString()}\n`);

Set up helper functions for transferring HTS tokens

Once we have our treasury account with FT and a new NFT collection created, our next step is to transfer them to Bob using their alias. We'll create the sendToken helper function to send fungible tokens and create transferNft to send a single NFT.

A quick reminder to use the tab on the left of the code block to switch between the two helper functions.

export const sendToken = async (client: Client, tokenId: TokenId, owner: AccountId, aliasAccountId: AccountId, sendBalance: number, treasuryAccPvKey: PrivateKey) => {
 const tokenTransferTx = new TransferTransaction()
   .addTokenTransfer(tokenId, owner, -sendBalance)
   .addTokenTransfer(tokenId, aliasAccountId, sendBalance)
   .freezeWith(client);
 
    // Sign the transaction with the operator key
    let tokenTransferTxSign = await tokenTransferTx.sign(treasuryAccPvKey);
 
    // Submit the transaction to the Hedera network
    let tokenTransferSubmit = await tokenTransferTxSign.execute(client);
    
    // Get transaction receipt information
    await tokenTransferSubmit.getReceipt(client);
}
export const transferNft = async (client: Client, nftTokenId: TokenId, nftId: number, treasuryAccId: AccountId, treasuryAccPvKey: PrivateKey, aliasAccountId: AccountId) => {
 const nftTransferTx = new TransferTransaction()
   .addNftTransfer(nftTokenId, nftId, treasuryAccId, aliasAccountId)
   .freezeWith(client);
   
 // Sign the transaction with the treasury account private key
 const nftTransferTxSign = await nftTransferTx.sign(treasuryAccPvKey);
 
 // Submit the transaction to the Hedera network
 const nftTransferSubmit = await nftTransferTxSign.execute(client);
 
 // Get transaction receipt information here
 await nftTransferSubmit.getReceipt(client);
}

Transfer FT and an NFT to Bob using their alias

Transfer 5 fungible tokens to Bob using their alias and the helper function sendToken.

Transfer the NFT with serial number 1 to Bob using the helper function transfertNFT.

await sendToken(client, tokenId, treasuryAccId, aliasAccountId, 5, treasuryAccPvKey);
const nftTokenId = nftCreateTxnResponse.tokenId;
 const exampleNftId = 1;
 await transferNft(client, nftTokenId, exampleNftId, treasuryAccId, treasuryAccPvKey, aliasAccountId);

Return New Account ID

Create a helper function to return the corresponding account Id to the given an alias.

export const getAccountIdByAlias = async (client: Client, aliasAccountId: AccountId ) => {
 const accountInfo =  await new AccountInfoQuery()
   .setAccountId(aliasAccountId)
   .execute(client);
  
return accountInfo.accountId;
}

Next we call getAccountIdByAlias and pass in our client and Bob's alias as the arguments.

const accountId = await getAccountIdByAlias(client, aliasAccountId);
console.log(`The normal account ID of the given alias: ${accountId}`);

Show Bob's new account owns the 5 FT tokens

Complete an AccountBalanceQuery to show that Bob's new account owns the 5 fungible tokens the treasury account sent.

 const accountBalances = await new AccountBalanceQuery()
   .setAccountId(aliasAccountId)
   .execute(client);
 
 if (!accountBalances.tokens || !accountBalances.tokens._map) {
   throw new Error('account balance shows no tokens.')
 }
 
 const tokenBalanceAccountId = accountBalances.tokens._map
   .get(tokenId.toString());
 
 if (!tokenBalanceAccountId) {
   throw new Error(`account balance does not have tokens for token id: ${tokenId}.`);
 }
 
 tokenBalanceAccountId.toInt() === 5
   ? console.log(
     `Account is created successfully using HTS 'TransferTransaction'`
   )
   : console.log(
     "Creating account with HTS using public key alias failed"
   );
 
 client.close();

Show Bob's new account owns the NFT

First, create a helper function that creates a TokenNftInfoQuery transaction and returns the account id of the NFT owner for a specific NFT serial number.

export const getNftOwnerByNftId = async (client: Client, nftTokenId: TokenId, exampleNftId: number) => {
 const nftInfo = await new TokenNftInfoQuery()
   .setNftId(new NftId(nftTokenId, exampleNftId))
   .execute(client);
 
 if (nftInfo === null) { throw new Error('nftInfo is null.') }
 const nftOwnerAccountId = nftInfo[0].accountId.toString();
 console.log(`- Current owner account id: ${nftOwnerAccountId} for NFT with serial number: ${exampleNftId}`);
  return nftOwnerAccountId;
}

Then call getNftOwnerByNft and do a simple check to ensure the account id returned matches the account id created when we sent the NFT to Bob's alias.

 const nftOwnerAccountId = await getNftOwnerByNftId(client, nftTokenId, exampleNftId);
 
 nftOwnerAccountId === accountId
   ? console.log(
     `The NFT owner accountId matches the accountId created with the HTS\n`
   )
   : console.log(`The two account IDs does not match\n`);
  
 client.close();

Console Output ✅

And that's a wrap! 🎬 You've completed sending HTS tokens to an alias and triggering an auto-account creation! As well as learned that the account creation fee is paid by the payer of the transfer transaction.

Get a account .

Set up your environment and create a client .

To learn more about accounts created via an account alias go .

Join and collaborate with Hedera Developers on the ! Happy Building! 🛠️

Hedera Testnet
here
here
auto-create account by sending FT
auto-create account by sending NFT
here
Hedera Discord Server
Create Treasury Account
Create FTs and NFT Collection
Create Bob's ECDSA Public Key Alias
Return New Account ID

Writer: Abi, DevRel Engineer

Editor: Krystal, Technical Writer

HIP-32
alias
HIP-542
here

|

|

GitHub
LinkedIn
GitHub
Hashnode