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
  • Prerequisites
  • Pause a Token
  • Freeze a Token
  • Wipe a Token
  • Delete a Token
  • Conclusion
  • Additional Resources

Was this helpful?

Edit on GitHub
  1. Tutorials
  2. Tokens

Hedera Token Service - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs

PreviousHedera Token Service - Part 2: KYC, Update, and Scheduled TransactionsNextCreate Your First Frictionless Airdrop Campaign

Last updated 4 months ago

Was this helpful?

In of the series, you saw how to mint and transfer an NFT using the Hedera Token Service (HTS). In , you saw how to enable and disable token , update token properties (if a token is mutable), and schedule transactions. In Part 3, you will learn how to use HTS capabilities that help you manage your tokens. Specifically, you will learn how to:

  • Pause a token (stops all operations for a token ID)

  • Freeze an account (stops all token operations only for a specific account)

  • Wipe a token (wipe a partial or entire token balance for a specific account)

  • Delete a token (the token will remain on the ledger)

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.

Pause a Token

Pausing a token may be useful in cases where a third party requests that you, as the administrator of a token, stop all operations for that token while something like an audit is conducted. The pause transaction provides you with a way to comply with requests of that nature.

nft-part3.js
// PAUSE ALL TOKEN OEPRATIONS
let tokenPauseTx = await new TokenPauseTransaction()
    .setTokenId(tokenId)
    .freezeWith(client)
    .sign(pauseKey);
let tokenPauseSubmitTx = await tokenPauseTx.execute(client);
let tokenPauseRx = await tokenPauseSubmitTx.getReceipt(client);
console.log(`- Token pause: ${tokenPauseRx.status}`);
console.log(
  `- See: https://hashscan.io/${network}/transaction/${tokenPauseSubmitTx.transactionId}`
);

// TEST THE TOKEN PAUSE BY TRYING AN NFT TRANSFER (TREASURY -> ALICE)
let tokenTransferTx3 = await new TransferTransaction()
    .addNftTransfer(tokenId, 3, treasuryId, aliceId)
    .freezeWith(client)
    .sign(treasuryKey);
let tokenTransferSubmit3 = await tokenTransferTx3.execute(client);
try {
   let tokenTransferRx3 = await tokenTransferSubmit3.getReceipt(client);
   console.log(
   `\n-NFT transfer Treasury -> Alice status: ${tokenTransferRx3.status}`
 );
} catch {
    // TOKEN QUERY TO CHECK PAUSE
   var tokenInfo = await tQueryFcn();
   console.log(
   `\n- NFT transfer unsuccessful: Token ${tokenId} is paused (${tokenInfo.pauseStatus})`
 );
   console.log(
   `- See: https://hashscan.io/${network}/transaction/${tokenTransferSubmit3.transactionId}`
 );
}

// UNPAUSE ALL TOKEN OPERATIONS
let tokenUnpauseTx = await new TokenUnpauseTransaction()
    .setTokenId(tokenId)
    .freezeWith(client)
    .sign(pauseKey);
let tokenUnpauseSubmitTx = await tokenUnpauseTx.execute(client);
let tokenUnpauseRx = await tokenUnpauseSubmitTx.getReceipt(client);
console.log(`- Token unpause: ${tokenUnpauseRx.status}\n`);
console.log(
  `- See: https://hashscan.io/${network}/transaction/${tokenUnpauseSubmitTx.transactionId}`
);
// TOKEN QUERY FUNCTION ==========================================
async function tQueryFcn() {
   var tokenInfo = await new TokenInfoQuery().setTokenId(tokenId).execute(client);
   return tokenInfo;
 }

Console output:

- Token pause: SUCCESS
- See: https://hashscan.io/testnet/transaction/0.0.46446@1723772395.193039130

- NFT transfer unsuccessful: Token 0.0.4686491 is paused (true)
- See: https://hashscan.io/testnet/transaction/0.0.46446@1723772400.030831515

- Token unpause: SUCCESS
- See: https://hashscan.io/testnet/transaction/0.0.46446@1723772398.843664980

Freeze a Token

nft-part3.js
// FREEZE ALICE'S ACCOUNT FOR THIS TOKEN
let tokenFreezeTx = await new TokenFreezeTransaction()
    .setTokenId(tokenId)
    .setAccountId(aliceId)
    .freezeWith(client)
    .sign(freezeKey);
let tokenFreezeSubmitTx = await tokenFreezeTx.execute(client);
let tokenFreezeRx = await tokenFreezeSubmitTx.getReceipt(client);
console.log(
  `\n- Freeze Alice's account for token ${tokenId}: ${tokenFreezeRx.status}`
);
console.log(
  `- See: https://hashscan.io/${network}/transaction/${tokenFreezeSubmitTx.transactionId}`
);

