forked from Burstall/hedera-nft-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransferFT.js
253 lines (206 loc) · 6.56 KB
/
transferFT.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
const {
Client,
PrivateKey,
AccountId,
TransferTransaction,
TransactionId,
TokenId,
} = require('@hashgraph/sdk');
require('dotenv').config();
const { fetch } = require('cross-fetch');
const { requestMultiSig } = require('./reqMultiSig.js');
let baseUrl;
const maxRetries = Number(process.env.MAX_RETRY) || 3;
const operatorId = AccountId.fromString(process.env.MY_ACCOUNT_ID);
const operatorKey = PrivateKey.fromString(process.env.MY_PRIVATE_KEY);
const env = process.env.ENVIRONMENT || null;
const readlineSync = require('readline-sync');
let client;
let isApproval = false;
let multiSig = false;
let onBehalfOfAccount;
async function main() {
if (getArgFlag('h')) {
console.log('Usage: node transferFT.js -rec 0.0.XXXX -amt Z -token 0.0.TTTT [-memo \'ABC DEF\' ] [-multisig] [-approval 0.0.YYY]');
// console.log('Usage: node transferHbar.js [-sender 0.0.ZZZ] -rec 0.0.XXXX -amt Z [-memo \'ABC DEF\' ] [-multisig]');
// console.log(' -sender overide the account sending - will require additional signatures');
console.log(' -rec address of the receving account');
console.log(' -amt amount to send');
console.log(' -token token to send');
console.log(' -multisig flag to look for multisig signing');
console.log(' -approval spend hbar from the account assuming allowance approved');
process.exit(0);
}
multiSig = getArgFlag('multisig');
isApproval = getArgFlag('approval');
const memo = getArg('memo');
let sender;
if (getArgFlag('sender')) {
// turn on multi sig function to colect additional signatures
multiSig = true;
sender = AccountId.fromString(getArg('sender'));
}
else {
sender = operatorId;
}
const tokenId = TokenId.fromString(getArg('token'));
const receiver = AccountId.fromString(getArg('rec'));
if (!receiver) {
console.log('Must specify receiver - exiting');
process.exit(1);
}
const amount = Number(getArg('amt'));
if (!receiver) {
console.log('Must specify amount - exiting');
process.exit(1);
}
if (!env || !operatorId || !operatorKey) {
console.log('Please check environment variables ar set -> MY_PRIVATE_KEY / MY_PRIVATE_KEY / ENVIRONMENT');
process.exit(1);
}
console.log(`- Using account: ${sender} as sender`);
console.log('- Receiver:', receiver.toString());
console.log('- paying tx fees:', operatorId.toString());
console.log('- Amount:', amount);
console.log('- Using ENVIRONMENT:', env);
if (isApproval) {
onBehalfOfAccount = AccountId.fromString(getArg('approval'));
console.log('- Approval spend on behalf of:', onBehalfOfAccount.toString());
}
if (env == 'TEST') {
client = Client.forTestnet();
console.log('Transfer FT in *TESTNET*');
baseUrl = 'https://testnet.mirrornode.hedera.com';
}
else if (env == 'MAIN') {
client = Client.forMainnet();
console.log('Transfer FT in *MAINNET*');
baseUrl = 'https://mainnet-public.mirrornode.hedera.com';
}
else {
console.log('ERROR: Must specify either MAIN or TEST as environment in .env file');
return;
}
const [tokenType, tokenDecimal, tokenName] = await getTokenType(tokenId);
if (tokenType == 'NON_FUNGIBLE_UNIQUE') {
console.log('Script designed for FT not NFT - exiting');
process.exit(1);
}
console.log('- Sending:', tokenType, 'Decimal:', tokenDecimal, 'Name:', tokenName);
client.setOperator(operatorId, operatorKey);
const proceed = readlineSync.keyInYNStrict('Do you want to make the transfer?');
if (proceed) {
const result = await transferFungibleFcn(tokenId, sender, receiver, amount * (10 ** tokenDecimal), memo);
if (result) {
console.log('\n-Transfer completed');
}
else {
console.log('\n-**FAILED**');
}
}
else {
console.log('User aborted');
return;
}
}
/**
* Helper method for the hbar transfer
* @param {TokenId} tokenId
* @param {AccountId} sender
* @param {AccountId} receiver
* @param {Number} amount
* @param {string} memo
* @param {boolean} multiSig default false, set true if to spit out bytes and take the returned signed ones
* @returns {boolean} outcome of the requested transfer
*/
async function transferFungibleFcn(tokenId, sender, receiver, amount, memo = null) {
// add signature documented to require only single node to be used.
const nodeId = [];
nodeId.push(new AccountId(3));
const transferTx = new TransferTransaction()
.addTokenTransfer(tokenId, receiver, amount)
.setNodeAccountIds(nodeId)
.setTransactionId(TransactionId.generate(operatorId));
if (isApproval) {
transferTx.addApprovedTokenTransfer(tokenId, onBehalfOfAccount, -amount);
}
else {
transferTx.addTokenTransfer(tokenId, sender, -amount);
}
if (memo) {
transferTx.setTransactionMemo(memo);
}
transferTx.freezeWith(client);
let transferSigned;
if (multiSig) {
// request other signatures
transferSigned = await requestMultiSig(transferTx);
}
else {
console.log('\n-Single signing\n');
transferSigned = await transferTx.sign(operatorKey);
}
const transferSubmit = await transferSigned.execute(client);
const transferRx = await transferSubmit.getReceipt(client);
return transferRx.status.toString() == 'SUCCESS' ? true : false;
}
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;
}
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
};
async function getTokenType(tokenId) {
const routeUrl = `/api/v1/tokens/${tokenId}`;
const tokenDetailJSON = await fetchJson(baseUrl + routeUrl);
return [tokenDetailJSON.type, tokenDetailJSON.decimals, tokenDetailJSON.name];
}
async function fetchJson(url, depth = 0) {
if (depth >= maxRetries) return null;
depth++;
try {
const res = await fetchWithTimeout(url);
if (res.status != 200) {
// console.log(depth, url, res);
await sleep(1000 * depth);
return await fetchJson(url, depth);
}
return res.json();
}
catch (err) {
await sleep(1000 * 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;
}
main()
.then(() => {
process.exit(0);
})
.catch(error => {
console.error(error);
process.exit(1);
});