Hedera
Search…
Create and Transfer Your First NFT

Summary

Using the Hedera Token Service you can create non-fungible tokens (NFTs). NFTs are uniquely identifiable. On the Hedera network, the token ID represents a collection of NFTs of the same class, and the serial number of each token uniquely identifies each NFT in the class.
We recommend you complete the following introduction to get a basic understanding of Hedera transactions. This example does not build upon the previous examples.

1. Create a Non-Fungible Token (NFT)

Use TokenCreateTransaction() to configure and set the token properties. At a minimum, this constructor requires setting a name, symbol, and treasury account ID. All other fields are optional, so if they’re not specified then default values are used. For instance, not specifying an admin key, makes a token immutable (can’t change or add properties); not specifying a supply key, makes a token supply fixed (can’t mint new or burn existing tokens); not specifying a token type, makes a token fungible.
After submitting the transaction to the Hedera network, you can obtain the new token ID by requesting the receipt. This token ID represents an NFT class.
Java
JavaScript
Go
1
//Create the NFT
2
TokenCreateTransaction nftCreate = new TokenCreateTransaction()
3
.setTokenName("diploma")
4
.setTokenSymbol("GRAD")
5
.setTokenType(TokenType.NON_FUNGIBLE_UNIQUE)
6
.setDecimals(0)
7
.setInitialSupply(0)
8
.setTreasuryAccountId(treasuryId)
9
.setSupplyType(TokenSupplyType.FINITE)
10
.setMaxSupply(250)
11
.setSupplyKey(supplyKey)
12
.freezeWith(client);
13
​
14
​
15
//Sign the transaction with the treasury key
16
TokenCreateTransaction nftCreateTxSign = nftCreate.sign(treasuryKey);
17
​
18
//Submit the transaction to a Hedera network
19
TransactionResponse nftCreateSubmit = nftCreateTxSign.execute(client);
20
​
21
//Get the transaction receipt
22
TransactionReceipt nftCreateRx = nftCreateSubmit.getReceipt(client);
23
​
24
//Get the token ID
25
TokenId tokenId = nftCreateRx.tokenId;
26
​
27
//Log the token ID
28
System.out.println("Created NFT with token ID " +tokenId);
Copied!
1
//Create the NFT
2
let nftCreate = await new TokenCreateTransaction()
3
.setTokenName("diploma")
4
.setTokenSymbol("GRAD")
5
.setTokenType(TokenType.NonFungibleUnique)
6
.setDecimals(0)
7
.setInitialSupply(0)
8
.setTreasuryAccountId(treasuryId)
9
.setSupplyType(TokenSupplyType.Finite)
10
.setMaxSupply(250)
11
.setSupplyKey(supplyKey)
12
.freezeWith(client);
13
​
14
//Sign the transaction with the treasury key
15
let nftCreateTxSign = await nftCreate.sign(treasuryKey);
16
​
17
//Submit the transaction to a Hedera network
18
let nftCreateSubmit = await nftCreateTxSign.execute(client);
19
​
20
//Get the transaction receipt
21
let nftCreateRx = await nftCreateSubmit.getReceipt(client);
22
​
23
//Get the token ID
24
let tokenId = nftCreateRx.tokenId;
25
​
26
//Log the token ID
27
console.log(`- Created NFT with Token ID: ${tokenId} \n`);
Copied!
1
//Create the NFT
2
nftCreate, err := hedera.NewTokenCreateTransaction().
3
SetTokenName("diploma").
4
SetTokenSymbol("GRAD").
5
SetTokenType(hedera.TokenTypeNonFungibleUnique).
6
SetDecimals(0).
7
SetInitialSupply(0).
8
SetTreasuryAccountID(treasuryAccountId).
9
SetSupplyType(hedera.TokenSupplyTypeFinite).
10
SetMaxSupply(250).
11
SetSupplyKey(supplyKey).
12
FreezeWith(client)
13
​
14
//Sign the transaction with the treasury key
15
nftCreateTxSign := nftCreate.Sign(treasuryKey)
16
​
17
//Submit the transaction to a Hedera network
18
nftCreateSubmit, err := nftCreateTxSign.Execute(client)
19
​
20
//Get the transaction receipt
21
nftCreateRx, err := nftCreateSubmit.GetReceipt(client)
22
​
23
//Get the token ID
24
tokenId := *nftCreateRx.TokenID
25
​
26
//Log the token ID
27
fmt.Println("Created NFT with token ID ", tokenId)
Copied!

