forked from hedera-dev/hedera-code-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-fungible-token-with-metadata.js
79 lines (65 loc) · 2.53 KB
/
create-fungible-token-with-metadata.js
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
const dotenv = require('dotenv');
const fs = require('fs');
dotenv.config();
const {
AccountId,
PrivateKey,
Client,
TokenCreateTransaction,
TokenType,
} = require('@hashgraph/sdk');
const operatorId = AccountId.fromString(process.env.OPERATOR_ID);
const operatorKey = PrivateKey.fromString(process.env.OPERATOR_KEY);
const client = Client.forTestnet().setOperator(operatorId, operatorKey);
const metadataKey = PrivateKey.generate();
console.log(`- Created new metadataKey: ${metadataKey} \n`);
// Update the .env file with METADATA_KEY – comment out if not needed
updateEnvFile('METADATA_KEY', metadataKey.toString());
// Function to create fungible token
async function createFungibleToken() {
let tokenCreateTx = await new TokenCreateTransaction()
.setTokenName("Test")
.setTokenSymbol("TEST")
.setMetadata(Buffer.from(process.env.IPFS_CID))
.setTokenType(TokenType.FungibleCommon)
.setDecimals(3)
.setInitialSupply(10000)
.setTreasuryAccountId(operatorId)
.setMetadataKey(metadataKey)
.freezeWith(client);
let tokenCreateSign = await tokenCreateTx.sign(operatorKey);
let tokenCreateSubmit = await tokenCreateSign.execute(client);
let tokenCreateRx = await tokenCreateSubmit.getReceipt(client);
let tokenId = tokenCreateRx.tokenId;
console.log(`- Created token with ID: ${tokenId} \n`);
// Update the .env file with TOKEN_ID – comment out if not needed
updateEnvFile('TOKEN_ID', tokenId.toString());
}
createFungibleToken().finally(() => {
client.close();
});
// ------------------------------------------------------------
// Helper Functions
// ------------------------------------------------------------
// Helper function to read .env file
function readEnvFile() {
if (fs.existsSync('.env')) {
return fs.readFileSync('.env', 'utf8');
}
return '';
}
// Helper function to update or add a key in the .env file
function updateEnvFile(key, value) {
let envFileContent = readEnvFile();
const keyString = `${key}=${value}\n`;
if (envFileContent.includes(`${key}=`)) {
// Replace the existing key value
const updatedEnvContent = envFileContent.replace(new RegExp(`${key}=.*`), keyString.trim() + '\n');
fs.writeFileSync('.env', updatedEnvContent, 'utf8');
console.log(`${key} updated in .env file.`);
} else {
// Append the new key if it doesn't exist
fs.appendFileSync('.env', '\n' + keyString, 'utf8');
console.log(`${key} added to .env file.`);
}
}