-
Notifications
You must be signed in to change notification settings - Fork 44
/
ont_sdk.go
874 lines (834 loc) · 21.3 KB
/
ont_sdk.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
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
/*
* Copyright (C) 2018 The ontology Authors
* This file is part of The ontology library.
*
* The ontology is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ontology is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The ontology. If not, see <http://www.gnu.org/licenses/>.
*/
//Ontolog sdk in golang. Using for operation with ontology
package ontology_go_sdk
import (
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/big"
"math/rand"
"time"
"github.com/ontio/go-bip32"
"github.com/ontio/ontology-go-sdk/bip44"
"github.com/ontio/ontology/smartcontract/event"
"github.com/tyler-smith/go-bip39"
"github.com/ontio/ontology-crypto/keypair"
"github.com/ontio/ontology-go-sdk/client"
sdkcom "github.com/ontio/ontology-go-sdk/common"
"github.com/ontio/ontology-go-sdk/utils"
"github.com/ontio/ontology/common"
"github.com/ontio/ontology/common/constants"
"github.com/ontio/ontology/core/payload"
"github.com/ontio/ontology/core/types"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
//OntologySdk is the main struct for user
type OntologySdk struct {
client.ClientMgr
Native *NativeContract
NeoVM *NeoVMContract
WasmVM *WasmVMContract
Credential *Credential
ChainId uint32
}
//NewOntologySdk return OntologySdk.
func NewOntologySdk() *OntologySdk {
ontSdk := &OntologySdk{}
native := newNativeContract(ontSdk)
ontSdk.Native = native
neoVM := newNeoVMContract(ontSdk)
ontSdk.NeoVM = neoVM
wasmVM := newWasmVMContract(ontSdk)
ontSdk.WasmVM = wasmVM
credential := newCredential(ontSdk)
ontSdk.Credential = credential
return ontSdk
}
type Layer2Sdk struct {
*OntologySdk
*client.Layer2ClientMgr
}
func NewLayer2Sdk() *Layer2Sdk {
sdk := NewOntologySdk()
sdk.ChainId = sdkcom.LAYER2_SYSTEM_ID
layer2Client := client.NewLayer2ClientMgr(&sdk.ClientMgr)
return &Layer2Sdk{
OntologySdk: sdk,
Layer2ClientMgr: layer2Client,
}
}
//CreateWallet return a new wallet
func (this *OntologySdk) CreateWallet(walletFile string) (*Wallet, error) {
if utils.IsFileExist(walletFile) {
return nil, fmt.Errorf("wallet:%s has already exist", walletFile)
}
return NewWallet(walletFile), nil
}
//OpenWallet return a wallet instance
func (this *OntologySdk) OpenWallet(walletFile string) (*Wallet, error) {
return OpenWallet(walletFile)
}
//OpenWallet return a wallet instance
func (this *OntologySdk) SetCredContractAddress(addr string) error {
address, err := common.AddressFromHexString(addr)
if err != nil {
return fmt.Errorf("SetCredContractAddress error: %s", err)
}
this.Credential.credRecordContractAddress = address
return nil
}
func ParseNativeTxPayload(raw []byte) (map[string]interface{}, error) {
tx, err := types.TransactionFromRawBytes(raw)
if err != nil {
return nil, err
}
invokeCode, ok := tx.Payload.(*payload.InvokeCode)
if !ok {
return nil, fmt.Errorf("error payload")
}
code := invokeCode.Code
return ParsePayload(code)
}
func ParseNativeTxPayloadV2(raw []byte) (map[string]interface{}, error) {
tx, err := types.TransactionFromRawBytes(raw)
if err != nil {
return nil, err
}
invokeCode, ok := tx.Payload.(*payload.InvokeCode)
if !ok {
return nil, fmt.Errorf("error payload")
}
code := invokeCode.Code
return ParsePayloadV2(code)
}
func ParsePayload(code []byte) (map[string]interface{}, error) {
l := len(code)
if l > 44 && string(code[l-22:]) == "Ontology.Native.Invoke" {
//46 = 22 "Ontology.Native.Invoke"
// +1 length
// +1 SYSCALL
// +1 version
// +20 address
// +1 length
//TODO if version>15, there will be bug
if l > 54 && string(code[l-46-8:l-46]) == "transfer" {
param := make([]sdkcom.StateInfo, 0)
source := common.NewZeroCopySource(code)
for {
zeroByte, eof := source.NextByte()
if eof {
return nil, io.ErrUnexpectedEOF
}
if zeroByte != 0 {
break
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
from, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
to, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
amount, err := getValue(source)
if err != nil {
return nil, err
}
state := sdkcom.StateInfo{
From: from.ToBase58(),
To: to.ToBase58(),
Value: amount,
}
param = append(param, state)
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
var isend bool
if isend, err = isEnd(source); err != nil {
return nil, err
}
if isend {
break
}
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
//method name
_, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return nil, io.ErrUnexpectedEOF
}
//contract address
contractAddress, err := readAddress(source)
if err != nil {
return nil, err
}
res := make(map[string]interface{})
res["functionName"] = "transfer"
res["contractAddress"] = contractAddress
res["param"] = param
if contractAddress == ONT_CONTRACT_ADDRESS {
res["asset"] = "ont"
} else if contractAddress == ONG_CONTRACT_ADDRESS {
res["asset"] = "ong"
}
return res, nil
} else if l > 58 && string(code[l-46-12:l-46]) == "transferFrom" {
source := common.NewZeroCopySource(code)
//ignore 00
_, eof := source.NextByte()
if eof {
return nil, io.ErrUnexpectedEOF
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
sender, err := readAddress(source)
if err != nil {
return nil, err
}
_, eof = source.NextBytes(6)
if eof {
return nil, io.EOF
}
from, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
to, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
amount, err := getValue(source)
if err != nil {
return nil, err
}
tf := sdkcom.TransferFromInfo{
Sender: sender.ToBase58(),
From: from.ToBase58(),
To: to.ToBase58(),
Value: amount,
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
//method name
_, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return nil, io.ErrUnexpectedEOF
}
//contract address
contractAddress, err := readAddress(source)
if err != nil {
return nil, err
}
res := make(map[string]interface{})
res["functionName"] = "transferFrom"
res["contractAddress"] = contractAddress
res["param"] = tf
if contractAddress == ONT_CONTRACT_ADDRESS {
res["asset"] = "ont"
} else if contractAddress == ONG_CONTRACT_ADDRESS {
res["asset"] = "ong"
}
return res, nil
}
}
return nil, fmt.Errorf("not native transfer and transferFrom transaction")
}
func ParsePayloadV2(code []byte) (map[string]interface{}, error) {
l := len(code)
if l > 44 && string(code[l-22:]) == "Ontology.Native.Invoke" {
//46 = 22 "Ontology.Native.Invoke"
// +1 length
// +1 SYSCALL
// +1 version
// +20 address
// +1 length
//TODO if version>15, there will be bug
//transferV2
if l > 54 && string(code[l-46-10:l-46]) == "transferV2" {
param := make([]sdkcom.StateInfoV2, 0)
source := common.NewZeroCopySource(code)
for {
zeroByte, eof := source.NextByte()
if eof {
return nil, io.ErrUnexpectedEOF
}
if zeroByte != 0 {
break
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
from, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
to, err := readAddress(source)
if err != nil {
return nil, err
}
err = ignoreOpCodeV2(source)
if err != nil {
return nil, err
}
amount, err := getValueV2(source)
if err != nil {
return nil, err
}
state := sdkcom.StateInfoV2{
From: from.ToBase58(),
To: to.ToBase58(),
Value: amount,
}
param = append(param, state)
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
var isend bool
if isend, err = isEnd(source); err != nil {
return nil, err
}
if isend {
break
}
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
//method name
_, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return nil, io.ErrUnexpectedEOF
}
//contract address
contractAddress, err := readAddress(source)
if err != nil {
return nil, err
}
res := make(map[string]interface{})
res["functionName"] = "transferV2"
res["contractAddress"] = contractAddress
res["param"] = param
if contractAddress == ONT_CONTRACT_ADDRESS {
res["asset"] = "ont"
} else if contractAddress == ONG_CONTRACT_ADDRESS {
res["asset"] = "ong"
}
return res, nil
} else if l > 58 && string(code[l-46-14:l-46]) == "transferFromV2" {
source := common.NewZeroCopySource(code)
//ignore 00
_, eof := source.NextByte()
if eof {
return nil, io.ErrUnexpectedEOF
}
err := ignoreOpCode(source)
if err != nil {
return nil, err
}
sender, err := readAddress(source)
if err != nil {
return nil, err
}
_, eof = source.NextBytes(6)
if eof {
return nil, io.EOF
}
from, err := readAddress(source)
if err != nil {
return nil, err
}
_, eof = source.NextBytes(3)
if eof {
return nil, io.EOF
}
to, err := readAddress(source)
if err != nil {
return nil, err
}
_, eof = source.NextBytes(3)
if eof {
return nil, io.EOF
}
amount, err := getValueV2(source)
if err != nil {
return nil, err
}
tf := sdkcom.TransferFromInfoV2{
Sender: sender.ToBase58(),
From: from.ToBase58(),
To: to.ToBase58(),
Value: amount,
}
err = ignoreOpCode(source)
if err != nil {
return nil, err
}
//method name
_, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return nil, io.ErrUnexpectedEOF
}
//contract address
contractAddress, err := readAddress(source)
if err != nil {
return nil, err
}
res := make(map[string]interface{})
res["functionName"] = "transferFromV2"
res["contractAddress"] = contractAddress
res["param"] = tf
if contractAddress == ONT_CONTRACT_ADDRESS {
res["asset"] = "ont"
} else if contractAddress == ONG_CONTRACT_ADDRESS {
res["asset"] = "ong"
}
return res, nil
}
}
return nil, fmt.Errorf("not native transfer and transferFrom transaction")
}
func getValue(source *common.ZeroCopySource) (uint64, error) {
var amount = uint64(0)
zeroByte, eof := source.NextByte()
if eof {
return 0, io.ErrUnexpectedEOF
}
if zeroByte == 0 {
amount = 0
} else if zeroByte >= 0x51 && zeroByte <= 0x5f {
b := common.BigIntFromNeoBytes([]byte{zeroByte})
amount = b.Uint64() - 0x50
} else {
source.BackUp(1)
amountBytes, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return 0, io.ErrUnexpectedEOF
}
amount = common.BigIntFromNeoBytes(amountBytes).Uint64()
}
return amount, nil
}
func getValueV2(source *common.ZeroCopySource) (*big.Int, error) {
var amount = big.NewInt(0)
zeroByte, eof := source.NextByte()
if eof {
return nil, io.ErrUnexpectedEOF
}
if zeroByte == 0 {
amount = big.NewInt(0)
} else if zeroByte >= 0x51 && zeroByte <= 0x5f {
b := common.BigIntFromNeoBytes([]byte{zeroByte})
amount = amount.Sub(b, big.NewInt(0x50))
} else {
source.BackUp(1)
amountBytes, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return nil, io.ErrUnexpectedEOF
}
amount = common.BigIntFromNeoBytes(amountBytes)
}
return amount, nil
}
func isEnd(source *common.ZeroCopySource) (bool, error) {
by, eof := source.NextByte()
if eof {
return true, io.EOF
}
if by == 0x00 || by >= 0x14 && by < 0x51 {
source.BackUp(1)
return false, nil
} else {
if by >= 0x51 && by <= 0x5f {
return true, nil
} else {
_, _, irregular, eof := source.NextVarUint()
if irregular || eof {
return true, io.ErrUnexpectedEOF
}
return true, nil
}
}
}
func readAddress(source *common.ZeroCopySource) (common.Address, error) {
senderBytes, _, irregular, eof := source.NextVarBytes()
if irregular || eof {
return common.ADDRESS_EMPTY, io.ErrUnexpectedEOF
}
sender, err := utils.AddressParseFromBytes(senderBytes)
if err != nil {
return common.ADDRESS_EMPTY, err
}
return sender, nil
}
func ignoreOpCodeV2(source *common.ZeroCopySource) error {
_, eof := source.NextBytes(3)
if eof {
return io.EOF
}
return nil
}
func ignoreOpCode(source *common.ZeroCopySource) error {
s := source.Size()
start := source.Pos()
for {
if source.Pos() >= s {
return nil
}
by, eof := source.NextByte()
if eof {
return io.EOF
}
if OPCODE_IN_PAYLOAD[by] {
continue
} else {
if start < source.Pos() {
source.BackUp(1)
}
return nil
}
}
}
func (this *OntologySdk) GenerateMnemonicCodesStr() (string, error) {
entropy, err := bip39.NewEntropy(128)
if err != nil {
return "", err
}
return bip39.NewMnemonic(entropy)
}
func (this *OntologySdk) GetPrivateKeyFromMnemonicCodesStrBip44(mnemonicCodesStr string, index uint32) ([]byte, error) {
if mnemonicCodesStr == "" {
return nil, fmt.Errorf("mnemonicCodesStr should not be nil")
}
//address_index
if index < 0 {
return nil, fmt.Errorf("index should be bigger than 0")
}
seed := bip39.NewSeed(mnemonicCodesStr, "")
masterKey, err := bip32.NewMasterKey(seed)
if err != nil {
return nil, err
}
//m / purpose' / coin_type' / account' / change / address_index
//coin type 1024'
coin := 0x80000400
//account 0'
account := 0x80000000
key, err := bip44.NewKeyFromMasterKey(masterKey, uint32(coin), uint32(account), 0, index)
if err != nil {
return nil, err
}
keyBytes, err := key.Serialize()
if err != nil {
return nil, err
}
return keyBytes[46:78], nil
}
//NewInvokeTransaction return smart contract invoke transaction
func (this *OntologySdk) NewInvokeTransaction(gasPrice, gasLimit uint64, invokeCode []byte) *types.MutableTransaction {
invokePayload := &payload.InvokeCode{
Code: invokeCode,
}
tx := &types.MutableTransaction{
GasPrice: gasPrice,
GasLimit: gasLimit,
TxType: types.InvokeNeo,
Nonce: rand.Uint32(),
Payload: invokePayload,
Sigs: make([]types.Sig, 0, 0),
}
return tx
}
func (this *OntologySdk) SetPayer(tx *types.MutableTransaction, payer common.Address) {
tx.Payer = payer
}
func (this *OntologySdk) SignToTransaction(tx *types.MutableTransaction, signer Signer) error {
if tx.Payer == common.ADDRESS_EMPTY {
account, ok := signer.(*Account)
if ok {
tx.Payer = account.Address
}
}
for _, sigs := range tx.Sigs {
if utils.PubKeysEqual([]keypair.PublicKey{signer.GetPublicKey()}, sigs.PubKeys) {
//have already signed
return nil
}
}
txHash := tx.Hash()
if this.ChainId == sdkcom.LAYER2_SYSTEM_ID {
tempTx, _ := tx.IntoImmutable()
txHash = tempTx.SigHashForChain(sdkcom.LAYER2_SYSTEM_ID)
}
sigData, err := signer.Sign(txHash.ToArray())
if err != nil {
return fmt.Errorf("sign error:%s", err)
}
if tx.Sigs == nil {
tx.Sigs = make([]types.Sig, 0)
}
tx.Sigs = append(tx.Sigs, types.Sig{
PubKeys: []keypair.PublicKey{signer.GetPublicKey()},
M: 1,
SigData: [][]byte{sigData},
})
return nil
}
func (this *OntologySdk) MultiSignToTransaction(tx *types.MutableTransaction, m uint16, pubKeys []keypair.PublicKey, signer Signer) error {
pkSize := len(pubKeys)
if m == 0 || int(m) > pkSize || pkSize > constants.MULTI_SIG_MAX_PUBKEY_SIZE {
return fmt.Errorf("both m and number of pub key must larger than 0, and small than %d, and m must smaller than pub key number", constants.MULTI_SIG_MAX_PUBKEY_SIZE)
}
validPubKey := false
for _, pk := range pubKeys {
if keypair.ComparePublicKey(pk, signer.GetPublicKey()) {
validPubKey = true
break
}
}
if !validPubKey {
return fmt.Errorf("invalid signer")
}
if tx.Payer == common.ADDRESS_EMPTY {
payer, err := types.AddressFromMultiPubKeys(pubKeys, int(m))
if err != nil {
return fmt.Errorf("AddressFromMultiPubKeys error:%s", err)
}
tx.Payer = payer
}
txHash := tx.Hash()
if this.ChainId == sdkcom.LAYER2_SYSTEM_ID {
tempTx, _ := tx.IntoImmutable()
txHash = tempTx.SigHashForChain(sdkcom.LAYER2_SYSTEM_ID)
}
if len(tx.Sigs) == 0 {
tx.Sigs = make([]types.Sig, 0)
}
sigData, err := signer.Sign(txHash.ToArray())
if err != nil {
return fmt.Errorf("sign error:%s", err)
}
hasMutilSig := false
for i, sigs := range tx.Sigs {
if utils.PubKeysEqual(sigs.PubKeys, pubKeys) {
hasMutilSig = true
if utils.HasAlreadySig(txHash.ToArray(), signer.GetPublicKey(), sigs.SigData) {
break
}
sigs.SigData = append(sigs.SigData, sigData)
tx.Sigs[i] = sigs
break
}
}
if !hasMutilSig {
tx.Sigs = append(tx.Sigs, types.Sig{
PubKeys: pubKeys,
M: m,
SigData: [][]byte{sigData},
})
}
return nil
}
func (this *OntologySdk) GetTxData(tx *types.MutableTransaction) (string, error) {
txData, err := tx.IntoImmutable()
if err != nil {
return "", fmt.Errorf("IntoImmutable error:%s", err)
}
sink := common.ZeroCopySink{}
txData.Serialization(&sink)
rawtx := hex.EncodeToString(sink.Bytes())
return rawtx, nil
}
type TransferEvent struct {
FuncName string
From string
To string
Amount uint64
}
func (this *OntologySdk) ParseNativeTransferEvent(event *event.NotifyEventInfo) (*TransferEvent, error) {
if event == nil {
return nil, fmt.Errorf("event is nil")
}
state, ok := event.States.([]interface{})
if !ok {
return nil, fmt.Errorf("state.States is not []interface")
}
if len(state) != 4 {
return nil, fmt.Errorf("state length is not 4")
}
funcName, ok := state[0].(string)
if !ok {
return nil, fmt.Errorf("state.States[0] is not string")
}
if funcName != "transfer" {
return nil, fmt.Errorf("funcName is not transfer")
} else {
from, ok := state[1].(string)
if !ok {
return nil, fmt.Errorf("state[1] is not string")
}
to, ok := state[2].(string)
if !ok {
return nil, fmt.Errorf("state[2] is not string")
}
amount, ok := state[3].(uint64)
if !ok {
return nil, fmt.Errorf("state[3] is not uint64")
}
return &TransferEvent{
FuncName: "transfer",
From: from,
To: to,
Amount: uint64(amount),
}, nil
}
}
type TransferEventV2 struct {
FuncName string
From string
To string
Amount *big.Int
}
func (this *OntologySdk) ParseNativeTransferEventV2(event *sdkcom.NotifyEventInfo) (*TransferEventV2, error) {
if event == nil {
return nil, fmt.Errorf("event is nil")
}
state, ok := event.States.([]interface{})
if !ok {
return nil, fmt.Errorf("state.States is not []interface")
}
if len(state) != 4 && len(state) != 5 {
return nil, fmt.Errorf("state length is not 4 or 5")
}
funcName, ok := state[0].(string)
if !ok {
return nil, fmt.Errorf("state.States[0] is not string")
}
if funcName != "transfer" {
return nil, fmt.Errorf("funcName is not transfer")
} else {
from, ok := state[1].(string)
if !ok {
return nil, fmt.Errorf("state[1] is not string")
}
to, ok := state[2].(string)
if !ok {
return nil, fmt.Errorf("state[2] is not string")
}
amount, ok := state[3].(json.Number)
if !ok {
return nil, fmt.Errorf("state[3] is not uint64")
}
transAmount, err := amount.Int64()
if err != nil {
return nil, err
}
if len(state) == 5 {
value, ok := state[4].(json.Number)
if !ok {
return nil, fmt.Errorf("state[4] is not uint64")
}
transValue, err := value.Int64()
if err != nil {
return nil, err
}
res := big.NewInt(transAmount)
res.Mul(res, big.NewInt(constants.GWei))
res.Add(res, big.NewInt(transValue))
return &TransferEventV2{
FuncName: "transfer",
From: from,
To: to,
Amount: res,
}, nil
}
return &TransferEventV2{
FuncName: "transfer",
From: from,
To: to,
Amount: big.NewInt(transAmount),
}, nil
}
}
func (this *OntologySdk) GetMutableTx(rawTx string) (*types.MutableTransaction, error) {
txData, err := hex.DecodeString(rawTx)
if err != nil {
return nil, fmt.Errorf("RawTx hex decode error:%s", err)
}
tx, err := types.TransactionFromRawBytes(txData)
if err != nil {
return nil, fmt.Errorf("TransactionFromRawBytes error:%s", err)
}
mutTx, err := tx.IntoMutable()
if err != nil {
return nil, fmt.Errorf("[ONT]IntoMutable error:%s", err)
}
return mutTx, nil
}
func (this *OntologySdk) GetMultiAddr(pubkeys []keypair.PublicKey, m int) (string, error) {
addr, err := types.AddressFromMultiPubKeys(pubkeys, m)
if err != nil {
return "", fmt.Errorf("GetMultiAddrs error:%s", err)
}
return addr.ToBase58(), nil
}
func (this *OntologySdk) GetAdddrByPubKey(pubKey keypair.PublicKey) string {
address := types.AddressFromPubKey(pubKey)
return address.ToBase58()
}
func (this *OntologySdk) SendTransaction(tx *types.MutableTransaction) (common.Uint256, error) {
return this.ClientMgr.SendTransaction(tx)
}