2. Mint a New NFT

When creating an NFT, the decimals and initial supply must be set to zero. After the token is created, you mint each NFT using the token mint operation. Specifying a supply key during token creation is a requirement to be able to mint and burn tokens. The supply key is required to sign mint and burn transactions.
Both the NFT image and metadata live in the InterPlanetary File System (IPFS), which provides decentralized storage. The file diploma_metadata.json contains the metadata for the NFT. A content identifier (CID) pointing to the metadata file is used during minting of the new NFT. Notice that the metadata file contains a URI pointing to the NFT image.
Java
JavaScript
Go
1
// IPFS content identifiers for which we will create a NFT
2
String CID = ("QmTzWcVfk88JRqjTpVwHzBeULRTNzHY7mnBSG42CpwHmPa") ;
3
​
4
// Mint a new NFT
5
TokenMintTransaction mintTx = new TokenMintTransaction()
6
.setTokenId(tokenId)
7
.addMetadata(CID.getBytes())
8
.freezeWith(client);
9
​
10
//Sign transaction with the supply key
11
TokenMintTransaction mintTxSign = mintTx.sign(supplyKey);
12
​
13
//Submit the transaction to a Hedera network
14
TransactionResponse mintTxSubmit = mintTxSign.execute(client);
15
​
16
//Get the transaction receipt
17
TransactionReceipt mintRx = mintTxSubmit.getReceipt(client);
18
​
19
//Log the serial number
20
System.out.println("Created NFT " +tokenId + "with serial: " +mintRx.serials);
21
Copied!
1
//IPFS content identifiers for which we will create a NFT
2
CID = "QmTzWcVfk88JRqjTpVwHzBeULRTNzHY7mnBSG42CpwHmPa";
3
​
4
// Mint new NFT
5
let mintTx = await new TokenMintTransaction()
6
.setTokenId(tokenId)
7
.setMetadata([Buffer.from(CID)])
8
.freezeWith(client);
9
​
10
//Sign the transaction with the supply key
11
let mintTxSign = await mintTx.sign(supplyKey);
12
​
13
//Submit the transaction to a Hedera network
14
let mintTxSubmit = await mintTxSign.execute(client);
15
​
16
//Get the transaction receipt
17
let mintRx = await mintTxSubmit.getReceipt(client);
18
​
19
//Log the serial number
20
console.log(`- Created NFT ${tokenId} with serial: ${mintRx.serials[0].low} \n`);
Copied!
1
//IPFS content identifiers for which we will create a NFT
2
CID := "QmTzWcVfk88JRqjTpVwHzBeULRTNzHY7mnBSG42CpwHmPa"
3
​
4
//Mint new NFT
5
mintTx, err := hedera.NewTokenMintTransaction().
6
SetTokenID(tokenId).
7
SetMetadata([]byte(CID)).
8
FreezeWith(client)
9
​
10
//Sign the transaction with the supply key
11
mintTxSign := mintTx.Sign(supplyKey)
12
​
13
//Submit the transaction to a Hedera network
14
mintTxSubmit, err := mintTxSign.Execute(client)
15
​
16
//Get the transaction receipt
17
mintRx, err := mintTxSubmit.GetReceipt(client)
18
​
19
//Log the serial number
20
fmt.Print("Created NFT ", tokenId, " with serial: ", mintRx.SerialNumbers)o
Copied!
diploma_metadata.json
1
{
2
"name": "Diploma",
3
"description": "Certificate of Graduation",
4
"image": "https://ipfs.io/ipfs/QmdTNJDYePd4EUUzYPuhc1GsDELjab6ypgvDQAp4visoM9?filename=diploma.jpg",
5
"properties": {
6
"university": "H State University",
7
"college": "Engineering and Applied Sciences",
8
"level": "Masters",
9
"field": "Mechanical Engineering",
10
"honors": "yes",
11
"honorsType": "Summa Cum Laude",
12
"gpa": "3.84",
13
"student": "Alice",
14
"date": "2021-03-18"
15
}
16
}
Copied!

3. Associate User Accounts with the NFT