// TEST THE TOKEN FREEZE FOR THE ACCOUNT BY TRYING A TRANSFER (ALICE -> BOB)
let tokenTransferTx4 = await new TransferTransaction()
    .addNftTransfer(tokenId, 2, aliceId, bobId)
    .addHbarTransfer(aliceId, nftPrice)
    .addHbarTransfer(bobId, nftPrice.negated())
    .freezeWith(client)
    .sign(aliceKey);
let tokenTransferTx4Sign = await tokenTransferTx4.sign(bobKey);
let tokenTransferSubmit4 = await tokenTransferTx4Sign.execute(client);
try {
  let tokenTransferRx4 = await tokenTransferSubmit4.getReceipt(client);
  console.log(
    `\n- NFT transfer Alice -> Bob status: ${tokenTransferRx4.status}`
 );
} catch {
  console.log(
    `\n- NFT transfer Alice -> Bob unsuccessful: Alice's account is frozen for this token`
 );
  console.log(
    `- See: https://hashscan.io/${network}/transaction/${
     tokenTransferSubmit4.transactionId
  }`
 );
}

// UNFREEZE ALICE'S ACCOUNT FOR THIS TOKEN
let tokenUnfreezeTx = await new TokenUnfreezeTransaction()
    .setTokenId(tokenId)
    .setAccountId(aliceId)
    .freezeWith(client)
    .sign(freezeKey);
let tokenUnfreezeSubmitTx = await tokenUnfreezeTx.execute(client);
let tokenUnfreezeRx = await tokenUnfreezeSubmitTx.getReceipt(client);
console.log(
  `\n- Unfreeze Alice's account for token ${tokenId}: ${tokenUnfreezeRx.status}`
);
console.log(
  `- See: https://hashscan.io/${network}/transaction/${
    tokenUnfreezeSubmitTx.transactionId
 }`
);

Console output:

- Freeze Alice's account for token 0.0.46864: SUCCESS
- See: https://hashscan.io/testnet/transaction/0.0.46446@1723772402.841848773

- NFT transfer Alice -> Bob unsuccessful: Alice's account is frozen for this token
- See: https://hashscan.io/testnet/transaction/0.0.46446@1723772405.380352596

- Unfreeze Alice's account for token 0.0.4686491: SUCCESS
- See: https://hashscan.io/testnet/transaction/0.0.46446@1723772403.655969673

Wipe a Token

Note: Wiping an account's tokens burns the tokens and decreases the total supply. This transaction does not delete tokens from the treasury account. You must use the Token Burn operation to delete tokens from the treasury.

nft-part3.js
// WIPE THE TOKEN FROM ALICE'S ACCOUNT
let tokenWipeTx = await new TokenWipeTransaction()
    .setAccountId(aliceId)
    .setTokenId(tokenId)
    .setSerials([2])
    .freezeWith(client)
    .sign(wipeKey);
let tokenWipeSubmitTx = await tokenWipeTx.execute(client);
let tokenWipeRx = await tokenWipeSubmitTx.getReceipt(client);
console.log(`\n- Wipe token ${tokenId} from Alice's account: ${tokenWipeRx.status}`);
console.log(
  `- See: https://hashscan.io/${network}/transaction/${tokenWipeSubmitTx.transactionId}`
);

// CHECK ALICE'S BALANCE
aB = await bCheckerFcn(aliceId);
console.log(`\n- Alice balance: ${aB[0]} NFTs of ID:${tokenId} and ${aB[1]}`);

// TOKEN QUERY TO CHECK TOTAL TOKEN SUPPLY
var tokenInfo = await tQueryFcn();
console.log(`- Current NFT supply: ${tokenInfo.totalSupply}`);

Console output:

Delete a Token

In our example, we delete the token and perform a query to double-check that the deletion was successful. Note that for NFTs, you can’t delete a specific serial ID. Instead, you delete the entire class of the NFT specified by the token ID.

nft-part3.js
// DELETE THE TOKEN
let tokenDeleteTx = await new TokenDeleteTransaction()
    .setTokenId(tokenId)
    .freezeWith(client);
let tokenDeleteSign = await tokenDeleteTx.sign(adminKey);
let tokenDeleteSubmit = await tokenDeleteSign.execute(client);
let tokenDeleteRx = await tokenDeleteSubmit.getReceipt(client);
console.log(`\n- Delete token ${tokenId}: ${tokenDeleteRx.status}`);
console.log(
  `- See: https://hashscan.io/${network}/transaction/${
   tokenDeleteSubmitTx.transactionId
  }`
);

