How to Auto-Create Hedera Accounts with HBAR and Token… | Hedera Hedera Network Services Token Service Mint and configure tokens and accounts. Consensus Service Verifiable timestamps and ordering of events. Smart Contracts Run Solidity smart contracts. HBAR The Hedera network's native cryptocurrency. Insights How It Works Learn about Hedera from end to end. Explorers View live and historical data on Hedera. Dashboards Analyze network activity and metrics. Network Nodes Understand networks and node types. Devs Start Building Get Started Learn core concepts and build the future. Documentation Review the API and build using your favorite language. Developer Resources Integrations Plugins and microservices for Hedera. Fee Estimator Understand and estimate transaction costs. Open Source Hedera is committed to open, transparent code. Learning Center Learn about web3 and blockchain technologies. Grants Grants & accelerators for your project. Bounties Find bugs. Submit a report. Earn rewards. Ecosystem ECOSYSTEM Hedera Ecosystem Applications, developer tools, network explorers, and more. NFT Ecosystem Metrics Analyze on-chain and market NFT ecosystem metrics. CATEGORIES Web3 Applications Connect into the innovative startups decentralizing the web on Hedera. Enterprise Applications Learn about the Fortune 500 companies decentralizing the web on Hedera. Wallets & Custodians Create a Hedera account to manage HBAR, fungible tokens, and NFTs. Network Explorers Hedera mainnet and testnet graphical network explorers. Developer Tooling Third-party APIs, integrations, and plugins to build apps on Hedera. Grants & Accelerators Boost your project with support from the Hedera ecosystem. Partner Program Explore our partners to bring your vision into reality. Hedera Council Over 30 highly diversified organizations govern Hedera. Use Cases Hedera Solutions Asset Tokenization Studio Open source toolkit for tokenizing assets securely. Stablecoin Studio All-in-one toolkit for stablecoin solutions. Hedera Guardian Auditable carbon markets and traceability. Functional Use Cases Data Integrity & AI Reliable, secure, and ethically governed insights. Sustainability Enabling fair carbon markets with trust. Real-World Asset Tokenization Seamless tokenization of real-world assets and digital at scale. Consumer Engagement & Loyalty Mint, distribute, and redeem loyalty rewards. Decentralized Identity Maintain the lifecycle of credentials. Decentralized Logs Scalable, real-time timestamped events. DeFi Dapps built for the next-generation of finance. NFTs Low, fixed fees. Immutable royalties. Payments Scalable, real-time, and affordable crypto-payments. HBAR Overview Learn about Hedera's token, HBAR. Treasury Management Hedera’s report of the HBAR supply. Governance Decentralized Governance Hedera Council See the world's leading organizations that own Hedera. About Meet Hedera's Board of Directors and team. Journey Watch Hedera's journey to build an empowered digital future for all. Transparent Governance Public Policy Hedera's mission is to inform policy and regulation that impact the industry. Meeting Minutes Immutably recorded on Hedera. Roadmap Follow Hedera's roadmap in its journey to build the future. Resources Company What's New Partners Papers Careers Media Blog Technical Press Podcast Community Events Meetups Store Brand Navigation QUICKSTART How to Auto-Create Hedera Accounts with HBAR and Token Transfers technical Oct 26, 2022 by Abi Castro HIP-32 introduced the ability to auto-create accounts when sending HBAR to an alias 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. HIP-542 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 here. The figure below highlights the transaction flow before HIP-542 and after. Try It Yourself: Get a Hedera testnet account This portal acts like a faucet, giving you 10,000 test HBAR every 24 hours! Use this Codesandbox to try auto-creating an account by sending FT to an alias Use this Codesandbox to try auto-creating an account by sending an NFT to an alias Fork the sandbox Remember to provide testnet account credentials in the .env file Open a new terminal to execute: npm run start Get the example code on Github: auto-create account by sending FT auto-create account by sending NFT Let’s work through the below example which will walk us through auto-account creation when sending HTS tokens. If you need assistance creating a client and setting up your environment make sure to start on our getting started section. Example: Treasury sends FT's and an NFT to Bob's alias to auto-create an account This example guides you through the following steps: Creating a treasury account Creating fungible tokens and an NFT collection (1000 FT / 5 NFT) Creating Bob's ECDSA public key alias Treasury account transfers HTS token to Bob's alias using the transfer transaction (10 FT / 1 NFT) Return Bob's new account ID Show Bob's new account ID owns the tokens and NFT 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 code tab switch on the upper left of the code block to see the helper functions. create account with initial balance create account with initial balance create simple fungible token create simple non-fungible token Mint token and create NFT collection const createAccount = async (client: Client, initialBalance: number) => { const accountPrivateKey = PrivateKey.generateED25519(); const response = await new AccountCreateTransaction() .setKey(accountPrivateKey) .setAlias(accountPublicKey.toEvmAddress()) .setInitialBalance(new Hbar(initialBalance)) .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 => { /* * 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, }; } 1. Create a 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 100 HBAR. const [treasuryAccId, treasuryAccPvKey] = await createAccount(client, 100); Copy 2. Create FTs and create 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. createFungibleToken createFungibleToken createNewNftCollection 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); 3. 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 ... To learn more about accounts created via an account alias go here. 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`); Copy 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); } 4. Transfer FT and an NFT to Bob using their alias  Transfer 10 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. Send Bob 10 FT Send Bob 10 FT Send Bob an NFT await sendToken(client, tokenId, treasuryAccId, aliasAccountId, 10, treasuryAccPvKey); const nftTokenId = nftCreateTxnResponse.tokenId; const exampleNftId = 1; await transferNft(client, nftTokenId, exampleNftId, treasuryAccId, treasuryAccPvKey, aliasAccountId); 5. Return the 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; } Copy 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}`); Copy 6. Show Bob's new account owns the 10 FT tokens Complete an AccountBalanceQuery to show that Bob's new account owns the 10 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() === 10 ? console.log( `Account is created successfully using HTS 'TransferTransaction'` ) : console.log( "Creating account with HTS using public key alias failed" ); client.close(); Copy 6a. 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; } Copy 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(); Copy 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.  Join and collaborate with Hedera Developers on the Hedera Discord Server!  Happy Building! 👷 Share This Back to blog What is gRPC, gRPC-Web, and Proxies? Ed Marquez Pragmatic Blockchain Design Patterns – Integrating Blockchain into Business Processes Michiel Mulders Zero Cost EthereumTransaction on Success: Hedera's New Fee Model for Relay Operators Oliver Thorn Hedera Adopts Chainlink Standard for Cross-Chain Interoperability To Accelerate Ecosystem Adoption Hedera Team Hedera Developer Highlights March 2025 Michiel Mulders Hedera Release Cycle Overview Ed Marquez View All Posts Sign up for the newsletter CONNECT WITH US Transparency Open Source Audits & Standards Sustainability Commitment Carbon Offsets Governance Hedera Council Public Policy Treasury Management Meeting Minutes LLC Agreement Node Requirements Community Events Meetups HBAR Telegram Developer Discord Twitter Community Support FAQ Network Status Developer Discord StackOverflow Brand Brand Guidelines Built on Hedera Logo Hedera Store About Team Partners Journey Roadmap Careers Contact General Inquiry Public Relations © 2018-2025 Hedera Hashgraph, LLC. All trademarks and company names are the property of their respective owners. All rights in the Deutsche Telekom mark are protected by Deutsche Telekom AG. All rights reserved. Hedera uses the third party marks with permission. Terms of Use  |  Privacy Policy