Before an account that is not the treasury for a token can receive or send this specific token ID, the account must become β€œassociated” with the token. To associate a token to an account the account owner must sign the associate transaction.
If you have an account with the automatic token association property set you do not need to associate the token before transferring it the receiving account.
Java
JavaScript
Go
1
//Create the associate transaction and sign with Alice's key
2
TokenAssociateTransaction associateAliceTx = new TokenAssociateTransaction()
3
.setAccountId(aliceAccountId)
4
.setTokenIds(Collections.singletonList(tokenId))
5
.freezeWith(client)
6
.sign(aliceKey);
7
​
8
//Submit the transaction to a Hedera network
9
TransactionResponse associateAliceTxSubmit = associateAliceTx.execute(client);
10
​
11
//Get the transaction receipt
12
TransactionReceipt associateAliceRx = associateAliceTxSubmit.getReceipt(client);
13
​
14
//Confirm the transaction was successful
15
System.out.println("NFT association with Alice's account: " +associateAliceRx.status);
Copied!
1
//Create the associate transaction and sign with Alice's key
2
let associateAliceTx = await new TokenAssociateTransaction()
3
.setAccountId(aliceId)
4
.setTokenIds([tokenId])
5
.freezeWith(client)
6
.sign(aliceKey);
7
​
8
//Submit the transaction to a Hedera network
9
let associateAliceTxSubmit = await associateAliceTx.execute(client);
10
​
11
//Get the transaction receipt
12
let associateAliceRx = await associateAliceTxSubmit.getReceipt(client);
13
​
14
//Confirm the transaction was successful
15
console.log(`- NFT association with Alice's account: ${associateAliceRx.status}\n`);
Copied!
1
//Create the associate transaction
2
associateAliceTx, err := hedera.NewTokenAssociateTransaction().
3
SetAccountID(aliceAccountId).
4
SetTokenIDs(tokenId).
5
FreezeWith(client)
6
​
7
//Sign with Alice's key
8
signTx := associateAliceTx.Sign(aliceKey)
9
​
10
//Submit the transaction to a Hedera network
11
associateAliceTxSubmit, err := signTx.Execute(client)//Get the transaction receipt
12
​
13
//Get the transaction receipt
14
associateAliceRx, err := associateAliceTxSubmit.GetReceipt(client)
15
​
16
//Confirm the transaction was successful
17
fmt.Println("NFT association with Alice's account:", associateAliceRx.Status)
Copied!

4. Transfer the NFT