// TOKEN QUERY TO CHECK DELETION
var tokenInfo = await tQueryFcn();
console.log(`- Token ${tokenId} is deleted: ${tokenInfo.isDeleted}`);

Console output:

- Delete token 0.0.4686491: SUCCESS
- See: https://hashscan.io/testnet/transaction/0.0.4644601@1723772409.964607591

- Token 0.0.4686491 is deleted: true

Conclusion

Code Check ✅
nft-part3.js
console.clear();
require("dotenv").config();

const {
	AccountId,
	PrivateKey,
	Client,
	TokenCreateTransaction,
	TokenInfoQuery,
	TokenType,
	CustomRoyaltyFee,
	CustomFixedFee,
	Hbar,
	HbarUnit,
	TokenSupplyType,
	TokenMintTransaction,
	TokenBurnTransaction,
	TransferTransaction,
	AccountBalanceQuery,
	AccountUpdateTransaction,
	TokenAssociateTransaction,
	TokenUpdateTransaction,
	TokenGrantKycTransaction,
	TokenRevokeKycTransaction,
	ScheduleCreateTransaction,
	ScheduleSignTransaction,
	ScheduleInfoQuery,
	TokenPauseTransaction,
	TokenUnpauseTransaction,
	TokenWipeTransaction,
	TokenFreezeTransaction,
	TokenUnfreezeTransaction,
	TokenDeleteTransaction,
	AccountCreateTransaction,
} = require("@hashgraph/sdk");

// CONFIGURE ACCOUNTS AND CLIENT, AND GENERATE  accounts and client, and generate needed keys
const operatorId = AccountId.fromString(process.env.OPERATOR_ID);
const operatorKey = PrivateKey.fromStringECDSA(process.env.OPERATOR_KEY_HEX);
const network = process.env.NETWORK;

const client = Client.forNetwork(network).setOperator(operatorId, operatorKey);
client.setDefaultMaxTransactionFee(new Hbar(50));
client.setDefaultMaxQueryPayment(new Hbar(1));

