-
Notifications
You must be signed in to change notification settings - Fork 1
/
neo-course.js
429 lines (395 loc) · 12.2 KB
/
neo-course.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
const { tx, wallet, CONST, rpc, sc, u } = require('@cityofzion/neon-core')
const { Command } = require('commander')
const defaultSystemFee = 0
const defaultNetworkFee = 0
const networkMagic = CONST.MAGIC_NUMBER.TestNet
const NS_CONTRACT_HASH = '50ac1c37690cc2cfc594472833cf57505d5f46de' // Name Service
const NS_CONTRACT_ADDRESS = '0x50ac1c37690cc2cfc594472833cf57505d5f46de'
const URL = process.env.URL
if (typeof URL === 'undefined') {
console.log('The URL environment variable is not defined.')
process.exit(1)
}
const privateKey = process.env.PRIVATE_KEY
if (typeof privateKey === 'undefined') {
console.log('The PRIVATE_KEY environment variable is not defined.')
process.exit(1)
}
const recordTypes = {
ipv4: 1,
cn: 5,
text: 16,
ipv6: 28
}
async function checkNetworkFee (client, transaction) {
const feePerByteInvokeResponse = await client.invokeFunction(
CONST.NATIVE_CONTRACT_HASH.PolicyContract,
'getFeePerByte'
)
if (feePerByteInvokeResponse.state !== 'HALT') {
if (defaultNetworkFee === 0) {
throw new Error('Unable to retrieve data to calculate network fee.')
} else {
console.log(
'\u001b[31m ✗ Unable to get information to calculate network fee. Using user provided value.\u001b[0m'
)
transaction.networkFee = u.BigInteger.fromNumber(defaultNetworkFee)
}
}
const feePerByte = u.BigInteger.fromNumber(
feePerByteInvokeResponse.stack[0].value
)
// Account for witness size
const transactionByteSize = transaction.serialize().length / 2 + 109
// Hardcoded. Running a witness is always the same cost for the basic account.
const witnessProcessingFee = u.BigInteger.fromNumber(1000390)
const networkFeeEstimate = feePerByte
.mul(transactionByteSize)
.add(witnessProcessingFee)
if (defaultNetworkFee && networkFeeEstimate.compare(defaultNetworkFee) <= 0) {
transaction.networkFee = u.BigInteger.fromNumber(defaultNetworkFee)
console.log(
` i Node indicates ${networkFeeEstimate.toDecimal(
8
)} networkFee but using user provided value of ${defaultNetworkFee}`
)
} else {
transaction.networkFee = networkFeeEstimate
}
console.log(
`\u001b[32m ✓ Network Fee set: ${transaction.networkFee.toDecimal(
8
)} \u001b[0m`
)
}
async function checkSystemFee (client, transaction, fromAccount) {
const invokeFunctionResponse = await client.invokeScript(
u.HexString.fromHex(transaction.script),
[
{
account: fromAccount.scriptHash,
scopes: tx.WitnessScope.CalledByEntry
}
]
)
if (invokeFunctionResponse.state !== 'HALT') {
throw new Error(`Script errored out: ${invokeFunctionResponse.exception}`)
}
const requiredSystemFee = u.BigInteger.fromNumber(
invokeFunctionResponse.gasconsumed
)
if (defaultSystemFee && requiredSystemFee.compare(defaultSystemFee) <= 0) {
transaction.systemFee = u.BigInteger.fromNumber(defaultSystemFee)
console.log(
` i Node indicates ${requiredSystemFee} systemFee but using user provided value of ${defaultSystemFee}`
)
} else {
transaction.systemFee = requiredSystemFee
}
console.log(
`\u001b[32m ✓ SystemFee set: ${transaction.systemFee.toDecimal(
8
)}\u001b[0m`
)
}
async function getRoots (rpcClient) {
const query = new rpc.Query({
method: 'invokefunction',
params: [NS_CONTRACT_ADDRESS, 'roots']
})
const response = await rpcClient.execute(query)
const iteratorId = response.stack[0].id
const sessionId = response.session
return { iteratorId, sessionId }
}
async function isAvailable (rpcClient, name) {
const query = new rpc.Query({
method: 'invokefunction',
params: [
NS_CONTRACT_ADDRESS,
'isAvailable',
[{ type: 'String', value: name }]
]
})
const response = await rpcClient.execute(query)
if (response.exception != null) {
console.log(response.exception)
process.exit(0)
}
return response.stack[0].value
}
async function getPrice (rpcClient, length) {
const query = new rpc.Query({
method: 'invokefunction',
params: [
NS_CONTRACT_ADDRESS,
'getPrice',
[
{
type: 'Integer',
value: length
}
],
[]
]
})
const response = await rpcClient.execute(query)
return transformGasDecimal(response.stack[0].value)
}
async function sendTransaction (rpcClient, account, operation, params) {
const args = params.map((param) => {
return sc.ContractParam[param.type](param.value)
})
const script = sc.createScript({
scriptHash: NS_CONTRACT_HASH,
operation,
args
})
const currentHeight = await rpcClient.getBlockCount()
console.log(`Current height: ${currentHeight}`)
const transaction = new tx.Transaction({
signers: [
{
account: account.scriptHash,
scopes: tx.WitnessScope.CalledByEntry
}
],
validUntilBlock: currentHeight + 1000,
script
})
await checkNetworkFee(rpcClient, transaction)
await checkSystemFee(rpcClient, transaction, account)
const signedTransaction = transaction.sign(account, networkMagic)
const result = await rpcClient.sendRawTransaction(
u.HexString.fromHex(signedTransaction.serialize(true)).toBase64()
)
console.log(`Transaction hash: ${result}`)
}
async function resolve (rpcClient, domainName, type) {
const query = new rpc.Query({
method: 'invokefunction',
params: [
NS_CONTRACT_ADDRESS,
'resolve',
[
{
type: 'String',
value: domainName
},
{
type: 'Integer',
value: type
}
]
]
})
const response = await rpcClient.execute(query)
return response
}
async function getRecord (rpcClient, domainName, type) {
const query = new rpc.Query({
method: 'invokefunction',
params: [
NS_CONTRACT_ADDRESS,
'resolve',
[
{
type: 'String',
value: domainName
},
{
type: 'Integer',
value: type
}
]
]
})
const response = await rpcClient.execute(query)
return response
}
async function traverseIterator (rpcClient, sessionId, iteratorId, pageSize) {
const response = []
let iter = []
do {
iter = await rpcClient.traverseIterator(sessionId, iteratorId, pageSize)
response.push(...iter)
} while (iter.length > 0)
return response
}
function base64hex2str (value) {
return u.hexstring2str(u.base642hex(value))
}
function transformGasDecimal (num) {
if (num.length <= 8) {
return '0.' + num.padStart(8, '0')
}
const decimalPoint = num.length - 8
return (
num.substring(0, decimalPoint) +
'.' +
num.substring(decimalPoint, num.length)
)
}
function checkDomainName (name) {
// eslint-disable-next-line no-control-regex
const isAscii = /^[\x00-\x7F]*$/.test(name)
if (!isAscii) {
console.log(`${name} is not a valid domain name`)
process.exit(0)
}
const endsWithNeo = name.endsWith('.neo')
if (!endsWithNeo) {
console.log(`${name} is not a valid domain name`)
process.exit(0)
}
}
function checkType (type) {
if (!Object.keys(recordTypes).includes(type)) {
console.log('Type must be one of: ipv4, cn, text, and ipv6')
process.exit(0)
}
}
(async () => {
const account = new wallet.Account(privateKey)
console.log(`Address: ${account.address} / 0x${account.scriptHash}`)
const rpcClient = new rpc.RPCClient(URL)
const program = new Command()
program
.name('nns-cli')
.description('CLI for the Neo Name Service API')
.version('0.0.1')
program
.command('get-roots')
.description('Get roots')
.action(async () => {
const getRootsResponse = await getRoots(rpcClient)
const iterableResponse = await traverseIterator(
rpcClient,
getRootsResponse.sessionId,
getRootsResponse.iteratorId,
10
)
for (item of iterableResponse) {
console.log(base64hex2str(item.value))
}
})
program
.command('is-available')
.description('Checks if a second-level domain is available')
.argument('name', 'Domain name')
.action(async (name) => {
checkDomainName(name)
if (await isAvailable(rpcClient, name)) {
console.log(`${name} is available`)
} else {
console.log(`${name} isn't available`)
}
})
program
.command('get-price')
.description('Retrieves the price for registering a second-level domain.')
.argument('name', 'Domain name')
.action(async (name) => {
checkDomainName(name)
console.log(
`The price for registering ${name} is ${await getPrice(
rpcClient,
name.length
)}`
)
})
program
.command('register')
.description('Register a second-level domain')
.argument('name', 'Domain name')
.action(async (name) => {
checkDomainName(name)
const params = [{ type: 'string', value: name }, { type: 'hash160', value: account.address }]
await sendTransaction(rpcClient, account, 'register', params)
})
program
.command('set-record')
.description('Sets a record for a second-level domain or its subdomains.')
.argument('name', 'Domain name')
.argument('type', 'Type must be one of: ipv4, cn, text, and ipv6')
.argument('data', 'The corresponding data')
.action(async (name, type, data) => {
checkDomainName(name)
checkType(type)
if (!Object.keys(recordTypes).includes(type)) {
console.log('Type must be one of: ipv4, cn, text, and ipv6')
process.exit(0)
}
const params = [{ type: 'string', value: name }, { type: 'integer', value: recordTypes[type] }, { type: 'string', value: data }]
await sendTransaction(rpcClient, account, 'setRecord', params)
})
program
.command('resolve')
.description(
'Resolves the record of a second-level domain with the specific type.'
)
.argument('name', 'Domain name')
.argument('type', 'Type must be one of: ipv4, cn, text, or ipv6.')
.action(async (name, type) => {
checkDomainName(name)
checkType(type)
const response = await resolve(rpcClient, name, recordTypes[type])
console.log(base64hex2str(response.stack[0].value))
})
program
.command('get-record')
.description(
'Gets the record of a second-level domain with the specific type.'
)
.argument('name', 'Domain name')
.argument('type', 'Type must be one of: ipv4, cn, text, or ipv6.')
.action(async (name, type) => {
checkDomainName(name)
checkType(type)
const response = await getRecord(rpcClient, name, recordTypes[type])
console.log(base64hex2str(response.stack[0].value))
})
program
.command('renew')
.description(
'Extends the validity period of a domain.'
)
.argument('name', 'Domain name')
.argument('years', 'The address to transfer to')
.action(async (name, years) => {
checkDomainName(name)
if (years < 1 || years > 1) {
console.log('Please enter a number between 1 and 10.')
process.exit(0)
}
const params = [{ type: 'string', value: name }, { type: 'integer', value: years }]
await sendTransaction(rpcClient, account, 'renew', params)
})
program
.command('set-admin')
.description(
'Sets the administrator for a second-level domain.'
)
.argument('name', 'Domain name')
.argument('admin', 'The administrator that the owner specifies.')
.action(async (name, admin) => {
checkDomainName(name)
const params = [{ type: 'string', value: name }, { type: 'hash160', value: admin }]
await sendTransaction(rpcClient, account, 'setAdmin', params)
// await setAdmin(rpcClient, account, name, admin)
})
program
.command('transfer')
.description(
'Transfers a domain from the owner address to another address.'
)
.argument('name', 'Domain name')
.argument('to', 'The address to transfer to')
.argument('data', 'The data information used after transfer.')
.action(async (name, to, data) => {
checkDomainName(name)
const params = [{ type: 'hash160', value: to }, { type: 'string', value: name }, { type: 'string', value: data }]
await sendTransaction(rpcClient, account, 'transfer', params)
})
program.parse()
})()