Now, transfer the NFT and check the account balances before and after the send! After the transfer you should expect to the NFT to be removed from the treasury account and available in Alice's account. The treasury account key has to sign the transfer transaction to authorize the transfer to Alice's account.
Java
JavaScript
Go
1
// Check the balance before the transfer for the treasury account
2
AccountBalance balanceCheckTreasury = new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
3
System.out.println("Treasury balance: " +balanceCheckTreasury.tokens + "NFTs of ID " +tokenId);
4
​
5
// Check the balance before the transfer for Alice's account
6
AccountBalance balanceCheckAlice = new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client);
7
System.out.println("Alice's balance: " +balanceCheckAlice.tokens + "NFTs of ID " +tokenId);
8
​
9
// Transfer the NFT from treasury to Alice
10
// Sign with the treasury key to authorize the transfer
11
TransferTransaction tokenTransferTx = new TransferTransaction()
12
.addNftTransfer( new NftId(tokenId, 1), treasuryId, aliceAccountId)
13
.freezeWith(client)
14
.sign(treasuryKey);
15
​
16
TransactionResponse tokenTransferSubmit = tokenTransferTx.execute(client);
17
TransactionReceipt tokenTransferRx = tokenTransferSubmit.getReceipt(client);
18
​
19
System.out.println("NFT transfer from Treasury to Alice: " +tokenTransferRx.status);
20
​
21
// Check the balance of the treasury account after the transfer
22
AccountBalance balanceCheckTreasury2 = new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
23
System.out.println("Treasury balance: " +balanceCheckTreasury2.tokens + "NFTs of ID " + tokenId);
24
​
25
// Check the balance of Alice's account after the transfer
26
AccountBalance balanceCheckAlice2 = new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client);
27
System.out.println("Alice's balance: " +balanceCheckAlice2.tokens + "NFTs of ID " +tokenId);
Copied!
1
// Check the balance before the transfer for the treasury account
2
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
3
console.log(`- Treasury balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
4
​
5
// Check the balance before the transfer for Alice's account
6
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(aliceId).execute(client);
7
console.log(`- Alice's balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
8
​
9
// Transfer the NFT from treasury to Alice
10
// Sign with the treasury key to authorize the transfer
11
let tokenTransferTx = await new TransferTransaction()
12
.addNftTransfer(tokenId, 1, treasuryId, aliceId)
13
.freezeWith(client)
14
.sign(treasuryKey);
15
​
16
let tokenTransferSubmit = await tokenTransferTx.execute(client);
17
let tokenTransferRx = await tokenTransferSubmit.getReceipt(client);
18
​
19
console.log(`\n- NFT transfer from Treasury to Alice: ${tokenTransferRx.status} \n`);
20
​
21
// Check the balance of the treasury account after the transfer
22
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
23
console.log(`- Treasury balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
24
​
25
// Check the balance of Alice's account after the transfer
26
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(aliceId).execute(client);
27
console.log(`- Alice's balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
Copied!
1
//Transfer the NFT from treasury to Alice
2
tokenTransferTx, err := hedera.NewTransferTransaction().
3
AddNftTransfer(hedera.NftID{TokenID: tokenId, SerialNumber: 1}, treasuryAccountId, aliceAccountId).
4
FreezeWith(client)
5
​
6
//Sign with the treasury key to authorize the transfer
7
signTransferTx := tokenTransferTx.Sign(treasuryKey)
8
​
9
//Submit the transaction
10
tokenTransferSubmit, err := signTransferTx.Execute(client)
11
​
12
//Get the transaction receipt
13
tokenTransferRx, err := tokenTransferSubmit.GetReceipt(client)
14
​
15
//Log the transaction status
16
fmt.Println("NFT transfer from Treasury to Alice:", tokenTransferRx.Status)
17
​
18
// Check the balance of the treasury account after the transfer
19
balanceCheckTreasury2, err := hedera.NewAccountBalanceQuery().SetAccountID(treasuryAccountId).Execute(client)
20
fmt.Println("Treasury balance:", balanceCheckTreasury2.Tokens, "NFTs of ID", tokenId)
21
​
22
// Check the balance of Alice's account after the transfer
23
balanceCheckAlice2, err := hedera.NewAccountBalanceQuery().SetAccountID(aliceAccountId).Execute(client)
24
fmt.Println("Alice's balance:", balanceCheckAlice2.Tokens, "NFTs of ID", tokenId)
Copied!

Code Check βœ…

Java
JavaScript
Go
1
import com.hedera.hashgraph.sdk.*;
2
import io.github.cdimascio.dotenv.Dotenv;
3
​
4
import java.util.Collections;
5
import java.util.List;
6
import java.util.Objects;
7
import java.util.concurrent.TimeoutException;
8
​
9
public class CreateNFTTutorial {
10
​
11
public static void main(String[] args) throws TimeoutException, PrecheckStatusException, ReceiptStatusException {
12
​
13
//Grab your Hedera testnet account ID and private key
14
AccountId myAccountId = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("MY_ACCOUNT_ID")));
15
PrivateKey myPrivateKey = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("MY_PRIVATE_KEY")));
16
​
17
//Create your Hedera testnet client
18
Client client = Client.forTestnet();
19
client.setOperator(myAccountId, myPrivateKey);
20
​
21
//Treasury Key
22
PrivateKey treasuryKey = PrivateKey.generateED25519();
23
PublicKey treasuryPublicKey = treasuryKey.getPublicKey();
24
​
25
//Create treasury account
26
TransactionResponse treasuryAccount = new AccountCreateTransaction()
27
.setKey(treasuryPublicKey)
28
.setInitialBalance(new Hbar(10))
29
.execute(client);
30
​
31
AccountId treasuryId = treasuryAccount.getReceipt(client).accountId;
32
​
33
//Alice Key
34
PrivateKey aliceKey = PrivateKey.generateED25519();
35
PublicKey alicePublicKey = aliceKey.getPublicKey();
36
​
37
//Create Alice's account
38
TransactionResponse aliceAccount = new AccountCreateTransaction()
39
.setKey(alicePublicKey)
40
.setInitialBalance(new Hbar(10))
41
.execute(client);
42
​
43
AccountId aliceAccountId = aliceAccount.getReceipt(client).accountId;
44
​
45
//Supply Key
46
PrivateKey supplyKey = PrivateKey.generateED25519();
47
PublicKey supplyPublicKey = supplyKey.getPublicKey();
48
​
49
//Create the NFT
50
TokenCreateTransaction nftCreate = new TokenCreateTransaction()
51
.setTokenName("diploma")
52
.setTokenSymbol("GRAD")
53
.setTokenType(TokenType.NON_FUNGIBLE_UNIQUE)
54
.setDecimals(0)
55
.setInitialSupply(0)
56
.setTreasuryAccountId(treasuryId)
57
.setSupplyType(TokenSupplyType.FINITE)
58
.setMaxSupply(250)
59
.setSupplyKey(supplyKey)
60
.freezeWith(client);
61
​
62
​
63
//Sign the transaction with the treasury key
64
TokenCreateTransaction nftCreateTxSign = nftCreate.sign(treasuryKey);
65
​
66
//Submit the transaction to a Hedera network
67
TransactionResponse nftCreateSubmit = nftCreateTxSign.execute(client);
68
​
69
//Get the transaction receipt
70
TransactionReceipt nftCreateRx = nftCreateSubmit.getReceipt(client);
71
​
72
//Get the token ID
73
TokenId tokenId = nftCreateRx.tokenId;
74
​
75
//Log the token ID
76
System.out.println("Created NFT with token ID " +tokenId);
77
​
78
// IPFS CONTENT IDENTIFIERS FOR WHICH WE WILL CREATE NFT
79
String CID = ("QmTzWcVfk88JRqjTpVwHzBeULRTNzHY7mnBSG42CpwHmPa") ;
80
​
81
// MINT NEW NFT
82
TokenMintTransaction mintTx = new TokenMintTransaction()
83
.setTokenId(tokenId)
84
.addMetadata(CID.getBytes())
85
.freezeWith(client);
86
​
87
//Sign with the supply key
88
TokenMintTransaction mintTxSign = mintTx.sign(supplyKey);
89
​
90
//Submit the transaction to a Hedera network
91
TransactionResponse mintTxSubmit = mintTxSign.execute(client);
92
​
93
//Get the transaction receipt
94
TransactionReceipt mintRx = mintTxSubmit.getReceipt(client);
95
​
96
//Log the serial number
97
System.out.println("Created NFT " +tokenId + "with serial: " +mintRx.serials);
98
​
99
//Create the associate transaction and sign with Alice's key
100
TokenAssociateTransaction associateAliceTx = new TokenAssociateTransaction()
101
.setAccountId(aliceAccountId)
102
.setTokenIds(Collections.singletonList(tokenId))
103
.freezeWith(client)
104
.sign(aliceKey);
105
​
106
//Submit the transaction to a Hedera network
107
TransactionResponse associateAliceTxSubmit = associateAliceTx.execute(client);
108
​
109
//Get the transaction receipt
110
TransactionReceipt associateAliceRx = associateAliceTxSubmit.getReceipt(client);
111
​
112
//Confirm the transaction was successful
113
System.out.println("NFT association with Alice's account: " +associateAliceRx.status);
114
​
115
// Check the balance before the NFT transfer for the treasury account
116
AccountBalance balanceCheckTreasury = new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
117
System.out.println("Treasury balance: " +balanceCheckTreasury.tokens + "NFTs of ID " +tokenId);
118
​
119
// Check the balance before the NFT transfer for Alice's account
120
AccountBalance balanceCheckAlice = new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client);
121
System.out.println("Alice's balance: " +balanceCheckAlice.tokens + "NFTs of ID " +tokenId);
122
​
123
// Transfer NFT from treasury to Alice
124
// Sign with the treasury key to authorize the transfer
125
TransferTransaction tokenTransferTx = new TransferTransaction()
126
.addNftTransfer( new NftId(tokenId, 1), treasuryId, aliceAccountId)
127
.freezeWith(client)
128
.sign(treasuryKey);
129
​
130
TransactionResponse tokenTransferSubmit = tokenTransferTx.execute(client);
131
TransactionReceipt tokenTransferRx = tokenTransferSubmit.getReceipt(client);
132
​
133
System.out.println("NFT transfer from Treasury to Alice: " +tokenTransferRx.status);
134
​
135
// Check the balance for the treasury account after the transfer
136
AccountBalance balanceCheckTreasury2 = new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
137
System.out.println("Treasury balance: " +balanceCheckTreasury2.tokens + "NFTs of ID " + tokenId);
138
​
139
// Check the balance for Alice's account after the transfer
140
AccountBalance balanceCheckAlice2 = new AccountBalanceQuery().setAccountId(aliceAccountId).execute(client);
141
System.out.println("Alice's balance: " +balanceCheckAlice2.tokens + "NFTs of ID " +tokenId);
142
​
143
}
144
}
Copied!
1
console.clear();
2
require("dotenv").config();
3
const {
4
AccountId,
5
PrivateKey,
6
Client,
7
TokenCreateTransaction,
8
TokenType,
9
TokenSupplyType,
10
TokenMintTransaction,
11
TransferTransaction,
12
AccountBalanceQuery,
13
TokenAssociateTransaction,
14
} = require("@hashgraph/sdk");
15
​
16
// Configure accounts and client, and generate needed keys
17
const operatorId = AccountId.fromString(process.env.OPERATOR_ID);
18
const operatorKey = PrivateKey.fromString(process.env.OPERATOR_PVKEY);
19
const treasuryId = AccountId.fromString(process.env.TREASURY_ID);
20
const treasuryKey = PrivateKey.fromString(process.env.TREASURY_PVKEY);
21
const aliceId = AccountId.fromString(process.env.ALICE_ID);
22
const aliceKey = PrivateKey.fromString(process.env.ALICE_PVKEY);
23
​
24
const client = Client.forTestnet().setOperator(operatorId, operatorKey);
25
​
26
const supplyKey = PrivateKey.generate();
27
​
28
async function main() {
29
//Create the NFT
30
let nftCreate = await new TokenCreateTransaction()
31
.setTokenName("diploma")
32
.setTokenSymbol("GRAD")
33
.setTokenType(TokenType.NonFungibleUnique)
34
.setDecimals(0)
35
.setInitialSupply(0)
36
.setTreasuryAccountId(treasuryId)
37
.setSupplyType(TokenSupplyType.Finite)
38
.setMaxSupply(250)
39
.setSupplyKey(supplyKey)
40
.freezeWith(client);
41
​
42
//Sign the transaction with the treasury key
43
let nftCreateTxSign = await nftCreate.sign(treasuryKey);
44
​
45
//Submit the transaction to a Hedera network
46
let nftCreateSubmit = await nftCreateTxSign.execute(client);
47
​
48
//Get the transaction receipt
49
let nftCreateRx = await nftCreateSubmit.getReceipt(client);
50
​
51
//Get the token ID
52
let tokenId = nftCreateRx.tokenId;
53
​
54
//Log the token ID
55
console.log(`- Created NFT with Token ID: ${tokenId} \n`);
56
​
57
//IPFS content identifiers for which we will create a NFT
58
CID = ["QmTzWcVfk88JRqjTpVwHzBeULRTNzHY7mnBSG42CpwHmPa"];
59
​
60
// Mint new NFT
61
let mintTx = await new TokenMintTransaction()
62
.setTokenId(tokenId)
63
.setMetadata([Buffer.from(CID)])
64
.freezeWith(client);
65
​
66
//Sign the transaction with the supply key
67
let mintTxSign = await mintTx.sign(supplyKey);
68
​
69
//Submit the transaction to a Hedera network
70
let mintTxSubmit = await mintTxSign.execute(client);
71
​
72
//Get the transaction receipt
73
let mintRx = await mintTxSubmit.getReceipt(client);
74
​
75
//Log the serial number
76
console.log(`- Created NFT ${tokenId} with serial: ${mintRx.serials[0].low} \n`);
77
78
//Create the associate transaction and sign with Alice's key
79
let associateAliceTx = await new TokenAssociateTransaction()
80
.setAccountId(aliceId)
81
.setTokenIds([tokenId])
82
.freezeWith(client)
83
.sign(aliceKey);
84
​
85
//Submit the transaction to a Hedera network
86
let associateAliceTxSubmit = await associateAliceTx.execute(client);
87
​
88
//Get the transaction receipt
89
let associateAliceRx = await associateAliceTxSubmit.getReceipt(client);
90
​
91
//Confirm the transaction was successful
92
console.log(`- NFT association with Alice's account: ${associateAliceRx.status}\n`);
93
​
94
​
95
// Check the balance before the transfer for the treasury account
96
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
97
console.log(`- Treasury balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
98
​
99
// Check the balance before the transfer for Alice's account
100
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(aliceId).execute(client);
101
console.log(`- Alice's balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
102
​
103
// Transfer the NFT from treasury to Alice
104
// Sign with the treasury key to authorize the transfer
105
let tokenTransferTx = await new TransferTransaction()
106
.addNftTransfer(tokenId, 1, treasuryId, aliceId)
107
.freezeWith(client)
108
.sign(treasuryKey);
109
​
110
let tokenTransferSubmit = await tokenTransferTx.execute(client);
111
let tokenTransferRx = await tokenTransferSubmit.getReceipt(client);
112
​
113
console.log(`\n- NFT transfer from Treasury to Alice: ${tokenTransferRx.status} \n`);
114
​
115
// Check the balance of the treasury account after the transfer
116
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(treasuryId).execute(client);
117
console.log(`- Treasury balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
118
​
119
// Check the balance of Alice's account after the transfer
120
var balanceCheckTx = await new AccountBalanceQuery().setAccountId(aliceId).execute(client);
121
console.log(`- Alice's balance: ${balanceCheckTx.tokens._map.get(tokenId.toString())} NFTs of ID ${tokenId}`);
122
}
123
main();
Copied!
1
package main
2
​
3
import (
4
"fmt"
5
"os"
6
​
7
"github.com/hashgraph/hedera-sdk-go/v2"
8
"github.com/joho/godotenv"
9
)
10
​
11
func main() {
12
​
13
//Loads the .env file and throws an error if it cannot load the variables from that file corectly
14
err := godotenv.Load(".env")
15
if err != nil {
16
panic(fmt.Errorf("Unable to load enviroment variables from .env file. Error:\n%v\n", err))
17
}
18
​
19
//Grab your testnet account ID and private key from the .env file
20
myAccountId, err := hedera.AccountIDFromString(os.Getenv("MY_ACCOUNT_ID"))
21
if err != nil {
22
panic(err)
23
}
24
​
25
myPrivateKey, err := hedera.PrivateKeyFromString(os.Getenv("MY_PRIVATE_KEY"))
26
if err != nil {
27
panic(err)
28
}
29
​
30
//Print your testnet account ID and private key to the console to make sure there was no error
31
fmt.Printf("The account ID is = %v\n", myAccountId)
32
fmt.Printf("The private key is = %v\n", myPrivateKey)
33
​
34
//Create your testnet client
35
client := hedera.ClientForTestnet()
36
client.SetOperator(myAccountId, myPrivateKey)
37
​
38
//Create a treasury Key
39
treasuryKey, err := hedera.GeneratePrivateKey()
40
treasuryPublicKey := treasuryKey.PublicKey()
41
​
42
//Create treasury account
43
treasuryAccount, err := hedera.NewAccountCreateTransaction().
44
SetKey(treasuryPublicKey).
45
SetInitialBalance(hedera.NewHbar(10)).
46
Execute(client)
47
48
//Get the receipt of the transaction
49
receipt, err := treasuryAccount.GetReceipt(client)
50
​
51
//Get the account ID
52
treasuryAccountId := *receipt.AccountID
53
​
54
//Alice Key
55
aliceKey, err := hedera.GeneratePrivateKey()
56
alicePublicKey := aliceKey.PublicKey()
57
​
58
//Create Alice's account
59
aliceAccount, err := hedera.NewAccountCreateTransaction().
60
SetKey(alicePublicKey).
61
SetInitialBalance(hedera.NewHbar(10)).
62
Execute(client)
63
64
//Get the receipt of the transaction
65
receipt2, err := aliceAccount.GetReceipt(client)
66
​
67
//Get the account ID
68
aliceAccountId := *receipt2.AccountID
69
​
70
//Create a supply key
71
supplyKey, err := hedera.GeneratePrivateKey()
72
​
73
//Create the NFT
74
nftCreate, err := hedera.NewTokenCreateTransaction().
75
SetTokenName("diploma").
76
SetTokenSymbol("GRAD").
77
SetTokenType(hedera.TokenTypeNonFungibleUnique).
78
SetDecimals(0).
79
SetInitialSupply(0).
80
SetTreasuryAccountID(treasuryAccountId).
81
SetSupplyType(hedera.TokenSupplyTypeFinite).
82
SetMaxSupply(250).
83
SetSupplyKey(supplyKey).
84
FreezeWith(client)
85
​
86
//Sign the transaction with the treasury key
87
nftCreateTxSign := nftCreate.Sign(treasuryKey)
88
​
89
//Submit the transaction to a Hedera network
90
nftCreateSubmit, err := nftCreateTxSign.Execute(client)
91
​
92
//Get the transaction receipt
93
nftCreateRx, err := nftCreateSubmit.GetReceipt(client)
94
​
95
//Get the token ID
96
tokenId := *nftCreateRx.TokenID
97
​
98
//Log the token ID
99
fmt.Println("Created NFT with token ID", tokenId)
100
​
101
// IPFS content identifiers for which we will create a NFT
102
CID := "QmTzWcVfk88JRqjTpVwHzBeULRTNzHY7mnBSG42CpwHmPa"
103
​
104
// Minet new NFT
105
mintTx, err := hedera.NewTokenMintTransaction().
106
SetTokenID(tokenId).
107
SetMetadata([]byte(CID)).
108
FreezeWith(client)
109
​
110
//Sign the transaction with the supply key
111
mintTxSign := mintTx.Sign(supplyKey)
112
​
113
//Submit the transaction to a Hedera network
114
mintTxSubmit, err := mintTxSign.Execute(client)
115
​
116
//Get the transaction receipt
117
mintRx, err := mintTxSubmit.GetReceipt(client)
118
​
119
//Log the serial number
120
fmt.Println("Created NFT", tokenId, "with serial:", mintRx.SerialNumbers)
121
​
122
//Create the associate transaction
123
associateAliceTx, err := hedera.NewTokenAssociateTransaction().
124
SetAccountID(aliceAccountId).
125
SetTokenIDs(tokenId).
126
FreezeWith(client)
127
​
128
//Sign with Alice's key
129
signTx := associateAliceTx.Sign(aliceKey)
130
​
131
//Submit the transaction to a Hedera network
132
associateAliceTxSubmit, err := signTx.Execute(client)
133
​
134
//Get the transaction receipt
135
associateAliceRx, err := associateAliceTxSubmit.GetReceipt(client)
136
​
137
//Confirm the transaction was successful
138
fmt.Println("NFT association with Alice's account:", associateAliceRx.Status)
139
​
140
// Check the balance before the transfer for the treasury account
141
balanceCheckTreasury, err := hedera.NewAccountBalanceQuery().SetAccountID(treasuryAccountId).Execute(client)
142
fmt.Println("Treasury balance:", balanceCheckTreasury.Tokens, "NFTs of ID", tokenId)
143
​
144
// Check the balance before the transfer for Alice's account
145
balanceCheckAlice, err := hedera.NewAccountBalanceQuery().SetAccountID(aliceAccountId).Execute(client)
146
fmt.Println("Alice's balance:", balanceCheckAlice.Tokens, "NFTs of ID", tokenId)
147
​
148
// Transfer the NFT from treasury to Alice
149
tokenTransferTx, err := hedera.NewTransferTransaction().
150
AddNftTransfer(hedera.NftID{TokenID: tokenId, SerialNumber: 1}, treasuryAccountId, aliceAccountId).
151
FreezeWith(client)
152
153
// Sign with the treasury key to authorize the transfer
154
signTransferTx := tokenTransferTx.Sign(treasuryKey)
155
​
156
tokenTransferSubmit, err := signTransferTx.Execute(client)
157
tokenTransferRx, err := tokenTransferSubmit.GetReceipt(client)
158
​
159
fmt.Println("NFT transfer from Treasury to Alice:", tokenTransferRx.Status)
160
​
161
// Check the balance of the treasury account after the transfer
162
balanceCheckTreasury2, err := hedera.NewAccountBalanceQuery().SetAccountID(treasuryAccountId).Execute(client)
163
fmt.Println("Treasury balance:", balanceCheckTreasury2.Tokens, "NFTs of ID", tokenId)
164
​
165
// Check the balance of Alice's account after the transfer
166
balanceCheckAlice2, err := hedera.NewAccountBalanceQuery().SetAccountID(aliceAccountId).Execute(client)
167
fmt.Println("Alice's balance:", balanceCheckAlice2.Tokens, "NFTs of ID", tokenId)
168
​
169
}
170
Copied!