async function main() {
	// CREATE NEW HEDERA ACCOUNTS TO REPRESENT OTHER USERS
	const initBalance = new Hbar(1);

	const treasuryKey = PrivateKey.generateECDSA();
	const [treasurySt, treasuryId] = await accountCreateFcn(treasuryKey, initBalance, client);
	console.log(`- Treasury's account: https://hashscan.io/testnet/account/${treasuryId}`);
	const aliceKey = PrivateKey.generateECDSA();
	const [aliceSt, aliceId] = await accountCreateFcn(aliceKey, initBalance, client);
	console.log(`- Alice's account: https://hashscan.io/testnet/account/${aliceId}`);
	const bobKey = PrivateKey.generateECDSA();
	const [bobSt, bobId] = await accountCreateFcn(bobKey, initBalance, client);
	console.log(`- Bob's account: https://hashscan.io/testnet/account/${bobId}`);

	// GENERATE KEYS TO MANAGE FUNCTIONAL ASPECTS OF THE TOKEN
	const supplyKey = PrivateKey.generateECDSA();
	const adminKey = PrivateKey.generateECDSA();
	const pauseKey = PrivateKey.generateECDSA();
	const freezeKey = PrivateKey.generateECDSA();
	const wipeKey = PrivateKey.generateECDSA();
	const kycKey = PrivateKey.generate();
	const newKycKey = PrivateKey.generate();

	// DEFINE CUSTOM FEE SCHEDULE
	let nftCustomFee = new CustomRoyaltyFee()
		.setNumerator(1)
		.setDenominator(10)
		.setFeeCollectorAccountId(treasuryId)
		.setFallbackFee(new CustomFixedFee().setHbarAmount(new Hbar(1, HbarUnit.Tinybar))); // 1 HBAR = 100,000,000 Tinybar

	// IPFS CONTENT IDENTIFIERS FOR WHICH WE WILL CREATE NFTs - SEE uploadJsonToIpfs.js
	let CIDs = [
		Buffer.from("ipfs://bafkreibr7cyxmy4iyckmlyzige4ywccyygomwrcn4ldcldacw3nxe3ikgq"),
		Buffer.from("ipfs://bafkreig73xgqp7wy7qvjwz33rp3nkxaxqlsb7v3id24poe2dath7pj5dhe"),
		Buffer.from("ipfs://bafkreigltq4oaoifxll3o2cc3e3q3ofqzu6puennmambpulxexo5sryc6e"),
		Buffer.from("ipfs://bafkreiaoswszev3uoukkepctzpnzw56ey6w3xscokvsvmfrqdzmyhas6fu"),
		Buffer.from("ipfs://bafkreih6cajqynaqwbrmiabk2jxpy56rpf25zvg5lbien73p5ysnpehyjm"),
	];

	// CREATE NFT WITH CUSTOM FEE
	let nftCreateTx = await new TokenCreateTransaction()
		.setTokenName("Fall Collection")
		.setTokenSymbol("LEAF")
		.setTokenType(TokenType.NonFungibleUnique)
		.setDecimals(0)
		.setInitialSupply(0)
		.setTreasuryAccountId(treasuryId)
		.setSupplyType(TokenSupplyType.Finite)
		.setMaxSupply(CIDs.length)
		.setCustomFees([nftCustomFee])
		.setAdminKey(adminKey.publicKey)
		.setSupplyKey(supplyKey.publicKey)
		.setKycKey(kycKey.publicKey)
		.setPauseKey(pauseKey.publicKey)
		.setFreezeKey(freezeKey.publicKey)
		.setWipeKey(wipeKey.publicKey)
		.freezeWith(client)
		.sign(treasuryKey);

	let nftCreateTxSign = await nftCreateTx.sign(adminKey);
	let nftCreateSubmit = await nftCreateTxSign.execute(client);
	let nftCreateRx = await nftCreateSubmit.getReceipt(client);
	let tokenId = nftCreateRx.tokenId;
	console.log(`\n- Created NFT with Token ID: ${tokenId}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${nftCreateSubmit.transactionId}`);

	// TOKEN QUERY TO CHECK THAT THE CUSTOM FEE SCHEDULE IS ASSOCIATED WITH NFT
	var tokenInfo = await tQueryFcn();
	console.log(` `);
	console.table(tokenInfo.customFees[0]);

	// MINT NEW BATCH OF NFTs - CAN MINT UP TO 10 NFT SERIALS IN A SINGLE TRANSACTION
	let [nftMintRx, mintTxId] = await tokenMinterFcn(CIDs);
	console.log(`\n- Mint ${CIDs.length} serials for NFT collection ${tokenId}: ${nftMintRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${mintTxId}`);

	// BURN THE LAST NFT IN THE COLLECTION
	let tokenBurnTx = await new TokenBurnTransaction().setTokenId(tokenId).setSerials([CIDs.length]).freezeWith(client).sign(supplyKey);
	let tokenBurnSubmit = await tokenBurnTx.execute(client);
	let tokenBurnRx = await tokenBurnSubmit.getReceipt(client);
	console.log(`\n- Burn NFT with serial ${CIDs.length}: ${tokenBurnRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenBurnSubmit.transactionId}`);

	var tokenInfo = await tQueryFcn();
	console.log(`- Current NFT supply: ${tokenInfo.totalSupply}`);

	// MANUAL ASSOCIATION FOR ALICE'S ACCOUNT
	let associateAliceTx = await new TokenAssociateTransaction().setAccountId(aliceId).setTokenIds([tokenId]).freezeWith(client).sign(aliceKey);
	let associateAliceTxSubmit = await associateAliceTx.execute(client);
	let associateAliceRx = await associateAliceTxSubmit.getReceipt(client);
	console.log(`\n- Alice NFT manual association: ${associateAliceRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${associateAliceTxSubmit.transactionId}`);

	// MANUAL ASSOCIATION FOR BOB'S ACCOUNT
	let associateBobTx = await new TokenAssociateTransaction().setAccountId(bobId).setTokenIds([tokenId]).freezeWith(client).sign(bobKey);
	let associateBobTxSubmit = await associateBobTx.execute(client);
	let associateBobRx = await associateBobTxSubmit.getReceipt(client);
	console.log(`\n- Bob NFT manual association: ${associateBobRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${associateBobTxSubmit.transactionId}`);

	// PART 2.1 STARTS ============================================================
	console.log(`\nPART 2.1 STARTS ============================================================`);
	// ENABLE TOKEN KYC FOR ALICE AND BOB
	let [aliceKycRx, aliceKycTxId] = await kycEnableFcn(aliceId);
	let [bobKyc, bobKycTxId] = await kycEnableFcn(bobId);
	console.log(`\n- Enabling token KYC for Alice's account: ${aliceKycRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${aliceKycTxId}`);
	console.log(`\n- Enabling token KYC for Bob's account: ${bobKyc.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${bobKycTxId}`);
	67898;

	// DISABLE TOKEN KYC FOR ALICE
	let kycDisableTx = await new TokenRevokeKycTransaction().setAccountId(aliceId).setTokenId(tokenId).freezeWith(client).sign(kycKey);
	// let kycDisableSubmitTx = await kycDisableTx.execute(client);
	// let kycDisableRx = await kycDisableSubmitTx.getReceipt(client);
	// console.log(`\n- Disabling token KYC for Alice's account: ${kycDisableRx.status}`);
	// console.log(`- See: https://hashscan.io/${network}/transaction/${kycDisableSubmitTx.transactionId}`);

	// QUERY TO CHECK INTIAL KYC KEY
	var tokenInfo = await tQueryFcn();
	console.log(`\n- KYC key for the NFT is: \n${tokenInfo.kycKey.toString()}`);

	// UPDATE TOKEN PROPERTIES: NEW KYC KEY
	let tokenUpdateTx = await new TokenUpdateTransaction().setTokenId(tokenId).setKycKey(newKycKey.publicKey).freezeWith(client).sign(adminKey);
	let tokenUpdateSubmitTx = await tokenUpdateTx.execute(client);
	let tokenUpdateRx = await tokenUpdateSubmitTx.getReceipt(client);
	console.log(`\n- Token update transaction (new KYC key): ${tokenUpdateRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenUpdateSubmitTx.transactionId}`);

	// QUERY TO CHECK CHANGE IN KYC KEY
	var tokenInfo = await tQueryFcn();
	console.log(`\n- KYC key for the NFT is: \n${tokenInfo.kycKey.toString()}`);

	// PART 2.1 ENDS ============================================================
	console.log(`\nPART 2.1 ENDS ============================================================`);

	// BALANCE CHECK 1
	oB = await bCheckerFcn(treasuryId);
	aB = await bCheckerFcn(aliceId);
	bB = await bCheckerFcn(bobId);
	console.log(`\n- Treasury balance: ${oB[0]} NFTs of ID: ${tokenId} and ${oB[1]}`);
	console.log(`- Alice balance: ${aB[0]} NFTs of ID: ${tokenId} and ${aB[1]}`);
	console.log(`- Bob balance: ${bB[0]} NFTs of ID: ${tokenId} and ${bB[1]}`);

	// 1st TRANSFER NFT Treasury -> Alice
	let tokenTransferTx = await new TransferTransaction().addNftTransfer(tokenId, 2, treasuryId, aliceId).freezeWith(client).sign(treasuryKey);
	let tokenTransferSubmit = await tokenTransferTx.execute(client);
	let tokenTransferRx = await tokenTransferSubmit.getReceipt(client);
	console.log(`\n- NFT transfer Treasury -> Alice status: ${tokenTransferRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenTransferSubmit.transactionId}`);

	// BALANCE CHECK 2
	oB = await bCheckerFcn(treasuryId);
	aB = await bCheckerFcn(aliceId);
	bB = await bCheckerFcn(bobId);
	console.log(`\n- Treasury balance: ${oB[0]} NFTs of ID:${tokenId} and ${oB[1]}`);
	console.log(`- Alice balance: ${aB[0]} NFTs of ID:${tokenId} and ${aB[1]}`);
	console.log(`- Bob balance: ${bB[0]} NFTs of ID:${tokenId} and ${bB[1]}`);

	// 2nd NFT TRANSFER NFT Alice - >Bob
	let nftPrice = new Hbar(10000000, HbarUnit.Tinybar); // 1 HBAR = 10,000,000 Tinybar

	let tokenTransferTx2 = await new TransferTransaction()
		.addNftTransfer(tokenId, 2, aliceId, bobId)
		.addHbarTransfer(aliceId, nftPrice)
		.addHbarTransfer(bobId, nftPrice.negated())
		.freezeWith(client)
		.sign(aliceKey);
	let tokenTransferTx2Sign = await tokenTransferTx2.sign(bobKey);
	let tokenTransferSubmit2 = await tokenTransferTx2Sign.execute(client);
	let tokenTransferRx2 = await tokenTransferSubmit2.getReceipt(client);
	console.log(`\n- NFT transfer Alice -> Bob status: ${tokenTransferRx2.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenTransferSubmit2.transactionId}`);

	// BALANCE CHECK 3
	oB = await bCheckerFcn(treasuryId);
	aB = await bCheckerFcn(aliceId);
	bB = await bCheckerFcn(bobId);
	console.log(`\n- Treasury balance: ${oB[0]} NFTs of ID:${tokenId} and ${oB[1]}`);
	console.log(`- Alice balance: ${aB[0]} NFTs of ID:${tokenId} and ${aB[1]}`);
	console.log(`- Bob balance: ${bB[0]} NFTs of ID:${tokenId} and ${bB[1]}`);

	// PART 2.2 STARTS ============================================================
	console.log(`\nPART 2.2 STARTS ============================================================`);

	// CREATE THE NFT TRANSFER FROM BOB -> ALICE TO BE SCHEDULED
	// REQUIRES ALICE'S AND BOB'S SIGNATURES
	let txToSchedule = new TransferTransaction()
		.addNftTransfer(tokenId, 2, bobId, aliceId)
		.addHbarTransfer(aliceId, nftPrice.negated())
		.addHbarTransfer(bobId, nftPrice);

	// SCHEDULE THE NFT TRANSFER TRANSACTION CREATED IN THE LAST STEP
	let scheduleTx = await new ScheduleCreateTransaction().setScheduledTransaction(txToSchedule).execute(client);
	let scheduleRx = await scheduleTx.getReceipt(client);
	let scheduleId = scheduleRx.scheduleId;
	let scheduledTxId = scheduleRx.scheduledTransactionId;
	console.log(`\n- The schedule ID is: ${scheduleId}`);
	console.log(`- The scheduled transaction ID is: ${scheduledTxId}`);

	// SUBMIT ALICE'S SIGNATURE FOR THE TRANSFER TRANSACTION
	let aliceSignTx = await new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(client).sign(aliceKey);
	let aliceSignSubmit = await aliceSignTx.execute(client);
	let aliceSignRx = await aliceSignSubmit.getReceipt(client);
	console.log(`\n- Status of Alice's signature submission: ${aliceSignRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${aliceSignSubmit.transactionId}`);

	// QUERY TO CONFIRM IF THE SCHEDULE WAS TRIGGERED (SIGNATURES HAVE BEEN ADDED)
	scheduleQuery = await new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
	console.log(`\n- Schedule triggered (all required signatures received): ${scheduleQuery.executed !== null}`);

	// SUBMIT BOB'S SIGNATURE FOR THE TRANSFER TRANSACTION
	let bobSignTx = await new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(client).sign(bobKey);
	let bobSignSubmit = await bobSignTx.execute(client);
	let bobSignRx = await bobSignSubmit.getReceipt(client);
	console.log(`\n- Status of Bob's signature submission: ${bobSignRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${bobSignSubmit.transactionId}`);

	// QUERY TO CONFIRM IF THE SCHEDULE WAS TRIGGERED (SIGNATURES HAVE BEEN ADDED)
	scheduleQuery = await new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
	console.log(`\n- Schedule triggered (all required signatures received): ${scheduleQuery.executed !== null}`);

	// VERIFY THAT THE SCHEDULED TRANSACTION (TOKEN TRANSFER) EXECUTED
	oB = await bCheckerFcn(treasuryId);
	aB = await bCheckerFcn(aliceId);
	bB = await bCheckerFcn(bobId);
	console.log(`\n- Treasury balance: ${oB[0]} NFTs of ID: ${tokenId} and ${oB[1]}`);
	console.log(`- Alice balance: ${aB[0]} NFTs of ID: ${tokenId} and ${aB[1]}`);
	console.log(`- Bob balance: ${bB[0]} NFTs of ID: ${tokenId} and ${bB[1]}`);

	// PART 3 ============================================================
	console.log(`\nPART 3 STARTS ============================================================`);

	// PAUSE ALL TOKEN OEPRATIONS
	let tokenPauseTx = await new TokenPauseTransaction().setTokenId(tokenId).freezeWith(client).sign(pauseKey);
	let tokenPauseSubmitTx = await tokenPauseTx.execute(client);
	let tokenPauseRx = await tokenPauseSubmitTx.getReceipt(client);
	console.log(`\n- Token pause: ${tokenPauseRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenPauseSubmitTx.transactionId}`);

	// TEST THE TOKEN PAUSE BY TRYING AN NFT TRANSFER (TREASURY -> ALICE)
	let tokenTransferTx3 = await new TransferTransaction().addNftTransfer(tokenId, 3, treasuryId, aliceId).freezeWith(client).sign(treasuryKey);
	let tokenTransferSubmit3 = await tokenTransferTx3.execute(client);
	try {
		let tokenTransferRx3 = await tokenTransferSubmit3.getReceipt(client);
		console.log(`\n- NFT transfer Treasury -> Alice status: ${tokenTransferRx3.status}`);
	} catch {
		// TOKEN QUERY TO CHECK PAUSE
		var tokenInfo = await tQueryFcn();
		console.log(`\n- NFT transfer unsuccessful: Token ${tokenId} is paused (${tokenInfo.pauseStatus})`);
		console.log(`- See: https://hashscan.io/${network}/transaction/${tokenTransferSubmit3.transactionId}`);
	}

	// UNPAUSE ALL TOKEN OEPRATIONS
	let tokenUnpauseTx = await new TokenUnpauseTransaction().setTokenId(tokenId).freezeWith(client).sign(pauseKey);
	let tokenUnpauseSubmitTx = await tokenUnpauseTx.execute(client);
	let tokenUnpauseRx = await tokenUnpauseSubmitTx.getReceipt(client);
	console.log(`\n- Token unpause: ${tokenUnpauseRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenUnpauseSubmitTx.transactionId}`);

	// FREEZE ALICE'S ACCOUNT FOR THIS TOKEN
	let tokenFreezeTx = await new TokenFreezeTransaction().setTokenId(tokenId).setAccountId(aliceId).freezeWith(client).sign(freezeKey);
	let tokenFreezeSubmitTx = await tokenFreezeTx.execute(client);
	let tokenFreezeRx = await tokenFreezeSubmitTx.getReceipt(client);
	console.log(`\n- Freeze Alice's account for token ${tokenId}: ${tokenFreezeRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenFreezeSubmitTx.transactionId}`);

	// TEST THE TOKEN FREEZE FOR THE ACCOUNT BY TRYING A TRANSFER (ALICE -> BOB)
	let tokenTransferTx4 = await new TransferTransaction()
		.addNftTransfer(tokenId, 2, aliceId, bobId)
		.addHbarTransfer(aliceId, nftPrice)
		.addHbarTransfer(bobId, nftPrice.negated())
		.freezeWith(client)
		.sign(aliceKey);
	let tokenTransferTx4Sign = await tokenTransferTx4.sign(bobKey);
	let tokenTransferSubmit4 = await tokenTransferTx4Sign.execute(client);
	try {
		let tokenTransferRx4 = await tokenTransferSubmit4.getReceipt(client);
		console.log(`\n- NFT transfer Alice -> Bob status: ${tokenTransferRx4.status}`);
	} catch {
		console.log(`\n- NFT transfer Alice -> Bob unsuccessful: Alice's account is frozen for this token`);
		console.log(`- See: https://hashscan.io/${network}/transaction/${tokenTransferSubmit4.transactionId}`);
	}
	// UNFREEZE ALICE'S ACCOUNT FOR THIS TOKEN
	let tokenUnfreezeTx = await new TokenUnfreezeTransaction().setTokenId(tokenId).setAccountId(aliceId).freezeWith(client).sign(freezeKey);
	let tokenUnfreezeSubmitTx = await tokenUnfreezeTx.execute(client);
	let tokenUnfreezeRx = await tokenUnfreezeSubmitTx.getReceipt(client);
	console.log(`\n- Unfreeze Alice's account for token ${tokenId}: ${tokenUnfreezeRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenUnfreezeSubmitTx.transactionId}`);

	// WIPE THE TOKEN FROM ALICE'S ACCOUNT
	let tokenWipeTx = await new TokenWipeTransaction().setAccountId(aliceId).setTokenId(tokenId).setSerials([2]).freezeWith(client).sign(wipeKey);
	let tokenWipeSubmitTx = await tokenWipeTx.execute(client);
	let tokenWipeRx = await tokenWipeSubmitTx.getReceipt(client);
	console.log(`\n- Wipe token ${tokenId} from Alice's account: ${tokenWipeRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenWipeSubmitTx.transactionId}`);

	// CHECK ALICE'S BALANCE
	aB = await bCheckerFcn(aliceId);
	console.log(`\n- Alice balance: ${aB[0]} NFTs of ID:${tokenId} and ${aB[1]}`);

	// TOKEN QUERY TO CHECK TOTAL TOKEN SUPPLY
	var tokenInfo = await tQueryFcn();
	console.log(`- Current NFT supply: ${tokenInfo.totalSupply}`);

	// DELETE THE TOKEN
	let tokenDeleteTx = new TokenDeleteTransaction().setTokenId(tokenId).freezeWith(client);
	let tokenDeleteSign = await tokenDeleteTx.sign(adminKey);
	let tokenDeleteSubmitTx = await tokenDeleteSign.execute(client);
	let tokenDeleteRx = await tokenDeleteSubmitTx.getReceipt(client);
	console.log(`\n- Delete token ${tokenId}: ${tokenDeleteRx.status}`);
	console.log(`- See: https://hashscan.io/${network}/transaction/${tokenDeleteSubmitTx.transactionId}`);

	// TOKEN QUERY TO CHECK DELETION
	var tokenInfo = await tQueryFcn();
	console.log(`\n- Token ${tokenId} is deleted: ${tokenInfo.isDeleted}`);

	console.log(`\n- THE END ============================================================`);
	console.log(`\n- 👇 Go to:`);
	console.log(`- 🔗 www.hedera.com/discord\n`);

	client.close();

	// ACCOUNT CREATOR FUNCTION ==========================================
	async function accountCreateFcn(pvKey, iBal, client) {
		const response = await new AccountCreateTransaction()
			.setInitialBalance(iBal)
			.setKey(pvKey.publicKey)
			.setMaxAutomaticTokenAssociations(10)
			.execute(client);
		const receipt = await response.getReceipt(client);
		return [receipt.status, receipt.accountId];
	}

	// TOKEN MINTER FUNCTION ==========================================
	async function tokenMinterFcn(CIDs) {
		let mintTx = new TokenMintTransaction().setTokenId(tokenId).setMetadata(CIDs).freezeWith(client);
		let mintTxSign = await mintTx.sign(supplyKey);
		let mintTxSubmit = await mintTxSign.execute(client);
		let mintRx = await mintTxSubmit.getReceipt(client);
		return [mintRx, mintTxSubmit.transactionId];
	}

	// BALANCE CHECKER FUNCTION ==========================================
	async function bCheckerFcn(id) {
		balanceCheckTx = await new AccountBalanceQuery().setAccountId(id).execute(client);
		return [balanceCheckTx.tokens._map.get(tokenId.toString()), balanceCheckTx.hbars];
	}

	// KYC ENABLE FUNCTION ==========================================
	async function kycEnableFcn(id) {
		let kycEnableTx = await new TokenGrantKycTransaction().setAccountId(id).setTokenId(tokenId).freezeWith(client).sign(kycKey);
		let kycSubmitTx = await kycEnableTx.execute(client);
		let kycRx = await kycSubmitTx.getReceipt(client);
		return [kycRx, kycSubmitTx.transactionId];
	}

	// TOKEN QUERY FUNCTION ==========================================
	async function tQueryFcn() {
		var tokenInfo = await new TokenInfoQuery().setTokenId(tokenId).execute(client);
		return tokenInfo;
	}
}
main();

