forked from eosspark/geos
/
system_api.go
785 lines (683 loc) · 26.1 KB
/
system_api.go
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
package console
import (
"encoding/json"
"fmt"
"github.com/robertkrimen/otto"
"github.com/zhangsifeng92/geos/chain/types"
"github.com/zhangsifeng92/geos/chain/types/generated_containers"
"github.com/zhangsifeng92/geos/common"
"github.com/zhangsifeng92/geos/crypto/ecc"
"github.com/zhangsifeng92/geos/crypto/rlp"
"github.com/zhangsifeng92/geos/exception"
. "github.com/zhangsifeng92/geos/exception/try"
"github.com/zhangsifeng92/geos/plugins/chain_plugin"
"sort"
"strconv"
"strings"
)
type system struct {
c *Console
}
func newSystem(c *Console) *system {
s := &system{
c: c,
}
return s
}
//NewAccount creates a new account on the blockchain with initial resources
func (s *system) NewAccount(call otto.FunctionCall) (response otto.Value) {
var params NewAccountParams
readParams(¶ms, call)
if len(params.ActiveKey) == 0 {
params.ActiveKey = params.OwnerKey
}
ownerKey, err := ecc.NewPublicKey(params.OwnerKey)
if err != nil {
throwJSException(fmt.Sprintf("Invalid owner public key: %s", params.OwnerKey))
}
activeKey, err := ecc.NewPublicKey(params.ActiveKey)
if err != nil {
throwJSException(fmt.Sprintf("Invalid active public key: %s", params.ActiveKey))
}
create := createNewAccount(params.Creator, params.Name, ownerKey, activeKey, params.TxPermission)
EosAssert(len(params.BuyRamEos) > 0 || params.BuyRamBytesInKbytes > 0 || params.BuyRamBytes > 0, &exception.ExplainedException{},
"ERROR: One of buy_ram, buy_ram_kbytes or buy_ram_bytes should have non_zero value")
EosAssert(params.BuyRamBytesInKbytes == 0 || params.BuyRamBytes == 0, &exception.ExplainedException{},
"ERROR: buy_ram_kbytes and buy_ram_bytes cannot be set at the same time")
buyram := &types.Action{}
if len(params.BuyRamEos) > 0 {
buyram = createBuyRam(params.Creator, params.Name, toAssetFromString(params.BuyRamEos), params.TxPermission)
} else {
var numBytes uint32
if params.BuyRamBytesInKbytes > 0 {
numBytes = params.BuyRamBytesInKbytes * 1024
} else {
numBytes = params.BuyRamBytes
}
buyram = createBuyRamBytes(params.Creator, params.Name, numBytes, params.TxPermission)
}
net := toAssetFromString(params.StakeNet)
cpu := toAssetFromString(params.StakeCpu)
if net.Amount != 0 || cpu.Amount != 0 {
delegate := createDelegate(params.Creator, params.Name, net, cpu, params.Transfer, params.TxPermission)
sendActions([]*types.Action{create, buyram, delegate}, 1000, types.CompressionNone, ¶ms)
} else {
sendActions([]*types.Action{create, buyram}, 1000, types.CompressionNone, ¶ms)
}
return
}
//RegProducer registers a new producer
func (s *system) RegProducer(call otto.FunctionCall) (response otto.Value) {
var params RegisterProducer
readParams(¶ms, call)
producerKey, err := ecc.NewPublicKey(params.Key)
if err != nil {
Throw(err) // EOS_RETHROW_EXCEPTIONS(public_key_type_exception, "Invalid producer public key: ${public_key}", ("public_key", producer_key_str))
}
regprodVar := regProducerVariant(common.N(params.Producer), producerKey, params.Url, params.Loc)
action := createAction([]common.PermissionLevel{{common.N(params.Producer), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("regproducer"), regprodVar)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Unregprod unregisters an existing producer
func (s *system) Unregprod(call otto.FunctionCall) (response otto.Value) {
var params UnregrodParams
readParams(¶ms, call)
actPayload := common.Variants{"producer": params.Producer}
action := createAction([]common.PermissionLevel{{common.N(params.Producer), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("unregprod"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//VoteproducerProxy votes your stake through a proxy
func (s *system) VoteproducerProxy(call otto.FunctionCall) (response otto.Value) {
var params Proxy
readParams(¶ms, call)
actPayload := common.Variants{
"voter": params.Voter,
"proxy": params.Proxy,
"producers": []common.AccountName{},
}
action := createAction([]common.PermissionLevel{{common.N(params.Voter), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("voteproduer"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//VoteproducerProds votes for one or more producers
func (s *system) VoteproducerProds(call otto.FunctionCall) (response otto.Value) {
var params Prods
readParams(¶ms, call)
sort.Sort(params.ProducerNames)
fmt.Println("producerNames after:", params.ProducerNames)
actPayload := common.Variants{
"voter": params.Voter,
"proxy": "",
"producers": params.ProducerNames,
}
action := createAction([]common.PermissionLevel{{common.N(params.Voter), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("voteproducer"), &actPayload)
sendActions([]*types.Action{action}, 10000, types.CompressionNone, ¶ms)
return
}
//Approveroducer adds one producer to list of voted producers
func (s *system) Approveroducer(call otto.FunctionCall) (response otto.Value) {
var params Approve
readParams(¶ms, call)
var res chain_plugin.GetTableRowsResult
err := DoHttpCall(&res, common.GetTableFunc, common.Variants{
"json": true,
"code": common.DefaultConfig.SystemAccountName.String(),
"scope": common.DefaultConfig.SystemAccountName.String(),
"table": "voters",
"table_key": "owner",
"lower_bound": uint64(params.Voter),
"limit": 1,
})
if err != nil {
throwJSException(fmt.Sprintf("http err :%s", err))
}
if len(res.Rows) == 0 {
throwJSException(fmt.Sprintf("Voter info not found for account %s", params.Voter))
} else {
rows0, ok := res.Rows[0]["owner"]
if !ok {
throwJSException(fmt.Sprintf("Voter info not found for account %s", params.Voter))
} else {
name := rows0.(string)
if strings.Compare(name, params.Voter.String()) != 0 {
throwJSException(fmt.Sprintf("Voter info not found for account %s", params.Voter))
}
}
}
EosAssert(1 == len(res.Rows), &exception.MultipleVoterInfo{}, "More than one voter_info for account")
prodsInterface, ok := res.Rows[0]["producers"] //TODO
if !ok {
throwJSException(fmt.Sprintf("Voter info not found producers"))
}
var prods Names
prodsVars := prodsInterface.(Names)
for _, name := range prodsVars {
if uint64(name) != uint64(params.ProducerName) {
prods = append(prods, name)
} else {
throwJSException(fmt.Sprintf("Producer %s is already on the list.", params.ProducerName))
}
}
prods = append(prods, params.ProducerName)
sort.Sort(prods)
clog.Debug("prods : %s", prods)
actPayload := common.Variants{
"voter": params.Voter.String(),
"proxy": "",
"producers": prods,
}
action := createAction([]common.PermissionLevel{{params.Voter, common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("voteproducer"), &actPayload)
sendActions([]*types.Action{action}, 10000, types.CompressionNone, ¶ms)
return
}
//UnapproveProducer removes one producer from list of voted producers
func (s *system) UnapproveProducer(call otto.FunctionCall) (response otto.Value) {
var params UnapproveProducer
readParams(¶ms, call)
var res chain_plugin.GetTableRowsResult
err := DoHttpCall(&res, common.GetTableFunc, common.Variants{
"json": true,
"code": common.DefaultConfig.SystemAccountName.String(),
"scope": common.DefaultConfig.SystemAccountName.String(),
"table": "voters",
"table_key": "owner",
"lower_bound": uint64(params.Voter),
"limit": 1,
})
if err != nil {
throwJSException(fmt.Sprintf("http err :%s", err))
}
if len(res.Rows) == 0 {
throwJSException(fmt.Sprintf("Voter info not found for account %s", params.Voter))
} else {
rows0, ok := res.Rows[0]["owner"]
if !ok {
throwJSException(fmt.Sprintf("Voter info not found for account %s", params.Voter))
} else {
name := rows0.(string)
if strings.Compare(name, params.Voter.String()) != 0 {
throwJSException(fmt.Sprintf("Voter info not found for account %s", params.Voter))
}
}
}
EosAssert(1 == len(res.Rows), &exception.MultipleVoterInfo{}, "More than one voter_info for account")
prodsInterface, ok := res.Rows[0]["producers"] //TODO
if !ok {
throwJSException(fmt.Sprintf("Voter info not found producers"))
}
var prods Names
prodsVars := prodsInterface.(Names)
for _, name := range prodsVars {
if uint64(name) != uint64(params.ProducerName) {
prods = append(prods, name)
}
}
if len(prodsVars) == len(prods) {
throwJSException(fmt.Sprintf("Cannot remove: producer %s is not on the list.", params.ProducerName))
}
actPayload := common.Variants{
"voter": params.Voter.String(),
"proxy": "",
"producers": prods,
}
action := createAction([]common.PermissionLevel{{params.Voter, common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("voteproducer"), &actPayload)
sendActions([]*types.Action{action}, 10000, types.CompressionNone, ¶ms)
return
}
//Listproducers lists producers
func (s *system) Listproducers(call otto.FunctionCall) (response otto.Value) {
var params ListproducersParams
readParams(¶ms, call)
if params.Limit == 0 {
params.Limit = 50 //default =50
}
var resp chain_plugin.GetProducersResult
err := DoHttpCall(&resp, common.GetProducersFunc, &common.Variants{
"json": true,
"lower_bound": params.Lower,
"limit": params.Limit,
})
if err != nil {
throwJSException(fmt.Sprintf("http error : %s", err))
}
if params.PrintJson {
return getJsResult(call, fmt.Sprintln(resp))
}
if len(resp.Rows) == 0 {
return getJsResult(call, fmt.Sprintln("No producers found"))
}
weight := resp.TotalProducerVoteWeight
if weight == 0 {
weight = 1
}
type ShowStruct struct {
Owner string `json:"owner"`
ProducerKey string `json:"producer_key"`
Url string `json:"url"`
TotalVotes float64 `json:"total_votes"`
}
//todo better display information
fmt.Printf("%-13s %-57s %-59s %s\n", "Producer", "Producer key", "Url", "Scaled votes")
for _, row := range resp.Rows {
var show ShowStruct
bytes, _ := json.Marshal(row)
err := json.Unmarshal(bytes, &show)
if err != nil {
fmt.Printf("resp.rows unmarhal is error:%s", err)
}
fmt.Printf("%-13.13s %-57.57s %-59.59s %1.4f\n",
show.Owner,
show.ProducerKey,
show.Url,
show.TotalVotes/weight)
}
if len(resp.More) > 0 {
fmt.Printf("-L %s for more\n", resp.More)
}
return
}
//Delegatebw delegates bandwidth
func (s *system) Delegatebw(call otto.FunctionCall) (response otto.Value) {
var params DelegatebwParams
readParams(¶ms, call)
EosAssert(len(params.BuyRamAmount) == 0 || params.BuyRamBytes == 0, &exception.ExplainedException{},
"ERROR: buyram and buy_ram_bytes cannot be set at the same time")
actPayload := common.Variants{
"from": params.From,
"receiver": params.Receiver,
"stake_net_quantity": toAssetFromString(params.StakeNetAmount),
"stake_cpu_quantity": toAssetFromString(params.StakeCpuAmount),
"transfer": params.Transfer,
}
action := createAction([]common.PermissionLevel{{common.N(params.From), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("delegatebw"), &actPayload)
acts := []*types.Action{action}
if len(params.BuyRamAmount) > 0 {
acts = append(acts, createBuyRam(common.N(params.From), common.N(params.Receiver), toAssetFromString(params.BuyRamAmount), params.TxPermission))
} else if params.BuyRamBytes > 0 {
acts = append(acts, createBuyRamBytes(common.N(params.From), common.N(params.Receiver), params.BuyRamBytes, params.TxPermission))
}
sendActions(acts, 1000, types.CompressionNone, ¶ms)
return
}
//Undelegatebw undelegates bandwidth
func (s *system) Undelegatebw(call otto.FunctionCall) (response otto.Value) {
var params UndelegatebwParams
readParams(¶ms, call)
actPayload := common.Variants{
"from": params.From,
"receiver": params.Receive,
"unstake_net_quantity": toAssetFromString(params.UnstakeNetAmount),
"unstake_cpu_quantity": toAssetFromString(params.UnstakeCpuAmount),
}
action := createAction([]common.PermissionLevel{{common.N(params.From), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("undelegatebw"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Listbw lists delegated bandwidth
func (s *system) Listbw(call otto.FunctionCall) (response otto.Value) {
var params ListbwParams
readParams(¶ms, call)
//get entire table in scope of user account
var resp chain_plugin.GetTableRowsResult
err := DoHttpCall(&resp, common.GetTableFunc, common.Variants{
"json": true,
"code": common.DefaultConfig.SystemAccountName.String(),
"scope": params.Account.String(),
"table": "delband",
})
if err != nil {
throwJSException(fmt.Sprintf("http is error :%s", err))
}
if !params.PrintJson {
if len(resp.Rows) != 0 { //Todo better display
//std::cout << std::setw(13) << std::left << "Receiver" << std::setw(21) << std::left << "Net bandwidth"
// << std::setw(21) << std::left << "CPU bandwidth" << std::endl;
// for ( auto& r : res.rows ){
// std::cout << std::setw(13) << std::left << r["to"].as_string()
// << std::setw(21) << std::left << r["net_weight"].as_string()
// << std::setw(21) << std::left << r["cpu_weight"].as_string()
// << std::endl;
// }
} else {
return getJsResult(call, fmt.Sprintln("Delegated bandwitdth not found"))
}
} else {
return getJsResult(call, fmt.Sprintln(resp))
}
return
}
//Bidname: Name bidding
func (s *system) Bidname(call otto.FunctionCall) (response otto.Value) {
var params BidnameParams
readParams(¶ms, call)
actPayload := common.Variants{
"bidder": params.Bidder,
"newname": params.NewName,
"bid": toAssetFromString(params.BidAmount),
}
action := createAction([]common.PermissionLevel{{common.N(params.Bidder), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("bidname"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Bidnameinfo gets bidname info
func (s *system) Bidnameinfo(call otto.FunctionCall) (response otto.Value) {
var params BidNameinfoParams
readParams(¶ms, call)
var resp chain_plugin.GetTableRowsResult
err := DoHttpCall(&resp, common.GetTableFunc, common.Variants{
"json": true,
"code": "eosio",
"scope": "eosio",
"table": "namebids",
"lower_bound": common.N(params.Newname),
"limit": 1,
})
if err != nil {
throwJSException(fmt.Sprintf("http is error: %s\n", err))
}
if params.PrintJson {
return getJsResult(call, fmt.Sprintln(resp))
}
if len(resp.Rows) == 0 {
return getJsResult(call, fmt.Sprintln("No bidname record found"))
}
for _, row := range resp.Rows { //todo better display
fmt.Println(row)
//fc::time_point time(fc::microseconds(row["last_bid_time"].as_uint64()));
// int64_t bid = row["high_bid"].as_int64();
//std::cout << std::left << std::setw(18) << "bidname:" << std::right << std::setw(24) << row["newname"].as_string() << "\n"
// << std::left << std::setw(18) << "highest bidder:" << std::right << std::setw(24) << row["high_bidder"].as_string() << "\n"
// << std::left << std::setw(18) << "highest bid:" << std::right << std::setw(24) << (bid > 0 ? bid : -bid) << "\n"
// << std::left << std::setw(18) << "last bid time:" << std::right << std::setw(24) << ((std::string)time).c_str() << std::endl;
// if (bid < 0) std::cout << "This auction has already closed" << std::endl;
}
return
}
//Buyram buy RAM
func (s *system) Buyram(call otto.FunctionCall) (response otto.Value) {
var params BuyramParams
readParams(¶ms, call)
EosAssert(!params.Kbytes || !params.BytesFlag, &exception.ExplainedException{}, "ERROR: kbytes and bytes cannot be set at the same time")
action := &types.Action{}
if params.Kbytes || params.BytesFlag {
var unit uint64
if params.Kbytes {
unit = 1024
} else {
unit = 1
}
amount, err := strconv.ParseUint(params.Amount, 10, 64)
if err != nil {
throwJSException(fmt.Sprintf("parseUint is error: %s\n", err))
}
action = createBuyRamBytes(common.N(params.Payer), common.N(params.Receiver), uint32(amount*unit), params.TxPermission)
} else {
action = createBuyRam(common.N(params.Payer), common.N(params.Receiver), toAssetFromString(params.Amount), params.TxPermission)
}
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Sellram sell RAM
func (s *system) Sellram(call otto.FunctionCall) (response otto.Value) {
var params SellRamParams
readParams(¶ms, call)
actPayload := common.Variants{
"account": params.Receiver,
"bytes": params.Amount,
}
action := createAction([]common.PermissionLevel{{common.N(params.Receiver), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("sellram"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Claimrewards claims producer rewards
func (s *system) Claimrewards(call otto.FunctionCall) (response otto.Value) {
var params ClaimrewardsParams
readParams(¶ms, call)
actPayload := common.Variants{
"owner": params.Owner,
}
action := createAction([]common.PermissionLevel{{common.N(params.Owner), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("claimrewards"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Regproxy Registers an account as a proxy (for voting)
func (s *system) Regproxy(call otto.FunctionCall) (response otto.Value) {
var params RegproxyParams
readParams(¶ms, call)
actPayload := common.Variants{
"proxy": params.Proxy,
"isproxy": true,
}
action := createAction([]common.PermissionLevel{{common.N(params.Proxy), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("regproxy"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Unregproxy unregisters an account as a proxy (for voting)
func (s *system) Unregproxy(call otto.FunctionCall) (response otto.Value) {
var params RegproxyParams
readParams(¶ms, call)
actPayload := common.Variants{
"proxy": params.Proxy,
"isproxy": false,
}
action := createAction([]common.PermissionLevel{{common.N(params.Proxy), common.DefaultConfig.ActiveName}},
common.DefaultConfig.SystemAccountName, common.N("regproxy"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
//Canceldelay cancels a delayed transaction
func (s *system) Canceldelay(call otto.FunctionCall) (response otto.Value) {
var params CanceldelayParams
readParams(¶ms, call)
cancelingAuth := common.PermissionLevel{common.N(params.CancelingAccount), common.N(params.CanclingPermission)}
actPayload := common.Variants{
"canceling_auth": cancelingAuth,
"trx_id": params.TrxID,
}
action := createAction([]common.PermissionLevel{cancelingAuth}, common.DefaultConfig.SystemAccountName, common.N("canceldelay"), &actPayload)
sendActions([]*types.Action{action}, 1000, types.CompressionNone, ¶ms)
return
}
func readParams(params interface{}, call otto.FunctionCall) {
JSON, _ := call.Otto.Object("JSON")
reqVal, err := JSON.Call("stringify", call.Argument(0))
if err != nil {
throwJSException(err.Error())
}
rawReq := reqVal.String()
dec := json.NewDecoder(strings.NewReader(rawReq))
dec.Decode(¶ms)
}
func getJsResult(call otto.FunctionCall, in interface{}) otto.Value {
bytes, _ := json.Marshal(in)
resps, _ := call.Otto.Object("new Array()")
JSON, _ := call.Otto.Object("JSON")
resultVal, _ := JSON.Call("parse", string(bytes))
resp, _ := call.Otto.Object(`({"eosgo":"1.0"})`)
resp.Set("result", resultVal)
resps.Call("push", resp)
return resps.Value()
}
func createAction(authorization []common.PermissionLevel, code common.AccountName, act common.ActionName, args *common.Variants) *types.Action {
return &types.Action{
Account: code,
Name: act,
Data: variantToBin(code, act, args),
Authorization: authorization,
}
}
func createBuyRam(creator common.Name, newaccount common.Name, quantity *common.Asset, txPermission []string) *types.Action {
actPayload := common.Variants{
"payer": creator.String(),
"receiver": newaccount.String(),
"quant": quantity.String(),
}
var auth []common.PermissionLevel
if len(txPermission) == 0 {
auth = []common.PermissionLevel{{Actor: creator, Permission: common.DefaultConfig.ActiveName}}
} else {
auth = getAccountPermissions(txPermission)
}
return createAction(auth, common.DefaultConfig.SystemAccountName, common.N("buyram"), &actPayload)
}
func createBuyRamBytes(creator common.Name, newaccount common.Name, numbytes uint32, txPermission []string) *types.Action {
actPayload := common.Variants{
"payer": creator.String(),
"receiver": newaccount.String(),
"bytes": numbytes,
}
var auth []common.PermissionLevel
if len(txPermission) == 0 {
auth = []common.PermissionLevel{{Actor: creator, Permission: common.DefaultConfig.ActiveName}}
} else {
auth = getAccountPermissions(txPermission)
}
return createAction(auth, common.DefaultConfig.SystemAccountName, common.N("buyrambytes"), &actPayload)
}
func createDelegate(from common.Name, receiver common.Name, net *common.Asset, cpu *common.Asset, transfer bool, txPermission []string) *types.Action {
actPayLoad := common.Variants{
"from": from.String(),
"receiver": receiver.String(),
"stake_net_quantity": net.String(),
"stake_cpu_quantity": cpu.String(),
"transfer": transfer,
}
var auth []common.PermissionLevel
if len(txPermission) == 0 {
auth = []common.PermissionLevel{{Actor: from, Permission: common.DefaultConfig.ActiveName}}
} else {
auth = getAccountPermissions(txPermission)
}
return createAction(auth, common.DefaultConfig.SystemAccountName, common.N("delegatebw"), &actPayLoad)
}
func sendActions(actions []*types.Action, extraKcpu int32, compression types.CompressionType, c ConsoleInterface) interface{} {
result := pushActions(actions, extraKcpu, compression, c)
if c.getOptions().TxPrintJson {
fmt.Println(result)
} else {
printResult(result)
}
return nil
}
func pushActions(actions []*types.Action, extraKcpu int32, compression types.CompressionType, c ConsoleInterface) interface{} {
trx := types.NewSignedTransactionNil()
trx.Actions = actions
return pushTransaction(trx, extraKcpu, compression, c)
}
func pushTransaction(trx *types.SignedTransaction, extraKcpu int32, compression types.CompressionType, c ConsoleInterface) interface{} {
var info chain_plugin.GetInfoResult
err := DoHttpCall(&info, common.GetInfoFunc, nil)
if err != nil {
fmt.Println(err)
}
if len(trx.Signatures) == 0 { // #5445 can't change txn content if already signed
// calculate expiration date
var expiration common.Microseconds
if c.getOptions().Expiration == 0 {
expiration = common.Seconds(30)
} else {
expiration = common.Seconds(int64(c.getOptions().Expiration))
}
trx.Expiration = common.NewTimePointSecTp(info.HeadBlockTime.AddUs(expiration))
// Set tapos, default to last irreversible block if it's not specified by the user
refBlockID := info.LastIrreversibleBlockID
if len(c.getOptions().TxRefBlockNumOrId) > 0 {
//var refBlock GetBlockResult
var refBlock chain_plugin.GetBlockResult
err := DoHttpCall(&refBlock, common.GetBlockFunc, common.Variants{"block_num_or_id": c.getOptions().TxRefBlockNumOrId})
if err != nil {
fmt.Println(err)
EosThrow(&exception.InvalidRefBlockException{}, "Invalid reference block num or id: %s", c.getOptions().TxRefBlockNumOrId)
}
refBlockID = refBlock.ID
}
trx.SetReferenceBlock(&refBlockID)
if c.getOptions().TxForceUnique {
trx.ContextFreeActions = append(trx.ContextFreeActions, generateNonceAction())
}
trx.MaxCpuUsageMS = uint8(c.getOptions().TxMaxCpuUsage)
trx.MaxNetUsageWords = (common.Vuint32(c.getOptions().TxMaxNetUsage) + 7) / 8
trx.DelaySec = common.Vuint32(c.getOptions().DelaySec)
}
if !c.getOptions().TxSkipSign {
requiredKeys := determineRequiredKeys(trx)
signTransaction(trx, requiredKeys, &info.ChainID)
}
if !c.getOptions().TxDontBroadcast {
var result chain_plugin.PushTransactionResult
packedTrx := types.NewPackedTransactionBySignedTrx(trx, compression)
err = DoHttpCall(&result, common.PushTxnFunc, packedTrx)
if err != nil {
clog.Error(err.Error())
}
return result
} else {
if !c.getOptions().TxReturnPacked {
out, _ := json.Marshal(trx)
return out
} else {
out, _ := json.Marshal(types.NewPackedTransactionBySignedTrx(trx, compression))
return out
}
}
}
func determineRequiredKeys(trx *types.SignedTransaction) []string {
var publicKeys []string
err := DoHttpCall(&publicKeys, common.WalletPublicKeys, nil)
if err != nil {
clog.Error(err.Error())
}
publicKeySet := generated.NewPublicKeySet()
for _, key := range publicKeys {
pubKey, _ := ecc.NewPublicKey(key)
publicKeySet.Add(pubKey)
}
var keys chain_plugin.GetRequiredKeysResult
arg := &common.Variants{
"transaction": trx,
"available_keys": publicKeySet,
}
err = DoHttpCall(&keys, common.GetRequiredKeys, arg)
if err != nil {
clog.Error(err.Error())
}
re := make([]string, 0, keys.RequiredKeys.Size())
for _, key := range keys.RequiredKeys.Values() {
re = append(re, key.String())
}
return re
}
func signTransaction(trx *types.SignedTransaction, requiredKeys []string, chainID *common.ChainIdType) {
signedTrx := common.Variants{"signed_transaction": trx, "keys": requiredKeys, "id": chainID}
err := DoHttpCall(trx, common.WalletSignTrx, signedTrx)
if err != nil {
clog.Error(err.Error())
}
}
func generateNonceAction() *types.Action {
t := common.Now().TimeSinceEpoch()
data, _ := rlp.EncodeToBytes(t)
return &types.Action{
Account: common.DefaultConfig.NullAccountName,
Name: common.N("nonce"),
Authorization: []common.PermissionLevel{},
Data: data,
}
}
func generateNonceString() string {
return strconv.FormatInt(common.Now().TimeSinceEpoch().Count(), 10)
}