-
Notifications
You must be signed in to change notification settings - Fork 1
/
NeoFairyClient.jsx
1122 lines (1016 loc) · 50.4 KB
/
NeoFairyClient.jsx
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { UInt160, UInt256, Hash160Str, Hash256Str, PublicKeyStr, Signer } from './types';
import { Interpreter } from './interpreters';
import fetchWithTimeout from "../utils/fetchWithTimeout";
//const os = require('os');
//const path = require('path');
//const fs = require('fs');
const default_request_timeout = 1_000;
class VMState {
static BREAK = new VMState('BREAK');
static FAULT = new VMState('FAULT');
static HALT = new VMState('HALT');
static NONE = new VMState('NONE');
constructor(name) {
this.name = name;
}
toString() {
return `VMState.${this.name}`;
}
}
class RpcBreakpoint {
constructor(state, break_reason, scripthash, contract_name, instruction_pointer, source_filename = null, source_line_num = null, source_content = null, exception = null, result_stack = null) {
if (typeof state === 'string') {
this.state = { 'BREAK': VMState.BREAK, 'FAULT': VMState.FAULT, 'HALT': VMState.HALT, 'NONE': VMState.NONE }[state.toUpperCase()];
} else {
this.state = state;
}
this.break_reason = break_reason;
if (typeof scripthash === 'string') {
scripthash = new Hash160Str(scripthash);
}
this.scripthash = scripthash;
this.contract_name = contract_name;
this.instruction_pointer = instruction_pointer;
this.source_filename = source_filename;
this.source_line_num = source_line_num;
this.source_content = source_content;
this.exception = exception;
this.result_stack = result_stack;
}
static from_raw_result(result) {
result = result['result'];
return new RpcBreakpoint(result['state'], result['breakreason'], result['scripthash'], result['contractname'], result['instructionpointer'], result['sourcefilename'], result['sourcelinenum'], result['sourcecontent']);
}
toString() {
if (this.state === VMState.HALT) {
return `RpcBreakpoint ${this.state} ${this.result_stack}`;
}
if (this.source_filename && this.source_line_num) {
return `RpcBreakpoint ${this.state} ${this.source_filename} line ${this.source_line_num} instructionPointer ${this.instruction_pointer}: ${this.source_content}`;
} else {
return `RpcBreakpoint ${this.state} ${this.contract_name} instructionPointer ${this.instruction_pointer};`;
}
}
}
function to_list(element) {
if (Array.isArray(element)) {
return element;
}
if (element !== null && element !== undefined) {
return [element];
}
return [];
}
class FairyClient {
constructor({
target_url = 'http://localhost:16868', // type URL or string
wallet_address_or_scripthash = null,
contract_scripthash = null,
signers = null,
fairy_session = null,
function_default_relay = true,
script_default_relay = false,
confirm_relay_to_blockchain = false,
auto_reset_fairy_session = true,
with_print = true,
verbose_return = false,
//verify_SSL = true,
//requests_session = null,
requests_timeout = default_request_timeout,
auto_set_neo_balance = 10000000000,
auto_set_gas_balance = 10000000000,
auto_preparation = true,
hook_function_after_rpc_call = null,
default_fairy_wallet_scripthash = new Hash160Str('0xd2cefc96ad5cb7b625a0986ef6badde0533731d5')
}) {
this.target_url = target_url;
this.contract_scripthash = contract_scripthash;
//this.requests_session = requests_session;
if (wallet_address_or_scripthash) {
if (wallet_address_or_scripthash.startsWith('N')) {
this.wallet_address = wallet_address_or_scripthash;
this.wallet_scripthash = Hash160Str.from_address(wallet_address_or_scripthash);
} else {
this.wallet_scripthash = wallet_address_or_scripthash;
this.wallet_address = wallet_address_or_scripthash.to_address();
}
this.signers = to_list(signers) || [new Signer(this.wallet_scripthash)];
} else {
this.wallet_address = null;
this.wallet_scripthash = null;
this.signers = signers || [];
//console.log('WARNING: No wallet address specified when building the fairy client!');
}
this.previous_post_data = null;
this.with_print = with_print;
this.previous_raw_result = null;
this.previous_result = null;
this.previous_txBase64Str = null;
this.previous_gas_consumed = null;
this.previous_network_fee = null;
this.verbose_return = verbose_return;
this.function_default_relay = function_default_relay;
this.script_default_relay = script_default_relay;
this.confirm_relay_to_blockchain = confirm_relay_to_blockchain;
this.fairy_session = fairy_session;
//this.verify_SSL = verify_SSL;
this.requests_timeout = requests_timeout;
this.hook_function_after_rpc_call = hook_function_after_rpc_call;
this.default_fairy_wallet_scripthash = default_fairy_wallet_scripthash;
//if (verify_SSL === false) {
// console.log('WARNING: Will ignore SSL certificate errors!');
// urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning);
//}
if (fairy_session && auto_preparation) {
try {
if (auto_reset_fairy_session) {
this.new_snapshots_from_current_system(fairy_session);
this.set_gas_balance(10000000000, fairy_session, default_fairy_wallet_scripthash);
}
if (auto_set_neo_balance && this.wallet_scripthash) {
this.set_neo_balance(auto_set_neo_balance);
}
if (auto_set_gas_balance && this.wallet_scripthash) {
this.set_gas_balance(auto_set_gas_balance);
}
} catch (error) {
console.trace(error);
console.log(`WARNING: Failed at some fairy operations at ${target_url}!`);
}
}
}
set_wallet_address_and_signers(wallet_address, signers = null) {
if (wallet_address instanceof Hash160Str) {
const wallet_scripthash = wallet_address;
this.wallet_scripthash = wallet_address;
this.wallet_address = Hash160Str.to_address(wallet_scripthash);
} else {
this.wallet_address = wallet_address;
const wallet_scripthash = Hash160Str.from_address(wallet_address);
this.wallet_scripthash = wallet_scripthash;
}
this.signers = to_list(signers) || [new Signer(this.wallet_scripthash)];
}
static request_body_builder(method, parameters) {
return JSON.stringify({
"jsonrpc": "2.0",
"method": method,
"params": parameters,
"id": 1
}, (key, value) => { return (typeof value === 'bigint') ? value.toString() : value; });
}
static bytes_to_UInt160(bytestring) {
return Hash160Str.from_UInt160(UInt160.deserialize_from_bytes(bytestring));
}
static base64_struct_to_bytestrs(base64_struct) {
const processed_struct = [];
if (typeof base64_struct === 'object' && base64_struct['type'] === 'Struct') {
const values = base64_struct['value'];
for (const value of values) {
if (value['type'] === 'ByteString') {
processed_struct.push(new TextDecoder().decode(FairyClient.base64ToArrayBuffer(value['value'])));
}
}
}
return processed_struct;
}
async meta_rpc_method_with_raw_result(method, parameters) {
const post_data = FairyClient.request_body_builder(method, parameters);
this.previous_post_data = post_data;
const result = await fetchWithTimeout(this.target_url, { method: "POST", mode: "cors", cache: "no-cache", body: post_data }, this.requests_timeout)
.then(res => res.text())
.then(text => JSON.parse(text));
if ('error' in result) {
throw new Error(result['error']);
}
this.previous_raw_result = result;
this.previous_result = null;
if (this.hook_function_after_rpc_call) {
this.hook_function_after_rpc_call();
}
return result;
}
async meta_rpc_method(method, parameters, relay = null, do_not_raise_on_result = false) {
const post_data = FairyClient.request_body_builder(method, parameters);
this.previous_post_data = post_data;
const result = await fetchWithTimeout(this.target_url, { method: "POST", mode: "cors", cache: "no-cache", body: post_data }, this.requests_timeout )
.then(res => res.text())
.then(text => JSON.parse(text));
if ('error' in result) {
throw new Error(`${result['error']['message']}\r\n${result['error']['data']}`);
}
if (typeof result['result'] === 'object') {
const result_result = result['result'];
if (result_result['gasconsumed']) {
this.previous_gas_consumed = parseInt(result_result['gasconsumed']);
}
if (result_result['networkfee']) {
this.previous_network_fee = parseInt(result_result['networkfee']);
}
if ('exception' in result_result && result_result['exception'] !== null) {
if (do_not_raise_on_result) {
return result_result['exception'];
} else {
console.log(post_data);
console.log(result);
if (result_result['traceback']) {
throw new Error(result_result['traceback']);
} else {
throw new Error(result_result['exception']);
}
}
}
if (relay || (relay === null && this.function_default_relay)) {
if (method === 'invokefunction' || method === 'invokescript') {
if (!('tx' in result_result)) {
throw new Error('No `tx` in response. Did you call `client.openwallet()` before `invokefunction`?');
} else {
const tx = result_result['tx'];
this.previous_txBase64Str = tx;
if (this.confirm_relay_to_blockchain === false || prompt(`Write transaction ${tx} to the actual blockchain instead of Fairy? Y/[n]: `) === "Y") {
this.sendrawtransaction(tx);
}
}
} else {
// this.previous_txBase64Str = null;
}
}
}
this.previous_raw_result = result;
this.previous_result = this.parse_stack_from_raw_result(result);
if (this.hook_function_after_rpc_call) {
this.hook_function_after_rpc_call();
}
if (this.verbose_return) {
return [this.previous_result, result, post_data];
}
return this.previous_result;
}
print_previous_result() {
console.log(this.previous_result);
}
async sendrawtransaction(transaction) {
return await this.meta_rpc_method("sendrawtransaction", [transaction], false);
}
async getrawtransaction(transaction_hash, verbose = false) {
return await this.meta_rpc_method("getrawtransaction", [transaction_hash.toString(), verbose], false);
}
async calculatenetworkfee(txBase64Str) {
return await this.meta_rpc_method("calculatenetworkfee", [txBase64Str], false);
}
get totalfee() {
return this.previous_network_fee + this.previous_gas_consumed;
}
get previous_total_fee() {
return this.totalfee;
}
get previous_system_fee() {
return this.previous_gas_consumed;
}
async openwallet(path, password) {
let open_wallet_result;
if (this.verbose_return) {
const result = await this.meta_rpc_method("openwallet", [path, password]);
[open_wallet_result, , ] = result;
} else {
open_wallet_result = await this.meta_rpc_method("openwallet", [path, password]);
}
if (!open_wallet_result) {
throw new Error(`Failed to open wallet ${path} with given password.`);
}
return open_wallet_result;
}
async closewallet() {
let close_wallet_result;
if (this.verbose_return) {
const result = await this.meta_rpc_method("closewallet", []);
[close_wallet_result, , ] = result;
} else {
close_wallet_result = await this.meta_rpc_method("closewallet", []);
}
if (!close_wallet_result) {
throw new Error('Failed to close wallet.');
}
return close_wallet_result;
}
async traverse_iterator(sid, iid, count = 100) {
const post_data = FairyClient.request_body_builder('traverseiterator', [sid, iid, count]);
this.previous_post_data = post_data;
const result = (await fetchWithTimeout(this.target_url, { options: { method: "POST", mode: "cors", cache: "no-cache", body: post_data }, timeout: this.requests_timeout })
.then(res => res.text())
.then(text => JSON.parse(text)))['result'];
const result_dict = {};
for (const kv of result) {
const [key, value] = kv['value'].map(item => this.parse_single_item(item));
result_dict[key] = value;
}
return result_dict;
}
static base64ToArrayBuffer(base64String) {
var binaryString = window.atob(base64String);
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
parse_single_item(item) {
if ('iterator' in item) {
item = item['iterator'];
if (item) {
if (!Array.isArray(item[0]['value'])) {
return item.map(i => this.parse_single_item(i));
} else {
const result_dict = {};
for (const i of item) {
const [key, value] = i['value'].map(subitem => this.parse_single_item(subitem));
result_dict[key] = value;
}
return result_dict;
}
} else {
if (!(Array.isArray(item) && item.length === 0))
throw new Error(`Unexpected iterator element ${item}`)
return item;
}
}
const _type = item['type'];
let value;
if (_type === 'Any' && !('value' in item)) {
return null;
} else if (_type === 'InteropInterface' && 'id' in item) {
const session = this.previous_raw_result['result']['session'];
const iterator_id = item['id'];
return this.traverse_iterator(session, iterator_id);
} else {
value = item['value'];
}
if (_type === 'Integer') {
return parseInt(value);
} else if (_type === 'Boolean') {
return value;
} else if (_type === 'ByteString' || _type === 'Buffer') {
const byte_value = FairyClient.base64ToArrayBuffer(value);
try {
return new window.TextDecoder("utf-8", { fatal: true }).decode(byte_value);
} catch (error) {
if (byte_value.byteLength === 20) {
return Hash160Str.from_UInt160(UInt160.deserialize_from_bytes(byte_value));
} else if (byte_value.byteLength === 32) {
return Hash256Str.from_UInt256(UInt256.deserialize_from_bytes(byte_value));
} else {
// may be an N3 address starting with 'N'
// TODO: decode to N3 address
return byte_value;
}
}
} else if (_type === 'Array') {
return value.map(i => this.parse_single_item(i));
} else if (_type === 'Struct') {
return value.map(i => this.parse_single_item(i));
} else if (_type === 'Map') {
const result_dict = {};
for (const i of value) {
const [key, mapValue] = [this.parse_single_item(i['key']), this.parse_single_item(i['value'])];
result_dict[key] = mapValue;
}
return result_dict;
} else if (_type === 'Pointer') {
return parseInt(value);
} else {
throw new Error(`Unknown type ${_type}`);
}
}
parse_stack_from_raw_result(raw_result) {
const result = raw_result['result'];
if (typeof result !== 'object' || !('stack' in result)) {
return result;
}
if (!result['stack']) {
return result['stack'];
}
const stack = result['stack'];
if (stack.length > 1) {
// typically happens when we invoke a script calling a series of methods
return stack.map(item => this.parse_single_item(item));
} else {
// if the stack has only 1 item, we simply return the item without a wrapping list
const result_item = stack[0];
return this.parse_single_item(result_item);
}
}
static parse_params(param) {
const type_param = typeof param;
if (param instanceof UInt160) {
return {
'type': 'Hash160',
'value': Hash160Str.from_UInt160(param).toString(),
};
} else if (typeof param === 'string' && /^0x[0-9a-fA-F]{40}$/.test(param)) {
// special case for script hash strings
return {
'type': 'Hash160',
'value': param.toString(),
};
} else if (param instanceof Hash160Str) {
return {
'type': 'Hash160',
'value': param.toString(),
};
} else if (param instanceof UInt256) {
return {
'type': 'Hash256',
'value': Hash256Str.from_UInt256(param).toString(),
};
} else if (param instanceof Hash256Str) {
return {
'type': 'Hash256',
'value': param.toString(),
};
} else if (param instanceof PublicKeyStr) {
return {
'type': 'PublicKey',
'value': param.toString(),
};
} else if (typeof param === 'boolean') {
return {
'type': 'Boolean',
'value': param,
};
} else if (typeof param === 'number') {
return {
'type': 'Integer',
'value': param.toString(),
};
} else if (typeof param === 'string') {
return {
'type': 'String',
'value': param,
};
} else if (param instanceof Uint8Array) {
// not the best way to judge, but maybe no better method
try {
return {
'type': 'String',
'value': new TextDecoder().decode(param),
};
} catch (error) {
return {
'type': 'ByteArray',
'value': FairyClient.all_to_base64(param),
};
}
} else if (Array.isArray(param)) {
return {
'type': 'Array',
'value': param.map(p => FairyClient.parse_params(p)),
};
} else if (type_param === 'object' && param !== null) {
return {
'type': 'Map',
'value': Object.entries(param).map(([k, v]) => ({
'key': FairyClient.parse_params(k),
'value': FairyClient.parse_params(v),
})),
};
} else if (param === null || typeof param === 'undefined') {
return {
'type': 'Any',
};
}
throw new Error(`Unable to handle param ${param} with type ${type_param}`);
}
async invokefunction_of_any_contract(scripthash, operation, params = null, signers = null, relay = null, do_not_raise_on_result = false, with_print = true, fairy_session = null) {
fairy_session = fairy_session || this.fairy_session;
params = params || [];
signers = to_list(signers || this.signers);
if (this.with_print && with_print) {
if (fairy_session) {
console.log(`${fairy_session}::${operation}${JSON.stringify(params)} relay=${relay} ${signers}`);
} else {
console.log(`${operation}${JSON.stringify(params)} relay=${relay} ${signers}`);
}
}
const parameters = [
scripthash.toString(),
operation,
params.map(param => FairyClient.parse_params(param)),
signers.map(signer => signer.to_dict()),
];
let result;
if (fairy_session) {
result = await this.meta_rpc_method('invokefunctionwithsession', [fairy_session, relay || (relay === null && this.function_default_relay), ...parameters], false, do_not_raise_on_result);
} else {
result = await this.meta_rpc_method('invokefunction', parameters, relay || (relay === null && this.function_default_relay), do_not_raise_on_result);
}
return result;
}
async invokefunction(operation, params = null, signers = null, relay = null, do_not_raise_on_result = false, with_print = true, fairy_session = null) {
if (!this.contract_scripthash || this.contract_scripthash.equals(Hash160Str.zero())) {
throw new Error(`Please set client.contract_scripthash before invoking function. Got ${this.contract_scripthash}`);
}
return await this.invokefunction_of_any_contract(this.contract_scripthash, operation, params, signers, relay || (relay === null && this.function_default_relay), do_not_raise_on_result, with_print, fairy_session);
}
async invokemany(call_arguments, signers = null, relay = null, do_not_raise_on_result = false, with_print = true, fairy_session = null) {
fairy_session = fairy_session || this.fairy_session;
if (fairy_session === null || fairy_session === undefined) throw new Error('invokemany only supports sessioned calls for now');
signers = to_list(signers || this.signers);
if (this.with_print && with_print) {
console.log(`${fairy_session}::${JSON.stringify(call_arguments)} relay=${relay} ${signers}`);
}
const parsed_call_arguments = call_arguments.map(call => [
typeof call[0] === 'string' ? call[0] : this.contract_scripthash.toString(),
typeof call[0] === 'string' ? call[1] : call[0],
(call.length >= 3 ? call[2].map(param => FairyClient.parse_params(param)) : []),
]);
return await this.meta_rpc_method('invokemanywithsession', [fairy_session, relay || (relay === null && this.function_default_relay), parsed_call_arguments, signers.map(signer => signer.to_dict())], false, do_not_raise_on_result);
}
async invokescript(script, signers = null, relay = null, fairy_session = null) {
if (typeof script === 'object' && script instanceof Uint8Array) {
script = new TextDecoder().decode(script);
}
signers = to_list(signers || this.signers);
fairy_session = fairy_session || this.fairy_session;
let result;
if (fairy_session) {
relay = relay || (relay === null && this.script_default_relay);
result = await this.meta_rpc_method('invokescriptwithsession', [fairy_session, relay, script, signers.map(signer => signer.to_dict())], false);
} else {
result = await this.meta_rpc_method('invokescript', [script, signers.map(signer => signer.to_dict())], relay || (relay === null && this.script_default_relay));
}
return result;
}
async sendfrom(asset_id, from_address, to_address, value, signers = null) {
signers = to_list(signers || this.signers);
return await this.meta_rpc_method('sendfrom', [
asset_id.toString(),
from_address, to_address, value,
signers.map(signer => signer.to_dict()),
]);
}
async sendtoaddress(asset_id, address, value) {
return await this.meta_rpc_method('sendtoaddress', [
asset_id.toString(), address, value,
]);
}
async send_neo_to_address(to_address, value) {
return await this.sendtoaddress(Hash160Str.fromString("0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5"), to_address.toString(), value);
}
async send_gas_to_address(to_address, value) {
return await this.sendtoaddress(Hash160Str.fromString("0xd2a4cff31913016155e38e474a2c06d08be276cf"), to_address.toString(), value);
}
async getwalletbalance(asset_id) {
return parseInt(await this.meta_rpc_method('getwalletbalance', [asset_id.toString()])['balance']);
}
async get_neo_balance(owner = null, with_print = false) {
return await this.invokefunction_of_any_contract(
Hash160Str.fromString("0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5"),
'balanceOf',
[owner || this.wallet_scripthash],
false,
with_print,
);
// return this.getwalletbalance(Hash160Str.from_UInt160(NeoToken().hash));
}
async get_gas_balance(owner = null, with_print = false) {
return await this.invokefunction_of_any_contract(
Hash160Str.fromString("0xd2a4cff31913016155e38e474a2c06d08be276cf"),
'balanceOf',
[owner || this.wallet_scripthash],
false,
with_print,
);
// return this.getwalletbalance(Hash160Str.from_UInt160(GasToken().hash));
}
async get_nep17token_balance(token_address, owner = null, with_print = false) {
return await this.invokefunction_of_any_contract(token_address, 'balanceOf', [owner || this.wallet_scripthash], false, with_print);
}
async get_nep11token_balance(token_address, tokenId, owner = null, with_print = false) {
return await this.invokefunction_of_any_contract(token_address, 'balanceOf', [owner || this.wallet_scripthash, tokenId], false, with_print);
}
/*
* Fairy features below!
* Mount your neo-cli RpcServer with https://github.com/Hecate2/neo-fairy-test/
* before using the following methods!
*/
async open_default_fairy_wallet(path, password) {
let open_wallet_result;
if (this.verbose_return) {
[open_wallet_result, , ] = await this.meta_rpc_method('opendefaultfairywallet', [path, password]);
} else {
open_wallet_result = await this.meta_rpc_method('opendefaultfairywallet', [path, password]);
}
if (!open_wallet_result) {
throw new Error(`Failed to open default wallet ${path} with given password.`);
}
return open_wallet_result;
}
async reset_default_fairy_wallet() {
let close_wallet_result;
if (this.verbose_return) {
[close_wallet_result, , ] = await this.meta_rpc_method('resetdefaultfairywallet', []);
} else {
close_wallet_result = await this.meta_rpc_method('resetdefaultfairywallet', []);
}
if (!close_wallet_result) {
throw new Error('Failed to reset default wallet.');
}
return close_wallet_result;
}
async set_session_fairy_wallet_with_NEP2(nep2, password, fairy_session = null) {
const open_wallet_result = await this.meta_rpc_method('setsessionfairywalletwithnep2', [nep2, password, fairy_session || this.fairy_session]);
if (!open_wallet_result) {
throw new Error(`Failed to open NEP2 wallet ${nep2} with given password.`);
}
return open_wallet_result;
}
async set_session_fairy_wallet_with_WIF(wif, password, fairy_session = null) {
const open_wallet_result = await this.meta_rpc_method('setsessionfairywalletwithwif', [wif, password, fairy_session || this.fairy_session]);
if (!open_wallet_result) {
throw new Error(`Failed to open WIF wallet ${wif} with given password.`);
}
return open_wallet_result;
}
async get_time_milliseconds() {
return await this.meta_rpc_method('gettime', [])['time'];
}
async new_snapshots_from_current_system(fairy_sessions = null) {
fairy_sessions = fairy_sessions || this.fairy_session;
if (fairy_sessions === null) {
throw new Error('No RpcServer session specified');
}
if (Array.isArray(fairy_sessions)) {
return await this.meta_rpc_method('newsnapshotsfromcurrentsystem', fairy_sessions);
} else {
return await this.meta_rpc_method('newsnapshotsfromcurrentsystem', [fairy_sessions]);
}
}
async delete_snapshots(fairy_sessions) {
return await this.meta_rpc_method('deletesnapshots', Array.isArray(fairy_sessions) ? fairy_sessions : [fairy_sessions]);
}
async list_snapshots() {
return await this.meta_rpc_method('listsnapshots', []);
}
async rename_snapshot(old_name, new_name) {
return await this.meta_rpc_method('renamesnapshot', [old_name, new_name]);
}
async copy_snapshot(old_name, new_name) {
return await this.meta_rpc_method('copysnapshot', [old_name, new_name]);
}
async set_snapshot_timestamp(timestamp_ms = null, fairy_session = null) {
fairy_session = fairy_session || this.fairy_session;
return await this.meta_rpc_method('setsnapshottimestamp', [fairy_session, timestamp_ms]);
}
async get_snapshot_timestamp(fairy_sessions = null) {
fairy_sessions = fairy_sessions || this.fairy_session;
if (fairy_sessions === null) {
throw new Error('No RpcServer session specified');
}
return await this.meta_rpc_method('getsnapshottimestamp', Array.isArray(fairy_sessions) ? fairy_sessions : [fairy_sessions]);
}
async set_snapshot_random(designated_random = null, fairy_session = null) {
fairy_session = fairy_session || this.fairy_session;
const result = await this.meta_rpc_method('setsnapshotrandom', [fairy_session, designated_random]);
for (let key in result) {
result[key] = result[key] === null ? null : parseInt(result[key]);
}
return result;
}
async get_snapshot_random(fairy_sessions = null) {
fairy_sessions = fairy_sessions || this.fairy_session;
let result;
if (typeof fairy_sessions === 'string') {
result = await this.meta_rpc_method('getsnapshotrandom', [fairy_sessions]);
} else {
result = await this.meta_rpc_method('getsnapshotrandom', fairy_sessions);
}
for (let key in result) {
result[key] = result[key] === null ? null : parseInt(result[key]);
}
return result;
}
async virtual_deploy(nef, manifest, signers = null, fairy_session = null) {
fairy_session = fairy_session || this.fairy_session;
const manifest_dict = JSON.parse(manifest);
if (manifest_dict["permissions"] === [{ 'contract': '0xacce6fd80d44e1796aa0c2c625e9e4e0ce39efc0', 'methods': ['deserialize', 'serialize'] }, { 'contract': '0xfffdc93764dbaddd97c48f252a53ea4643faa3fd', 'methods': ['destroy', 'getContract', 'update'] }]) {
console.warn('!!!SERIOUS WARNING: Did you write [ContractPermission("*", "*")] in your contract?!!!');
}
try {
const signers_list = Array.isArray(signers) ? signers.map(signer => signer.to_dict()) : to_list(signers || this.signers).map(signer => signer.to_dict());
const result = await this.meta_rpc_method("virtualdeploy", [fairy_session, FairyClient.all_to_base64(nef), manifest, signers_list])[fairy_session];
return new Hash160Str(result);
} catch (error) {
console.error(`If you have weird exceptions from this method, check if you have written any \`null\` to contract storage in \`_deploy\` method. Especially, consider marking your \`UInt160\` properties of class as \`static readonly UInt160\` in your contract.\nError: ${error}`);
throw error;
}
}
async get_contract(scripthash = null, fairy_session = null) {
scripthash = scripthash || this.contract_scripthash;
if (!scripthash) { throw new Error("No contract scripthash specified!"); }
fairy_session = fairy_session || this.fairy_session;
return await this.meta_rpc_method("getcontract", [fairy_session, scripthash]);
}
async await_confirmed_transaction(tx_hash, verbose = true, wait_block_count = 2) {
const result = await this.meta_rpc_method('awaitconfirmedtransaction', [tx_hash, verbose, wait_block_count]);
if (result['state'] === 'FAULT') {
throw new Error(`Transaction ${tx_hash} failed to execute with reason: ${result['vmstate']}`);
}
return result;
}
//static get_nef_and_manifest_from_path(nef_path_and_filename) {
// const [dir, nef_filename] = path.split(nef_path_and_filename);
// if (!nef_filename.endsWith('.nef')) {
// throw new Error('Invalid NEF file format. Please provide a .nef file.');
// }
// const nef = fs.readFileSync(nef_path_and_filename);
// const manifest = fs.readFileSync(path.join(dir, `${nef_filename.slice(0, -4)}.manifest.json`), 'utf8');
// return [nef, manifest];
//}
//async virtual_deploy_from_path(nef_path_and_filename, fairy_session = null, auto_dumpnef = true, dumpnef_backup = true, auto_set_debug_info = true, auto_set_client_contract_scripthash = true) {
// fairy_session = fairy_session || this.fairy_session;
// const [dir, nef_filename] = path.split(nef_path_and_filename);
// if (!nef_filename.endsWith('.nef')) {
// throw new Error('Invalid NEF file format. Please provide a .nef file.');
// }
// const [nef, manifest] = this.get_nef_and_manifest_from_path(nef_path_and_filename);
// const contract_hash = await this.virtual_deploy(nef, manifest, null, fairy_session);
// const nefdbgnfo_path_and_filename = path.join(dir, `${nef_filename.slice(0, -4)}.nefdbgnfo`);
// const dumpnef_path_and_filename = path.join(dir, `${nef_filename.slice(0, -4)}.nef.txt`);
// if (fs.existsSync(nefdbgnfo_path_and_filename)) {
// if (auto_dumpnef && (!fs.existsSync(dumpnef_path_and_filename) || fs.statSync(dumpnef_path_and_filename).mtime < fs.statSync(nef_path_and_filename).mtime)) {
// if (dumpnef_backup && fs.existsSync(dumpnef_path_and_filename) && !fs.existsSync(path.join(dir, `${nef_filename.slice(0, -4)}.bk.txt`))) {
// // only backup the .nef.txt file when no backup exists
// fs.renameSync(dumpnef_path_and_filename, path.join(dir, `${nef_filename.slice(0, -4)}.bk.txt`));
// }
// console.log(`dumpnef ${nef_filename}`, os.popen(`dumpnef ${nef_path_and_filename} > ${dumpnef_path_and_filename}`).read());
// }
// if (auto_set_debug_info && fs.existsSync(dumpnef_path_and_filename) && fs.statSync(dumpnef_path_and_filename).mtime >= fs.statSync(nef_path_and_filename).mtime && fairy_session) {
// const nefdbgnfo = fs.readFileSync(nefdbgnfo_path_and_filename);
// const dumpnef = fs.readFileSync(dumpnef_path_and_filename, 'utf8');
// await this.set_debug_info(nefdbgnfo, dumpnef, contract_hash, fairy_session);
// }
// } else {
// console.warn(`WARNING! No .nefdbgnfo found. It is highly recommended to generate .nefdbgnfo for debugging. If you are writing contracts in C#, consider building your project with command \`nccs your.csproj --debug\`.`);
// }
// if (auto_set_client_contract_scripthash) {
// this.contract_scripthash = contract_hash;
// }
// return contract_hash;
//}
static all_to_base64(key) {
if (typeof key === 'string') {
key = new TextEncoder().encode(key);
}
if (typeof key === 'number') {
key = Interpreter.int_to_bytes(key);
}
if (key.constructor === ArrayBuffer) {
key = window.btoa( // base64
new Uint8Array(key)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
} else {
throw new Error(`Unexpected input type ${typeof key} ${key}`);
}
return key;
}
async get_storage_with_session(key, fairy_session = null, contract_scripthash = this.contract_scripthash) {
fairy_session = fairy_session || this.fairy_session;
const result = await this.meta_rpc_method("getstoragewithsession", [fairy_session, contract_scripthash.value, this.all_to_base64(key)]);
return result;
}
async find_storage_with_session(key, fairy_session = null, contract_scripthash = this.contract_scripthash) {
fairy_session = fairy_session || this.fairy_session;
const result = await this.meta_rpc_method("findstoragewithsession", [fairy_session, contract_scripthash.value, this.all_to_base64(key)]);
return result;
}
async put_storage_with_session(key, value, fairy_session = null, contract_scripthash = this.contract_scripthash) {
fairy_session = fairy_session || this.fairy_session;
value = value === 0 ? '0' : value;
const result = await this.meta_rpc_method("putstoragewithsession", [fairy_session, contract_scripthash.value, this.all_to_base64(key), this.all_to_base64(value)]);
return result;
}
async set_neo_balance(balance, fairy_session = null, account = null) {
balance = parseInt(balance);
fairy_session = fairy_session || this.fairy_session;
account = account || this.wallet_scripthash;
if (!account) {
throw new Error('No account specified');
}
return await this.meta_rpc_method("setneobalance", [fairy_session, account.value, balance]);
}
async set_gas_balance(balance, fairy_session = null, account = null) {
balance = parseInt(balance);
fairy_session = fairy_session || this.fairy_session;
account = account || this.wallet_scripthash;
return await this.meta_rpc_method("setgasbalance", [fairy_session, account.value, balance]);
}
async set_nep17_balance(contract, balance, fairy_session = null, account = null, byte_prefix = 1) {
if (byte_prefix >= 256 || byte_prefix < 0) {
throw new Error(`Only 0<=byte_prefix<=255 accepted. Got ${byte_prefix}`);
}
fairy_session = fairy_session || this.fairy_session;
account = account || this.wallet_scripthash;
return await this.meta_rpc_method("setnep17balance", [fairy_session, contract.value, account.value, balance, byte_prefix]);
}
/* Fairy debugger features! */
// debug info and file names
async set_debug_info(nefdbgnfo, dumpnef_content, contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
const result = await this.meta_rpc_method("setdebuginfo", [contract_scripthash.value, this.all_to_base64(nefdbgnfo), dumpnef_content]);
return Object.fromEntries(Object.entries(result).map(([k, v]) => [new Hash160Str(k), v]));
}
async list_debug_info() {
const result = await this.meta_rpc_method("listdebuginfo", []);
return result.map(s => new Hash160Str(s));
}
async list_filenames_of_contract(contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
const result = await this.meta_rpc_method("listfilenamesofcontract", [contract_scripthash.value]);
return result.map(s => new Hash160Str(s));
}
async delete_debug_info(contract_scripthashes) {
if (contract_scripthashes instanceof Hash160Str) {
const result = await this.meta_rpc_method("deletedebuginfo", [contract_scripthashes.value]);
return { [new Hash160Str(Object.keys(result)[0])]: Object.values(result)[0] };
} else {
const result = await this.meta_rpc_method("deletedebuginfo", contract_scripthashes.map(h => h.value));
return Object.fromEntries(Object.entries(result).map(([k, v]) => [new Hash160Str(k), v]));
}
}
// breakpoints
async set_assembly_breakpoints(instruction_pointers, contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
if (typeof instruction_pointers === 'number') {
return await this.meta_rpc_method("setassemblybreakpoints", [contract_scripthash.value, instruction_pointers]);
} else {
return await this.meta_rpc_method("setassemblybreakpoints", [contract_scripthash.value, ...instruction_pointers]);
}
}
async list_assembly_breakpoints(contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
const result = await this.meta_rpc_method("listassemblybreakpoints", [contract_scripthash.value]);
return result;
}
async delete_assembly_breakpoints(instruction_pointers = null, contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
instruction_pointers = instruction_pointers || [];
if (typeof instruction_pointers === 'number') {
return await this.meta_rpc_method("deleteassemblybreakpoints", [contract_scripthash.value, instruction_pointers]);
} else {
return await this.meta_rpc_method("deleteassemblybreakpoints", [contract_scripthash.value, ...instruction_pointers]);
}
}
async set_source_code_breakpoint(filename, line_num, contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
return await this.meta_rpc_method("setsourcecodebreakpoints", [contract_scripthash.value, filename, line_num]);
}
async set_source_code_breakpoints(filename_and_line_num, contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
return await this.meta_rpc_method("setsourcecodebreakpoints", [contract_scripthash.value, ...filename_and_line_num]);
}
async list_source_code_breakpoints(contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
const result = await this.meta_rpc_method("listsourcecodebreakpoints", [contract_scripthash.value]);
return result;
}
async delete_source_code_breakpoint(filename, line_num, contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
return await this.meta_rpc_method("deletesourcecodebreakpoints", [contract_scripthash.value, filename, line_num]);
}
async delete_source_code_breakpoints(filename_and_line_num = null, contract_scripthash = null) {
contract_scripthash = contract_scripthash || this.contract_scripthash;
filename_and_line_num = filename_and_line_num || [];
return await this.meta_rpc_method("deletesourcecodebreakpoints", [contract_scripthash.value, ...filename_and_line_num]);
}
async delete_debug_snapshots(fairy_sessions) {
if (typeof fairy_sessions === 'string') {
return await this.meta_rpc_method("deletedebugsnapshots", [fairy_sessions]);
} else {
return await this.meta_rpc_method("deletedebugsnapshots", fairy_sessions);
}
}
async list_debug_snapshots() {
return await this.meta_rpc_method("listdebugsnapshots", []);
}
async get_method_by_instruction_pointer(instruction_pointer, scripthash = null) {
scripthash = scripthash || this.contract_scripthash;
return await this.meta_rpc_method("getmethodbyinstructionpointer", [scripthash.value, instruction_pointer]);
}
async debug_any_function_with_session(scripthash, operation, params = null, signers = null, relay = null,
do_not_raise_on_result = false, with_print = true, fairy_session = null) {
scripthash = scripthash || this.contract_scripthash;
fairy_session = fairy_session || this.fairy_session;
if (this.with_print && with_print) {
if (fairy_session) {
console.log(`${fairy_session}::debugfunction ${operation}`);
} else {
console.log(`debugfunction ${operation}`);
}
}
params = params || [];
signers = to_list(signers || this.signers);