Additional Resources

Get a .

Set up your environment .

✅ If you want the entire code used for this tutorial, skip to the section below.

The prevents a token from being involved in any kind of operation across all accounts. Specifying a <pauseKey> during the creation of a token is a requirement to be able to pause token operations. The code below shows you that this key must sign the pause transaction. Note that you can’t pause a token if it doesn’t have a pause key. Also keep in mind that if this key was not set during token creation, then a token update to add this key is not possible.

In our example below, we pause the token, test that by trying a token transfer and checking the token pauseStatus, and then we to enable operations again.

stops "freezes" transfers of that token for a specific account ID. Note that this transaction must be signed by the <freezeKey> of the token. Once a freeze executes, the specified account is marked as “Frozen” and will not be able to receive or send tokens unless unfrozen.

In our example below, we first freeze Alice’s account for the token ID we’re working with, test the freeze by trying a token transfer, and then Alice’s account so she can transact the token again.

wipes the provided amount of fungible or non-fungible tokens from the specified account. You see from the code below that this transaction must be signed by the token's <wipeKey>.

In this case, we wipe the NFT that Alice currently holds. We then check Alice’s balance and the NFT supply to see how these change with the wipe operation (these two values before the wipe are provided for comparison – see for the details).

After you , it’s no longer possible to perform any operations for that token, and transactions resolve to the error TOKEN_WAS_DELETED. Note that the token remains in the ledger, and you can still retrieve some information about it.

The delete operation must be signed by the token <adminKey>. Remember from that if this key is not set during token creation, then the token is immutable and deletion is not possible.

In this article, you saw key capabilities to help you manage your HTS tokens, including how to: pause, freeze, wipe, and delete tokens. If you haven’t already, check out and of this tutorial series to see examples of how to do even more with HTS – you will see how to mint NFTs, transfer NFTs, perform token KYC, schedule transactions, and more.

Continue learning more in our !

➡

➡ Have a question? Ask on

Hedera testnet account
here
pause transaction
unpause the token
Freezing a token
unfreeze
This operation
Part 2
delete a token
Part 1
Part 1
Part 2
learning center
Project Repository
StackOverflow
Code Check

Writer: Ed, DevRel Engineer

Editor: Krystal, Technical Writer

Part 1
Part 2

|

|

GitHub
LinkedIn
GitHub
Twitter
Know Your Customer (KYC)