forked from Burstall/hedera-nft-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallowanceSetCheckRevoke.js
388 lines (329 loc) · 11.9 KB
/
allowanceSetCheckRevoke.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
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
385
386
387
388
const {
Client,
PrivateKey,
AccountId,
AccountAllowanceApproveTransaction,
Hbar,
NftId,
TokenId,
} = require('@hashgraph/sdk');
const exit = require('node:process');
require('dotenv').config();
const fetch = require('cross-fetch');
/**
https://testnet.mirrornode.hedera.com/api/v1/tokens/0.0.47540431/nfts
hbar allowances
https://testnet.mirrornode.hedera.com/api/v1/accounts/0.0.2777997/allowances/crypto
FT allowances
https://testnet.mirrornode.hedera.com/api/v1/accounts/0.0.2777997/allowances/tokens
...no url for NFT allowances
0.0.47698672
*/
const maxRetries = 5;
const testBaseURL = 'https://testnet.mirrornode.hedera.com';
const mainBaseURL = 'https://mainnet-public.mirrornode.hedera.com';
const allowanceURL = '/api/v1/accounts/';
const allowanceFTEnd = '/allowances/tokens?limit=100';
const allowanceNFTEnd = '/allowances/crypto?limit=100';
const tokensURL = '/api/v1/tokens/';
let verbose = false;
const addressRegex = /(0\.0\.[1-9][0-9]+)/i;
let env;
function getArg(arg) {
const customIndex = process.argv.indexOf(`-${arg}`);
let customValue;
if (customIndex > -1) {
// Retrieve the value after --custom
customValue = process.argv[customIndex + 1];
}
return customValue;
}
function getArgFlag(arg) {
const customIndex = process.argv.indexOf(`-${arg}`);
if (customIndex > -1) {
return true;
}
return false;
}
async function fetchJson(url, depth = 0) {
if (depth >= maxRetries) return null;
depth++;
try {
const res = await fetchWithTimeout(url);
if (res.status != 200) {
if (depth > 4) console.log(depth, url, res);
await sleep(2000 * depth);
return await fetchJson(url, depth);
}
return res.json();
}
catch (err) {
await sleep(3000 * depth);
return await fetchJson(url, depth);
}
}
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 30000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal,
});
clearTimeout(id);
return response;
}
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
};
function readyClient() {
const operatorId = AccountId.fromString(process.env.MY_ACCOUNT_ID);
const operatorKey = PrivateKey.fromString(process.env.MY_PRIVATE_KEY);
// If we weren't able to grab it, we should throw a new error
if (operatorId == null ||
operatorKey == null) {
throw new Error('Environment variables for account ID / PKs must be present');
}
console.log(`Using wallet ${operatorId} to pay / sign`);
let client;
if (env == 'TEST') {
client = Client.forTestnet();
console.log('- Processing allowances in *TESTNET*');
}
else if (env == 'MAIN') {
client = Client.forMainnet();
console.log('- Processing allowances in *MAINNET*');
}
else {
console.log('ERROR: Must specify either MAIN or TEST as environment in .env file');
return;
}
client.setOperator(operatorId, operatorKey);
return [client, operatorId, operatorKey];
}
async function revoke(tokenId = null) {
// TODO: const [client, operatorId, operatorKey] = readyClient();
// casn only revoke 20 serials in a transaction
// https://docs.hedera.com/guides/docs/sdks/cryptocurrency/adjust-an-allowance
if (tokenId) {
// remove allowances for the specified token only
}
else {
// remove all allowances.
}
}
async function setNFTAllowance(wallet, tokenIdString, serialsList, allSerialsArg = false) {
const tokenId = TokenId.fromString(tokenIdString);
const [client, operatorId, operatorKey] = readyClient();
// https://docs.hedera.com/guides/docs/sdks/cryptocurrency/approve-an-allowance
// **an account is limited to 100 allowances of tokens // no limit on number serials of a given token**
if (allSerialsArg) {
const transaction = new AccountAllowanceApproveTransaction()
.approveTokenNftAllowanceAllSerials(tokenId, operatorId, wallet);
console.log(`Setting *NFT* allowance for ${wallet} to spend **ALL** NFTs of ${tokenId} on behalf of ${operatorId}`);
transaction.freezeWith(client);
const signTx = await transaction.sign(operatorKey);
const txResponse = await signTx.execute(client);
const receipt = await txResponse.getReceipt(client);
const transactionStatus = receipt.status;
console.log('The transaction consensus status is ' + transactionStatus.toString());
}
else {
// note - only 20 serials can be set in a single transaction
for (let outer = 0; outer < serialsList.length; outer = outer + 20) {
const transaction = new AccountAllowanceApproveTransaction();
const txSerialsList = [];
for (let inner = 0; (outer + inner) < serialsList.length; inner++) {
const nftId = new NftId(tokenId, serialsList[inner + outer]);
txSerialsList.push(nftId.serial);
console.log(nftId);
transaction.approveTokenNftAllowance(nftId, operatorId, wallet);
}
console.log(`Setting *NFT* allowance for ${wallet} to spend ${txSerialsList.length} serials (${txSerialsList}) of NFT ${tokenId} on behalf of ${operatorId}`);
transaction.freezeWith(client);
const signTx = await transaction.sign(operatorKey);
const txResponse = await signTx.execute(client);
const receipt = await txResponse.getReceipt(client);
const transactionStatus = receipt.status;
console.log('The transaction consensus status is ' + transactionStatus.toString());
}
}
}
async function setFungibleAllowance(wallet, tokenId, amount) {
const [client, operatorId, operatorKey] = readyClient();
// note - only 20 serials can be set in a single transaction
// https://docs.hedera.com/guides/docs/sdks/cryptocurrency/approve-an-allowance
// **an account is limited to 100 allowances of tokens // no limit on number serials of a given token**
const transaction = new AccountAllowanceApproveTransaction()
.approveTokenAllowance(tokenId, operatorId, wallet, amount);
console.log(`Setting *FT* allowance for ${wallet} to spend ${amount} of FT ${tokenId} on behalf of ${operatorId}`);
transaction.freezeWith(client);
const signTx = await transaction.sign(operatorKey);
const txResponse = await signTx.execute(client);
const receipt = await txResponse.getReceipt(client);
const transactionStatus = receipt.status;
console.log('The transaction consensus status is ' + transactionStatus.toString());
}
async function setHbarAllowance(wallet, amount) {
const [client, operatorId, operatorKey] = readyClient();
const transaction = new AccountAllowanceApproveTransaction()
.approveHbarAllowance(operatorId, wallet, Hbar.from(amount));
console.log(`Setting *HBAR* allowance for ${wallet} to spend ${amount} Hbar on behalf of ${operatorId}`);
transaction.freezeWith(client);
const signTx = await transaction.sign(operatorKey);
const txResponse = await signTx.execute(client);
const receipt = await txResponse.getReceipt(client);
const transactionStatus = receipt.status;
console.log('The transaction consensus status is ' + transactionStatus.toString());
}
async function isTokenNFT(baseUrl, tokenId) {
const routeUrl = tokensURL + tokenId;
if (verbose) console.log('checking token type:', baseUrl + routeUrl);
const tokenDetailJSON = await fetchJson(baseUrl + routeUrl);
const tokenType = tokenDetailJSON.type;
if (tokenType === 'NON_FUNGIBLE_UNIQUE') {
return true;
}
else {
return false;
}
}
async function getAllowances(wallet, baseUrl, isNFT) {
let routeUrl;
if (isNFT) {
routeUrl = allowanceURL + wallet + allowanceNFTEnd;
}
else {
routeUrl = allowanceURL + wallet + allowanceFTEnd;
}
if (verbose) { console.log(baseUrl + routeUrl);}
do {
const json = await fetchJson(baseUrl + routeUrl);
if (json == null) {
console.log('FATAL ERROR: no Allowances found', baseUrl + routeUrl);
// unlikely to get here but a sensible default
return;
}
const allowances = json.allowances;
console.log('Allowances found:', allowances.length);
for (let a = 0; a < allowances.length; a++) {
const value = allowances[a];
console.log(value);
}
routeUrl = json.links.next;
}
while (routeUrl);
}
async function main() {
const help = getArgFlag('h');
if (help) {
console.log('Usage: node alowanceSetCheckRevoke.js [-t 0.0.XXX] [-w 0.0.WWW] [-revoke [-hbar]] [-set 0.0.ZZZZ [-serial Q | -all | -hbar <amt> | -amt <amt>] [-v]');
console.log(' -t <tokenId> token to check allowances of (defaults: ALL)');
console.log(' -w <walletId> wallet to check allowances of (default: MY_ACCOUNT_ID fron .env)');
console.log(' -revoke revokes allowances for the token specified or **ALL** allowances');
console.log(' -hbar revoke only hbar allowances');
console.log(' -set <walletId> set new allowance for the token specified (-t) to the stated wallet');
console.log(' -serial Q required if the token is a NFT. Q can be single serial (e.g. 4) or comma seperated list (e.g. 4,9,11) or range using - (e.g. 2-8)');
console.log(' -all set approval for all serials owned of a given NFT');
console.log(' -hbar <amt> set approval for "amt" of hbar');
console.log(' -amt <amt> set approval of "amt" of Fungible token');
exit.exit(0);
}
verbose = getArgFlag('v');
// load from env file
const myAccountId = process.env.MY_ACCOUNT_ID;
// overide from command line or fall back to env file value
const acctId = getArgFlag('w') ? getArg('w') : myAccountId;
const walletId = acctId.match(addressRegex)[0];
env = process.env.ENVIRONMENT.toUpperCase() || null;
let baseUrl;
if (env == 'TEST') {
console.log('- Checking allowances in *TESTNET*');
baseUrl = testBaseURL;
}
else if (env == 'MAIN') {
console.log('- Checking allowances in *MAINNET*');
baseUrl = mainBaseURL;
}
else {
console.log('ERROR: Must specify either MAIN or TEST as environment in .env file');
return;
}
if (getArgFlag('set') && getArgFlag('revoke')) {
console.log('Please pick revoke **OR** set and run again - can\'t do both so exiting');
exit.exit(1);
}
const tokenArg = getArg('t') || null;
let tokenId;
const serialsArg = getArg('serial') || null;
let serialsList = [];
const allSerialsArg = getArg('all') || null;
// check if this is an NFT, if so has serial been set?
let isNFT;
if (tokenArg) {
tokenId = tokenArg.match(addressRegex)[0];
console.log('Using token:', tokenId);
isNFT = await isTokenNFT(baseUrl, tokenId);
}
else {
isNFT = false;
}
// TODO decide format and merge? isNFT
await getAllowances(walletId, baseUrl, true);
await getAllowances(walletId, baseUrl, false);
if (getArgFlag('set')) {
const setArg = getArg('set');
const allowWallet = setArg.match(addressRegex)[0];
if (getArgFlag('hbar')) {
const amt = getArg('hbar');
await setHbarAllowance(allowWallet, amt);
}
else if (!tokenArg) {
console.log('Must specify a token to set allowances for using: -t 0.0.XXX');
exit.exit(1);
}
else if (isNFT) {
if (allSerialsArg) {
await setNFTAllowance(allowWallet, tokenId, serialsList, true);
}
else {
if (!serialsArg) {
console.log('ERROR: must specify a serial to set an allowance for NFT:', tokenId);
}
else if (isNFT && allSerialsArg) {
serialsList = [];
}
else if (isNFT && serialsArg.includes('-')) {
// inclusive range
const rangeSplit = serialsArg.split('-');
for (let i = rangeSplit[0]; i <= rangeSplit[1]; i++) {
serialsList.push(`${i}`);
}
}
else if (isNFT && serialsArg.includes(',')) {
serialsList = serialsArg.split(',');
}
else if (isNFT) {
// only one serial to check
serialsList = [serialsArg];
}
await setNFTAllowance(allowWallet, tokenId, serialsList, false);
}
}
else {
const amtArg = getArg('amt') || null;
if (amtArg) {
const amt = Number(amtArg);
await setFungibleAllowance(allowWallet, tokenId, amt);
}
else {
console.log(`Error: must specify the amnount (XXX) of an FT to allow -> node alowanceSetCheckRevoke.js -t ${tokenId} -set ${allowWallet} -amt XXX`);
exit.exit(1);
}
}
}
if (getArgFlag(revoke)) {
await revoke(tokenArg ? tokenId : null);
}
}
main();