forked from ed-marquez/hedera-example-hts-nft-blog-p1-p2-p3
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnft-part3.js
More file actions
384 lines (334 loc) · 17.5 KB
/
nft-part3.js
File metadata and controls
384 lines (334 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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.fromString(process.env.OPERATOR_PVKEY);
const network = process.env.NETWORK;
const client = Client.forNetwork(network).setOperator(operatorId, operatorKey);
client.setDefaultMaxTransactionFee(new Hbar(100));
client.setMaxQueryPayment(new Hbar(50));
async function main() {
// CREATE NEW HEDERA ACCOUNTS TO REPRESENT OTHER USERS
const initBalance = new Hbar(2);
const treasuryKey = PrivateKey.generateED25519();
const [treasurySt, treasuryId] = await accountCreateFcn(treasuryKey, initBalance, client);
console.log(`- Treasury's account: https://hashscan.io/testnet/account/${treasuryId}`);
const aliceKey = PrivateKey.generateED25519();
const [aliceSt, aliceId] = await accountCreateFcn(aliceKey, initBalance, client);
console.log(`- Alice's account: https://hashscan.io/testnet/account/${aliceId}`);
const bobKey = PrivateKey.generateED25519();
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.generate();
const adminKey = PrivateKey.generate();
const pauseKey = PrivateKey.generate();
const kycKey = PrivateKey.generate();
const newKycKey = PrivateKey.generate();
const freezeKey = PrivateKey.generate();
const wipeKey = PrivateKey.generate();
// DEFINE CUSTOM FEE SCHEDULE
let nftCustomFee = new CustomRoyaltyFee()
.setNumerator(5)
.setDenominator(10)
.setFeeCollectorAccountId(treasuryId)
.setFallbackFee(new CustomFixedFee().setHbarAmount(new Hbar(200)));
// IPFS CONTENT IDENTIFIERS FOR WHICH WE WILL CREATE NFTs
CID = [
"QmNPCiNA3Dsu3K5FxDPMG5Q3fZRwVTg14EXA92uqEeSRXn",
"QmZ4dgAgt8owvnULxnKxNe8YqpavtVCXmc1Lt2XajFpJs9",
"QmPzY5GxevjyfMUF5vEAjtyRoigzWp47MiKAtLBduLMC1T",
"Qmd3kGgSrAwwSrhesYcY7K54f3qD7MDo38r7Po2dChtQx5",
"QmWgkKz3ozgqtnvbCLeh7EaR1H8u5Sshx3ZJzxkcrT3jbw",
];
// CREATE NFT WITH CUSTOM FEE
let nftCreate = await new TokenCreateTransaction()
.setTokenName("Fall Collection")
.setTokenSymbol("LEAF")
.setTokenType(TokenType.NonFungibleUnique)
.setDecimals(0)
.setInitialSupply(0)
.setTreasuryAccountId(treasuryId)
.setSupplyType(TokenSupplyType.Finite)
.setMaxSupply(CID.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 nftCreate.sign(adminKey);
let nftCreateSubmit = await nftCreateTxSign.execute(client);
let nftCreateRx = await nftCreateSubmit.getReceipt(client);
let tokenId = nftCreateRx.tokenId;
console.log(`Created NFT with Token ID: ${tokenId} \n`);
// TOKEN QUERY TO CHECK THAT THE CUSTOM FEE SCHEDULE IS ASSOCIATED WITH NFT
var tokenInfo = await tQueryFcn();
console.table(tokenInfo.customFees[0]);
// MINT NEW BATCH OF NFTs
nftLeaf = [];
for (var i = 0; i < CID.length; i++) {
nftLeaf[i] = await tokenMinterFcn(CID[i]);
console.log(`Created NFT ${tokenId} with serial: ${nftLeaf[i].serials[0].low}`);
}
// BURN THE LAST NFT IN THE COLLECTION
let tokenBurnTx = await new TokenBurnTransaction().setTokenId(tokenId).setSerials([CID.length]).freezeWith(client).sign(supplyKey);
let tokenBurnSubmit = await tokenBurnTx.execute(client);
let tokenBurnRx = await tokenBurnSubmit.getReceipt(client);
console.log(`\nBurn NFT with serial ${CID.length}: ${tokenBurnRx.status}`);
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}`);
// 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(`- Bob NFT manual association: ${associateBobRx.status}`);
// PART 2.1 STARTS ============================================================
console.log(`\nPART 2.1 STARTS ============================================================\n`);
// ENABLE TOKEN KYC FOR ALICE AND BOB
let aliceKyc = await kycEnableFcn(aliceId);
let bobKyc = await kycEnableFcn(bobId);
console.log(`- Enabling token KYC for Alice's account: ${aliceKyc.status}`);
console.log(`- Enabling token KYC for Bob's account: ${bobKyc.status}\n`);
// // 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(`- Disabling token KYC for Alice's account: ${kycDisableRx.status} \n`);
// QUERY TO CHECK INTIAL KYC KEY
var tokenInfo = await tQueryFcn();
console.log(`- KYC key for the NFT is: \n${tokenInfo.kycKey.toString()} \n`);
// 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(`- Token update transaction (new KYC key): ${tokenUpdateRx.status} \n`);
// QUERY TO CHECK CHANGE IN KYC KEY
var tokenInfo = await tQueryFcn();
console.log(`- KYC key for the NFT is: \n${tokenInfo.kycKey.toString()}`);
// PART 2.1 ENDS ============================================================
console.log(`\nPART 2.1 ENDS ============================================================\n`);
// BALANCE CHECK 1
oB = await bCheckerFcn(treasuryId);
aB = await bCheckerFcn(aliceId);
bB = await bCheckerFcn(bobId);
console.log(`- 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} \n`);
// BALANCE CHECK 2
oB = await bCheckerFcn(treasuryId);
aB = await bCheckerFcn(aliceId);
bB = await bCheckerFcn(bobId);
console.log(`- 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 tokenTransferTx2 = await new TransferTransaction()
.addNftTransfer(tokenId, 2, aliceId, bobId)
.addHbarTransfer(aliceId, 100)
.addHbarTransfer(bobId, -100)
.freezeWith(client)
.sign(aliceKey);
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} \n`);
// BALANCE CHECK 3
oB = await bCheckerFcn(treasuryId);
aB = await bCheckerFcn(aliceId);
bB = await bCheckerFcn(bobId);
console.log(`- 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 ============================================================\n`);
// 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, -200).addHbarTransfer(bobId, 200);
// 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(`- The schedule ID is: ${scheduleId}`);
console.log(`- The scheduled transaction ID is: ${scheduledTxId} \n`);
// 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(`- Status of Alice's signature submission: ${aliceSignRx.status}`);
// QUERY TO CONFIRM IF THE SCHEDULE WAS TRIGGERED (SIGNATURES HAVE BEEN ADDED)
scheduleQuery = await new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
console.log(`- 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(`- Status of Bob's signature submission: ${bobSignRx.status}`);
// QUERY TO CONFIRM IF THE SCHEDULE WAS TRIGGERED (SIGNATURES HAVE BEEN ADDED)
scheduleQuery = await new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
console.log(`- Schedule triggered (all required signatures received): ${scheduleQuery.executed !== null} \n`);
// VERIFY THAT THE SCHEDULED TRANSACTION (TOKEN TRANSFER) EXECUTED
oB = await bCheckerFcn(treasuryId);
aB = await bCheckerFcn(aliceId);
bB = await bCheckerFcn(bobId);
console.log(`- 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 ============================================================\n`);
// 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}`);
// 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} \n`);
} catch {
// TOKEN QUERY TO CHECK PAUSE
var tokenInfo = await tQueryFcn();
console.log(`- NFT transfer unsuccessful: Token ${tokenId} is paused (${tokenInfo.pauseStatus})`);
}
// 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(`- Token unpause: ${tokenUnpauseRx.status}\n`);
// FREEZE ALICE'S ACCOUNT FOR THIS TOKEN
let tokenFreezeTx = await new TokenFreezeTransaction().setTokenId(tokenId).setAccountId(aliceId).freezeWith(client).sign(freezeKey);
let tokenFreezeSubmit = await tokenFreezeTx.execute(client);
let tokenFreezeRx = await tokenFreezeSubmit.getReceipt(client);
console.log(`- Freeze Alice's account for token ${tokenId}: ${tokenFreezeRx.status}`);
// TEST THE TOKEN FREEZE FOR THE ACCOUNT BY TRYING A TRANSFER (ALICE -> BOB)
try {
let tokenTransferTx4 = await new TransferTransaction()
.addNftTransfer(tokenId, 2, aliceId, bobId)
.addHbarTransfer(aliceId, 100)
.addHbarTransfer(bobId, -100)
.freezeWith(client)
.sign(aliceKey);
let tokenTransferTx4Sign = await tokenTransferTx4.sign(bobKey);
let tokenTransferSubmit4 = await tokenTransferTx4Sign.execute(client);
let tokenTransferRx4 = await tokenTransferSubmit4.getReceipt(client);
console.log(`\n-NFT transfer Alice->Bob status: ${tokenTransferRx4.status} \n`);
} catch {
console.log(`- Operation unsuccessful: The account is frozen for this token`);
}
// UNFREEZE ALICE'S ACCOUNT FOR THIS TOKEN
let tokenUnfreezeTx = await new TokenUnfreezeTransaction().setTokenId(tokenId).setAccountId(aliceId).freezeWith(client).sign(freezeKey);
let tokenUnfreezeSubmit = await tokenUnfreezeTx.execute(client);
let tokenUnfreezeRx = await tokenUnfreezeSubmit.getReceipt(client);
console.log(`- Unfreeze Alice's account for token ${tokenId}: ${tokenUnfreezeRx.status}\n`);
// 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(`- Wipe token ${tokenId} from Alice's account: ${tokenWipeRx.status}`);
// CHECK ALICE'S BALANCE
aB = await bCheckerFcn(aliceId);
console.log(`- 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 = 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}`);
// TOKEN QUERY TO CHECK DELETION
var tokenInfo = await tQueryFcn();
console.log(`- Token ${tokenId} is deleted: ${tokenInfo.isDeleted}`);
// 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(CID) {
mintTx = await new TokenMintTransaction()
.setTokenId(tokenId)
.setMetadata([Buffer.from(CID)])
.freezeWith(client);
let mintTxSign = await mintTx.sign(supplyKey);
let mintTxSubmit = await mintTxSign.execute(client);
let mintRx = await mintTxSubmit.getReceipt(client);
return mintRx;
}
// 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;
}
// TOKEN QUERY FUNCTION ==========================================
async function tQueryFcn() {
var tokenInfo = await new TokenInfoQuery().setTokenId(tokenId).execute(client);
return tokenInfo;
}
}
main();