-
Notifications
You must be signed in to change notification settings - Fork 3
/
contract_client_test.go
1179 lines (1001 loc) · 43.5 KB
/
contract_client_test.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
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
//go:build integrationtests
// +build integrationtests
package coreum_test
import (
"context"
"crypto/rand"
"fmt"
"strconv"
"strings"
"testing"
sdkmath "cosmossdk.io/math"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/gogoproto/proto"
rippledata "github.com/rubblelabs/ripple/data"
"github.com/samber/lo"
"github.com/stretchr/testify/require"
"github.com/CoreumFoundation/coreum/v3/testutil/event"
coreumintegration "github.com/CoreumFoundation/coreum/v3/testutil/integration"
assetfttypes "github.com/CoreumFoundation/coreum/v3/x/asset/ft/types"
integrationtests "github.com/CoreumFoundation/coreumbridge-xrpl/integration-tests"
"github.com/CoreumFoundation/coreumbridge-xrpl/relayer/coreum"
"github.com/CoreumFoundation/coreumbridge-xrpl/relayer/xrpl"
)
const (
xrp = "XRP"
drop = "drop"
xrplPrecision = 15
xrpIssuer = "rrrrrrrrrrrrrrrrrrrrrho"
xrpCurrency = "XRP"
eventAttributeThresholdReached = "threshold_reached"
)
var defaultTrustSetLimitAmount = sdkmath.NewInt(10000000000000000)
func TestDeployAndInstantiateContract(t *testing.T) {
t.Parallel()
ctx, chains := integrationtests.NewTestingContext(t)
assetftClient := assetfttypes.NewQueryClient(chains.Coreum.ClientContext)
relayers := genRelayers(ctx, t, chains, 1)
usedTicketsThreshold := 10
owner, contractClient := integrationtests.DeployAndInstantiateContract(
ctx,
t,
chains,
relayers,
len(relayers),
usedTicketsThreshold,
defaultTrustSetLimitAmount,
)
contractCfg, err := contractClient.GetContractConfig(ctx)
require.NoError(t, err)
require.Equal(t, coreum.ContractConfig{
Relayers: relayers,
EvidenceThreshold: len(relayers),
UsedTicketsThreshold: usedTicketsThreshold,
TrustSetLimitAmount: defaultTrustSetLimitAmount,
}, contractCfg)
contractOwnership, err := contractClient.GetContractOwnership(ctx)
require.NoError(t, err)
require.Equal(t, coreum.ContractOwnership{
Owner: owner,
PendingOwner: sdk.AccAddress{},
}, contractOwnership)
contractAddress := contractClient.GetContractAddress()
tokensRes, err := assetftClient.Tokens(ctx, &assetfttypes.QueryTokensRequest{
Issuer: contractAddress.String(),
})
require.NoError(t, err)
require.Len(t, tokensRes.Tokens, 1)
coreumDenom := fmt.Sprintf("%s-%s", drop, contractAddress.String())
require.Equal(t, assetfttypes.Token{
Denom: coreumDenom,
Issuer: contractAddress.String(),
Symbol: xrp,
Subunit: drop,
Precision: 6,
Description: "",
GloballyFrozen: false,
Features: []assetfttypes.Feature{assetfttypes.Feature_minting, assetfttypes.Feature_burning, assetfttypes.Feature_ibc},
BurnRate: sdk.ZeroDec(),
SendCommissionRate: sdk.ZeroDec(),
Version: assetfttypes.CurrentTokenVersion,
}, tokensRes.Tokens[0])
// query all tokens
xrplTokens, err := contractClient.GetXRPLTokens(ctx)
require.NoError(t, err)
require.Len(t, xrplTokens, 1)
require.Equal(t, coreum.XRPLToken{
Issuer: xrpIssuer,
Currency: xrpCurrency,
CoreumDenom: coreumDenom,
State: coreum.TokenStateEnabled,
}, xrplTokens[0])
}
func TestChangeContractOwnership(t *testing.T) {
t.Parallel()
ctx, chains := integrationtests.NewTestingContext(t)
relayers := genRelayers(ctx, t, chains, 1)
usedTicketsThreshold := 10
owner, contractClient := integrationtests.DeployAndInstantiateContract(
ctx,
t,
chains,
relayers,
len(relayers),
usedTicketsThreshold,
defaultTrustSetLimitAmount,
)
contractOwnership, err := contractClient.GetContractOwnership(ctx)
require.NoError(t, err)
require.Equal(t, owner.String(), contractOwnership.Owner.String())
newOwner := chains.Coreum.GenAccount()
// fund to cover fees
chains.Coreum.FundAccountWithOptions(ctx, t, newOwner, coreumintegration.BalancesOptions{
Amount: sdkmath.NewIntFromUint64(1_000_000),
})
// transfer ownership
_, err = contractClient.TransferOwnership(ctx, owner, newOwner)
require.NoError(t, err)
contractOwnership, err = contractClient.GetContractOwnership(ctx)
require.NoError(t, err)
// the owner is still old until new owner accepts the ownership
require.Equal(t, owner.String(), contractOwnership.Owner.String())
require.Equal(t, newOwner.String(), contractOwnership.PendingOwner.String())
// accept the ownership
_, err = contractClient.AcceptOwnership(ctx, newOwner)
require.NoError(t, err)
contractOwnership, err = contractClient.GetContractOwnership(ctx)
require.NoError(t, err)
// the contract has a new owner
require.Equal(t, newOwner.String(), contractOwnership.Owner.String())
// try to update the ownership one more time (from old owner)
_, err = contractClient.TransferOwnership(ctx, owner, newOwner)
require.True(t, coreum.IsNotOwnerError(err), err)
}
func TestRegisterCoreumToken(t *testing.T) {
t.Parallel()
ctx, chains := integrationtests.NewTestingContext(t)
xrplRelayerSigner := xrpl.GenPrivKeyTxSigner()
relayers := []coreum.Relayer{
{
CoreumAddress: chains.Coreum.GenAccount(),
XRPLAddress: xrplRelayerSigner.Account().String(),
XRPLPubKey: xrplRelayerSigner.PubKey().String(),
},
}
usedTicketsThreshold := 10
notOwner := chains.Coreum.GenAccount()
chains.Coreum.FundAccountWithOptions(ctx, t, notOwner, coreumintegration.BalancesOptions{
Amount: sdkmath.NewInt(1_000_000),
})
owner, contractClient := integrationtests.DeployAndInstantiateContract(
ctx,
t,
chains,
relayers,
len(relayers),
usedTicketsThreshold,
defaultTrustSetLimitAmount,
)
denom1 := "denom1"
denom1Decimals := uint32(17)
// try to register from not owner
_, err := contractClient.RegisterCoreumToken(ctx, notOwner, denom1, denom1Decimals)
require.True(t, coreum.IsNotOwnerError(err), err)
// register from the owner
_, err = contractClient.RegisterCoreumToken(ctx, owner, denom1, denom1Decimals)
require.NoError(t, err)
// try to register the same denom one more time
_, err = contractClient.RegisterCoreumToken(ctx, owner, denom1, denom1Decimals)
require.True(t, coreum.IsCoreumTokenAlreadyRegisteredError(err), err)
coreumTokens, err := contractClient.GetCoreumTokens(ctx)
require.NoError(t, err)
require.Len(t, coreumTokens, 1)
registeredToken := coreumTokens[0]
require.Equal(t, denom1, registeredToken.Denom)
require.Equal(t, denom1Decimals, registeredToken.Decimals)
require.NotEmpty(t, registeredToken.XRPLCurrency)
// try to use the registered denom with new XRPL currency on the XRPL chain
issuerAcc := chains.XRPL.GenAccount(ctx, t, 10)
recipientAcc := chains.XRPL.GenAccount(ctx, t, 10)
// allow to receive the currency
amountToSend, err := rippledata.NewValue("10000000000000000", false)
require.NoError(t, err)
currency, err := rippledata.NewCurrency(registeredToken.XRPLCurrency)
require.NoError(t, err)
trustSetTx := rippledata.TrustSet{
LimitAmount: rippledata.Amount{
Value: amountToSend,
Currency: currency,
Issuer: issuerAcc,
},
TxBase: rippledata.TxBase{
TransactionType: rippledata.TRUST_SET,
},
}
require.NoError(t, chains.XRPL.AutoFillSignAndSubmitTx(ctx, t, &trustSetTx, recipientAcc))
paymentTx := rippledata.Payment{
Destination: recipientAcc,
Amount: rippledata.Amount{
Value: amountToSend,
Currency: currency,
Issuer: issuerAcc,
},
TxBase: rippledata.TxBase{
TransactionType: rippledata.PAYMENT,
},
}
balancesBeforeSend := chains.XRPL.GetAccountBalances(ctx, t, recipientAcc)
t.Logf("Recipient account balances before send: %s", balancesBeforeSend)
require.NoError(t, chains.XRPL.AutoFillSignAndSubmitTx(ctx, t, &paymentTx, issuerAcc))
balancesAfterSend := chains.XRPL.GetAccountBalances(ctx, t, recipientAcc)
t.Logf("Recipient account balances after send: %s", balancesAfterSend)
receiveAmount, ok := balancesAfterSend[fmt.Sprintf("%s/%s", currency.String(), issuerAcc.String())]
require.True(t, ok)
require.Equal(t, amountToSend.String(), receiveAmount.Value.String())
}
func TestRegisterXRPLToken(t *testing.T) {
t.Parallel()
ctx, chains := integrationtests.NewTestingContext(t)
assetftClient := assetfttypes.NewQueryClient(chains.Coreum.ClientContext)
bankClient := banktypes.NewQueryClient(chains.Coreum.ClientContext)
relayers := genRelayers(ctx, t, chains, 2)
usedTicketsThreshold := 3
coreumRecipient := chains.Coreum.GenAccount()
notOwner := chains.Coreum.GenAccount()
issueFee := chains.Coreum.QueryAssetFTParams(ctx, t).IssueFee
// fund with issuance fee and some coins on to cover fees
chains.Coreum.FundAccountWithOptions(ctx, t, notOwner, coreumintegration.BalancesOptions{
Amount: issueFee.Amount.AddRaw(1_000_000),
})
owner, contractClient := integrationtests.DeployAndInstantiateContract(
ctx,
t,
chains,
relayers,
len(relayers),
usedTicketsThreshold,
defaultTrustSetLimitAmount,
)
// fund owner to cover registration fees twice
chains.Coreum.FundAccountWithOptions(ctx, t, owner, coreumintegration.BalancesOptions{
Amount: issueFee.Amount.Mul(sdkmath.NewIntFromUint64(2)),
})
issuerAcc := chains.XRPL.GenAccount(ctx, t, 0)
issuer := issuerAcc.String()
invactiveCurrency := "INA"
activeCurrency := "ACT"
sendingPrecision := int32(15)
maxHoldingAmount := sdk.NewIntFromUint64(10000)
// recover tickets so that we can create a pending operation to activate the token
allocateInitialTickets(ctx, t, contractClient, owner, relayers)
// try to register from not owner
_, err := contractClient.RegisterXRPLToken(ctx, notOwner, issuer, invactiveCurrency, sendingPrecision, maxHoldingAmount)
require.True(t, coreum.IsNotOwnerError(err), err)
// register from the owner
_, err = contractClient.RegisterXRPLToken(ctx, owner, issuer, invactiveCurrency, sendingPrecision, maxHoldingAmount)
require.NoError(t, err)
// try to register the same denom one more time
_, err = contractClient.RegisterXRPLToken(ctx, owner, issuer, invactiveCurrency, sendingPrecision, maxHoldingAmount)
require.True(t, coreum.IsXRPLTokenAlreadyRegisteredError(err), err)
xrplTokens, err := contractClient.GetXRPLTokens(ctx)
require.NoError(t, err)
// one XRP token and registered
require.Len(t, xrplTokens, 2)
registeredInactiveToken, err := contractClient.GetXRPLToken(ctx, issuer, invactiveCurrency)
require.NoError(t, err)
require.NotNil(t, registeredInactiveToken)
require.Equal(t, coreum.XRPLToken{
Issuer: issuer,
Currency: invactiveCurrency,
CoreumDenom: registeredInactiveToken.CoreumDenom,
State: coreum.TokenStateProcessing,
}, *registeredInactiveToken)
// check that corresponding token is issued
contractAddress := contractClient.GetContractAddress()
tokenRes, err := assetftClient.Token(ctx, &assetfttypes.QueryTokenRequest{
Denom: registeredInactiveToken.CoreumDenom,
})
require.NoError(t, err)
// deconstruct the denom to get prefix used for the symbol and subunit
prefix, _, err := assetfttypes.DeconstructDenom(registeredInactiveToken.CoreumDenom)
require.NoError(t, err)
require.Equal(t, assetfttypes.Token{
Denom: registeredInactiveToken.CoreumDenom,
Issuer: contractAddress.String(),
Symbol: strings.ToUpper(prefix),
Subunit: prefix,
Precision: xrplPrecision,
Description: "",
GloballyFrozen: false,
Features: []assetfttypes.Feature{assetfttypes.Feature_minting, assetfttypes.Feature_burning, assetfttypes.Feature_ibc},
BurnRate: sdk.ZeroDec(),
SendCommissionRate: sdk.ZeroDec(),
Version: assetfttypes.CurrentTokenVersion,
}, tokenRes.Token)
// go through the trust set evidence use cases
pendingOperations, err := contractClient.GetPendingOperations(ctx)
require.NoError(t, err)
require.Len(t, pendingOperations, 1)
operation := pendingOperations[0]
require.NotNil(t, operation.OperationType.TrustSet)
rejectTxEvidenceTrustSet := coreum.XRPLTransactionResultTrustSetEvidence{
XRPLTransactionResultEvidence: coreum.XRPLTransactionResultEvidence{
TxHash: genXRPLTxHash(t),
TicketNumber: &operation.TicketNumber,
TransactionResult: coreum.TransactionResultRejected,
},
Issuer: issuer,
Currency: invactiveCurrency,
}
// try to register not existing operation
invalidEvidenceTrustSetWithInvalidTicket := rejectTxEvidenceTrustSet
invalidEvidenceTrustSetWithInvalidTicket.TicketNumber = lo.ToPtr(uint32(99))
_, err = contractClient.SendXRPLTrustSetTransactionResultEvidence(ctx, relayers[0].CoreumAddress, invalidEvidenceTrustSetWithInvalidTicket)
require.True(t, coreum.IsPendingOperationNotFoundError(err), err)
// try to register with not existing currency
invalidEvidenceNotExistingIssuer := rejectTxEvidenceTrustSet
invalidEvidenceNotExistingIssuer.Issuer = xrpl.GenPrivKeyTxSigner().Account().String()
_, err = contractClient.SendXRPLTrustSetTransactionResultEvidence(ctx, relayers[0].CoreumAddress, invalidEvidenceNotExistingIssuer)
require.True(t, coreum.IsTokenNotRegisteredError(err), err)
// send valid rejected evidence from first relayer
txResTrustSet, err := contractClient.SendXRPLTrustSetTransactionResultEvidence(ctx, relayers[0].CoreumAddress, rejectTxEvidenceTrustSet)
require.NoError(t, err)
thresholdReachedTrustSet, err := event.FindStringEventAttribute(txResTrustSet.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)
require.Equal(t, strconv.FormatBool(false), thresholdReachedTrustSet)
// send valid rejected evidence from second relayer
txResTrustSet, err = contractClient.SendXRPLTrustSetTransactionResultEvidence(ctx, relayers[1].CoreumAddress, rejectTxEvidenceTrustSet)
require.NoError(t, err)
thresholdReachedTrustSet, err = event.FindStringEventAttribute(txResTrustSet.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)
require.Equal(t, strconv.FormatBool(true), thresholdReachedTrustSet)
registeredInactiveToken, err = contractClient.GetXRPLToken(ctx, issuer, invactiveCurrency)
require.NoError(t, err)
require.NotNil(t, registeredInactiveToken)
require.Equal(t, coreum.XRPLToken{
Issuer: issuer,
Currency: invactiveCurrency,
CoreumDenom: registeredInactiveToken.CoreumDenom,
State: coreum.TokenStateInactive,
}, *registeredInactiveToken)
// try to send evidence one more time
_, err = contractClient.SendXRPLTrustSetTransactionResultEvidence(ctx, relayers[1].CoreumAddress, rejectTxEvidenceTrustSet)
require.True(t, coreum.IsOperationAlreadyExecutedError(err), err)
// try to register the sending from the XRPL to coreum evidence with inactive token
xrplToCoreumInactiveTokenTransferEvidence := coreum.XRPLToCoreumTransferEvidence{
TxHash: genXRPLTxHash(t),
Issuer: issuerAcc.String(),
Currency: invactiveCurrency,
Amount: sdkmath.NewInt(10),
Recipient: coreumRecipient,
}
_, err = contractClient.SendXRPLToCoreumTransferEvidence(ctx, relayers[1].CoreumAddress, xrplToCoreumInactiveTokenTransferEvidence)
require.True(t, coreum.IsXRPLTokenNotEnabledError(err), err)
_ = activeCurrency
// register one more token and activate it
_, err = contractClient.RegisterXRPLToken(ctx, owner, issuer, activeCurrency, sendingPrecision, maxHoldingAmount)
require.NoError(t, err)
registeredActiveToken, err := contractClient.GetXRPLToken(ctx, issuer, activeCurrency)
require.NoError(t, err)
require.NotNil(t, registeredInactiveToken)
require.Equal(t, coreum.XRPLToken{
Issuer: issuer,
Currency: activeCurrency,
CoreumDenom: registeredActiveToken.CoreumDenom,
State: coreum.TokenStateProcessing,
}, *registeredActiveToken)
activateXRPLToken(ctx, t, contractClient, relayers, issuer, activeCurrency)
amountToSend := sdkmath.NewInt(99)
sendFromXRPLToCoreum(ctx, t, contractClient, relayers, issuer, activeCurrency, amountToSend, coreumRecipient)
balanceRes, err := bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: coreumRecipient.String(),
Denom: registeredActiveToken.CoreumDenom,
})
require.NoError(t, err)
require.Equal(t, amountToSend.String(), balanceRes.Balance.Amount.String())
}
func TestSendFromXRPLToCoreumXRPLNativeToken(t *testing.T) {
t.Parallel()
ctx, chains := integrationtests.NewTestingContext(t)
coreumRecipient := chains.Coreum.GenAccount()
randomAddress := chains.Coreum.GenAccount()
relayers := genRelayers(ctx, t, chains, 2)
bankClient := banktypes.NewQueryClient(chains.Coreum.ClientContext)
chains.Coreum.FundAccountWithOptions(ctx, t, randomAddress, coreumintegration.BalancesOptions{
Amount: sdkmath.NewInt(1_000_000),
})
usedTicketsThreshold := 3
owner, contractClient := integrationtests.DeployAndInstantiateContract(
ctx,
t,
chains,
relayers,
len(relayers),
usedTicketsThreshold,
defaultTrustSetLimitAmount,
)
issueFee := chains.Coreum.QueryAssetFTParams(ctx, t).IssueFee
// fund owner to cover registration fees twice
chains.Coreum.FundAccountWithOptions(ctx, t, owner, coreumintegration.BalancesOptions{
Amount: issueFee.Amount.Mul(sdkmath.NewIntFromUint64(2)),
})
issuerAcc := chains.XRPL.GenAccount(ctx, t, 0)
issuer := issuerAcc.String()
currency := "RCR"
sendingPrecision := int32(15)
maxHoldingAmount := sdk.NewIntFromUint64(10000)
// recover tickets so that we can create a pending operation to activate the token
allocateInitialTickets(ctx, t, contractClient, owner, relayers)
// register from the owner
_, err := contractClient.RegisterXRPLToken(ctx, owner, issuer, currency, sendingPrecision, maxHoldingAmount)
require.NoError(t, err)
xrplTokens, err := contractClient.GetXRPLTokens(ctx)
require.NoError(t, err)
// find registered token
var registeredToken coreum.XRPLToken
for _, token := range xrplTokens {
if token.Issuer == issuer && token.Currency == currency {
registeredToken = token
break
}
}
require.Equal(t, issuer, registeredToken.Issuer)
require.Equal(t, currency, registeredToken.Currency)
require.NotEmpty(t, registeredToken.CoreumDenom)
// activate token
activateXRPLToken(ctx, t, contractClient, relayers, issuer, currency)
// create an evidence to transfer tokens from XRPL to Coreum
xrplToCoreumTransferEvidence := coreum.XRPLToCoreumTransferEvidence{
TxHash: genXRPLTxHash(t),
Issuer: issuerAcc.String(),
Currency: currency,
Amount: sdkmath.NewInt(10),
Recipient: coreumRecipient,
}
// try to call from not relayer
_, err = contractClient.SendXRPLToCoreumTransferEvidence(ctx, randomAddress, xrplToCoreumTransferEvidence)
require.True(t, coreum.IsUnauthorizedSenderError(err), err)
// try use not registered token
wrongXRPLToCoreumTransferEvidence := xrplToCoreumTransferEvidence
wrongXRPLToCoreumTransferEvidence.Currency = "NEZ"
_, err = contractClient.SendXRPLToCoreumTransferEvidence(ctx, relayers[0].CoreumAddress, wrongXRPLToCoreumTransferEvidence)
require.True(t, coreum.IsTokenNotRegisteredError(err), err)
// call from first relayer
txRes, err := contractClient.SendXRPLToCoreumTransferEvidence(ctx, relayers[0].CoreumAddress, xrplToCoreumTransferEvidence)
require.NoError(t, err)
recipientBalanceRes, err := bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: coreumRecipient.String(),
Denom: registeredToken.CoreumDenom,
})
require.NoError(t, err)
require.True(t, recipientBalanceRes.Balance.IsZero())
thresholdReached, err := event.FindStringEventAttribute(txRes.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)
require.Equal(t, strconv.FormatBool(false), thresholdReached)
// call from first relayer one more time
_, err = contractClient.SendXRPLToCoreumTransferEvidence(ctx, relayers[0].CoreumAddress, xrplToCoreumTransferEvidence)
require.True(t, coreum.IsEvidenceAlreadyProvidedError(err), err)
// call from second relayer
txRes, err = contractClient.SendXRPLToCoreumTransferEvidence(ctx, relayers[1].CoreumAddress, xrplToCoreumTransferEvidence)
require.NoError(t, err)
recipientBalanceRes, err = bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: coreumRecipient.String(),
Denom: registeredToken.CoreumDenom,
})
require.NoError(t, err)
thresholdReached, err = event.FindStringEventAttribute(txRes.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)
require.Equal(t, strconv.FormatBool(true), thresholdReached)
require.NoError(t, err)
// expect new token on the recipient balance
require.Equal(t, xrplToCoreumTransferEvidence.Amount.String(), recipientBalanceRes.Balance.Amount.String())
// try to push the same evidence
_, err = contractClient.SendXRPLToCoreumTransferEvidence(ctx, relayers[0].CoreumAddress, xrplToCoreumTransferEvidence)
require.True(t, coreum.IsOperationAlreadyExecutedError(err), err)
}
func TestSendFromXRPLToCoreumXRPLNativeTokenWithDifferentSendingPrecision(t *testing.T) {
// intentionally not parallel
var (
tokenDecimals = int64(15)
highMaxHoldingAmount = integrationtests.ConvertStringWithDecimalsToSDKInt(t, "1", 30)
)
ctx, chains := integrationtests.NewTestingContext(t)
bankClient := banktypes.NewQueryClient(chains.Coreum.ClientContext)
relayers := genRelayers(ctx, t, chains, 2)
coreumRecipient := chains.Coreum.GenAccount()
usedTicketsThreshold := 10
owner, contractClient := integrationtests.DeployAndInstantiateContract(
ctx,
t,
chains,
relayers,
len(relayers),
usedTicketsThreshold,
defaultTrustSetLimitAmount,
)
// register tickets
allocateInitialTickets(ctx, t, contractClient, owner, relayers)
issueFee := chains.Coreum.QueryAssetFTParams(ctx, t).IssueFee
tests := []struct {
name string
sendingPrecision int32
sendingAmount sdkmath.Int
maxHoldingAmount sdkmath.Int
wantReceivedAmount sdkmath.Int
wantIsAmountSentIsZeroAfterTruncationError bool
wantIsMaximumBridgedAmountReachedError bool
}{
{
name: "positive_precision_no_truncation",
sendingPrecision: 2,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999999999.15", tokenDecimals),
wantReceivedAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999999999.15", tokenDecimals),
},
{
name: "positive_precision_with_truncation",
sendingPrecision: 2,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "0.15567", tokenDecimals),
wantReceivedAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "0.15", tokenDecimals),
},
{
name: "positive_precision_low_amount",
sendingPrecision: 2,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "0.009999", tokenDecimals),
wantIsAmountSentIsZeroAfterTruncationError: true,
},
{
name: "zero_precision_no_truncation",
sendingPrecision: 0,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999999999", tokenDecimals),
wantReceivedAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999999999", tokenDecimals),
},
{
name: "zero_precision_with_truncation",
sendingPrecision: 0,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "1.15567", tokenDecimals),
wantReceivedAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "1", tokenDecimals),
},
{
name: "zero_precision_low_amount",
sendingPrecision: 0,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "0.9999", tokenDecimals),
wantIsAmountSentIsZeroAfterTruncationError: true,
},
{
name: "negative_precision_no_truncation",
sendingPrecision: -2,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999999900", tokenDecimals),
wantReceivedAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999999900", tokenDecimals),
},
{
name: "negative_precision_with_truncation",
sendingPrecision: -2,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999.15567", tokenDecimals),
wantReceivedAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9900", tokenDecimals),
},
{
name: "negative_precision_low_amount",
sendingPrecision: -2,
maxHoldingAmount: highMaxHoldingAmount,
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "99.9999", tokenDecimals),
wantIsAmountSentIsZeroAfterTruncationError: true,
},
{
name: "reached_max_holding_amount",
sendingPrecision: 2,
maxHoldingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999", tokenDecimals),
sendingAmount: integrationtests.ConvertStringWithDecimalsToSDKInt(t, "9999.01", tokenDecimals),
wantIsMaximumBridgedAmountReachedError: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
// fund owner to cover registration fee twice
chains.Coreum.FundAccountWithOptions(ctx, t, owner, coreumintegration.BalancesOptions{
Amount: issueFee.Amount,
})
issuerAcc := xrpl.GenPrivKeyTxSigner().Account()
issuer := issuerAcc.String()
currency := "CRC"
// register from the owner
txRes, err := contractClient.RegisterXRPLToken(ctx, owner, issuer, currency, tt.sendingPrecision, tt.maxHoldingAmount)
require.NoError(t, err)
issuedDenom := findOneIssuedDenomInTxResponse(t, txRes)
// create an evidence
xrplToCoreumTransferEvidence := coreum.XRPLToCoreumTransferEvidence{
TxHash: genXRPLTxHash(t),
Issuer: issuerAcc.String(),
Currency: currency,
Amount: tt.sendingAmount,
Recipient: coreumRecipient,
}
// activate token
activateXRPLToken(ctx, t, contractClient, relayers, issuerAcc.String(), currency)
// call from all relayers
for _, relayer := range relayers {
_, err = contractClient.SendXRPLToCoreumTransferEvidence(ctx, relayer.CoreumAddress, xrplToCoreumTransferEvidence)
if tt.wantIsAmountSentIsZeroAfterTruncationError {
require.True(t, coreum.IsAmountSentIsZeroAfterTruncationError(err), err)
return
}
if tt.wantIsMaximumBridgedAmountReachedError {
require.True(t, coreum.IsMaximumBridgedAmountReachedError(err), err)
return
}
require.NoError(t, err)
}
balanceRes, err := bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: coreumRecipient.String(),
Denom: issuedDenom,
})
require.NoError(t, err)
require.Equal(t, tt.wantReceivedAmount.String(), balanceRes.Balance.Amount.String())
})
}
}
func TestRecoverTickets(t *testing.T) {
t.Parallel()
// TODO(dzmitryhil) extend the test to check multiple operations once we have them allowed to be created
usedTicketsThreshold := 5
numberOfTicketsToInit := uint32(6)
ctx, chains := integrationtests.NewTestingContext(t)
relayers := genRelayers(ctx, t, chains, 3)
owner, contractClient := integrationtests.DeployAndInstantiateContract(
ctx,
t,
chains,
relayers,
2,
usedTicketsThreshold,
defaultTrustSetLimitAmount,
)
// ********** Ticket allocation / Recovery **********
firstBridgeAccountSeqNumber := uint32(1)
// try to call from not owner
_, err := contractClient.RecoverTickets(ctx, relayers[0].CoreumAddress, firstBridgeAccountSeqNumber, &numberOfTicketsToInit)
require.True(t, coreum.IsNotOwnerError(err), err)
// try to use more than max allowed tickets
_, err = contractClient.RecoverTickets(ctx, owner, firstBridgeAccountSeqNumber, lo.ToPtr(uint32(251)))
require.True(t, coreum.IsInvalidTicketNumberToAllocateError(err), err)
// try to use zero tickets
_, err = contractClient.RecoverTickets(ctx, owner, firstBridgeAccountSeqNumber, lo.ToPtr(uint32(0)))
require.True(t, coreum.IsInvalidTicketNumberToAllocateError(err), err)
_, err = contractClient.RecoverTickets(ctx, owner, firstBridgeAccountSeqNumber, &numberOfTicketsToInit)
require.NoError(t, err)
availableTickets, err := contractClient.GetAvailableTickets(ctx)
require.NoError(t, err)
require.Empty(t, availableTickets)
// check that we have just one operation with correct data
pendingOperations, err := contractClient.GetPendingOperations(ctx)
require.NoError(t, err)
require.Len(t, pendingOperations, 1)
ticketsAllocationOperation := pendingOperations[0]
require.Equal(t, coreum.Operation{
TicketNumber: 0,
SequenceNumber: firstBridgeAccountSeqNumber,
Signatures: make([]coreum.Signature, 0),
OperationType: coreum.OperationType{
AllocateTickets: &coreum.OperationTypeAllocateTickets{
Number: numberOfTicketsToInit,
},
},
}, ticketsAllocationOperation)
// try to recover tickets when the tickets allocation is in-process
_, err = contractClient.RecoverTickets(ctx, owner, firstBridgeAccountSeqNumber, &numberOfTicketsToInit)
require.True(t, coreum.IsPendingTicketUpdateError(err), err)
// ********** Signatures **********
createTicketsTx := rippledata.TicketCreate{
TicketCount: lo.ToPtr(numberOfTicketsToInit),
TxBase: rippledata.TxBase{
TransactionType: rippledata.TICKET_CREATE,
},
}
relayer1XRPLAcc, err := rippledata.NewAccountFromAddress(relayers[0].XRPLAddress)
require.NoError(t, err)
signerItem1 := chains.XRPL.Multisign(t, &createTicketsTx, *relayer1XRPLAcc).Signer
// try to send from not relayer
_, err = contractClient.RegisterSignature(ctx, owner, firstBridgeAccountSeqNumber, signerItem1.TxnSignature.String())
require.True(t, coreum.IsUnauthorizedSenderError(err), err)
// try to send with incorrect operation ID
_, err = contractClient.RegisterSignature(ctx, relayers[0].CoreumAddress, uint32(999), signerItem1.TxnSignature.String())
require.True(t, coreum.IsPendingOperationNotFoundError(err), err)
// send from first relayer
_, err = contractClient.RegisterSignature(ctx, relayers[0].CoreumAddress, firstBridgeAccountSeqNumber, signerItem1.TxnSignature.String())
require.NoError(t, err)
// try to send from the same relayer one more time
_, err = contractClient.RegisterSignature(ctx, relayers[0].CoreumAddress, firstBridgeAccountSeqNumber, signerItem1.TxnSignature.String())
require.True(t, coreum.IsSignatureAlreadyProvidedError(err), err)
// send from second relayer
createTicketsTx = rippledata.TicketCreate{
TicketCount: lo.ToPtr(numberOfTicketsToInit),
TxBase: rippledata.TxBase{
TransactionType: rippledata.TICKET_CREATE,
},
}
relayer2XRPLAcc, err := rippledata.NewAccountFromAddress(relayers[0].XRPLAddress)
require.NoError(t, err)
signerItem2 := chains.XRPL.Multisign(t, &createTicketsTx, *relayer2XRPLAcc).Signer
_, err = contractClient.RegisterSignature(ctx, relayers[1].CoreumAddress, firstBridgeAccountSeqNumber, signerItem2.TxnSignature.String())
require.NoError(t, err)
pendingOperations, err = contractClient.GetPendingOperations(ctx)
require.NoError(t, err)
require.Len(t, pendingOperations, 1)
ticketsAllocationOperation = pendingOperations[0]
require.Equal(t, coreum.Operation{
TicketNumber: 0,
SequenceNumber: firstBridgeAccountSeqNumber,
Signatures: []coreum.Signature{
{
Relayer: relayers[0].CoreumAddress,
Signature: signerItem1.TxnSignature.String(),
},
{
Relayer: relayers[1].CoreumAddress,
Signature: signerItem2.TxnSignature.String(),
},
},
OperationType: coreum.OperationType{
AllocateTickets: &coreum.OperationTypeAllocateTickets{
Number: numberOfTicketsToInit,
},
},
}, ticketsAllocationOperation)
// ********** TransactionResultEvidence / Transaction rejected **********
rejectedTxHash := genXRPLTxHash(t)
rejectedTxEvidence := coreum.XRPLTransactionResultTicketsAllocationEvidence{
XRPLTransactionResultEvidence: coreum.XRPLTransactionResultEvidence{
TxHash: rejectedTxHash,
SequenceNumber: &firstBridgeAccountSeqNumber,
TransactionResult: coreum.TransactionResultRejected,
},
Tickets: nil,
}
// try to send with not existing sequence
invalidRejectedTxEvidence := rejectedTxEvidence
invalidRejectedTxEvidence.SequenceNumber = lo.ToPtr(uint32(999))
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, invalidRejectedTxEvidence)
require.True(t, coreum.IsPendingOperationNotFoundError(err), err)
// try to send with not existing ticket
invalidRejectedTxEvidence = rejectedTxEvidence
invalidRejectedTxEvidence.SequenceNumber = nil
invalidRejectedTxEvidence.TicketNumber = lo.ToPtr(uint32(999))
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, invalidRejectedTxEvidence)
require.True(t, coreum.IsPendingOperationNotFoundError(err), err)
// try to send from not relayer
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, owner, rejectedTxEvidence)
require.True(t, coreum.IsUnauthorizedSenderError(err), err)
// send evidence from first relayer
txRes, err := contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, rejectedTxEvidence)
require.NoError(t, err)
thresholdReached, err := event.FindStringEventAttribute(txRes.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)
require.Equal(t, strconv.FormatBool(false), thresholdReached)
// try to send evidence from second relayer one more time
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, rejectedTxEvidence)
require.True(t, coreum.IsEvidenceAlreadyProvidedError(err), err)
// send evidence from second relayer
txRes, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[1].CoreumAddress, rejectedTxEvidence)
require.NoError(t, err)
thresholdReached, err = event.FindStringEventAttribute(txRes.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)
require.Equal(t, strconv.FormatBool(true), thresholdReached)
// try to send the evidence one more time
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, rejectedTxEvidence)
require.True(t, coreum.IsOperationAlreadyExecutedError(err), err)
pendingOperations, err = contractClient.GetPendingOperations(ctx)
require.NoError(t, err)
require.Len(t, pendingOperations, 0)
availableTickets, err = contractClient.GetAvailableTickets(ctx)
require.NoError(t, err)
require.Empty(t, availableTickets)
// ********** TransactionResultEvidence / Transaction invalid **********
invalidBridgeAccountSeqNumber := uint32(1000)
_, err = contractClient.RecoverTickets(ctx, owner, invalidBridgeAccountSeqNumber, &numberOfTicketsToInit)
require.NoError(t, err)
invalidTxEvidence := coreum.XRPLTransactionResultTicketsAllocationEvidence{
XRPLTransactionResultEvidence: coreum.XRPLTransactionResultEvidence{
TxHash: "",
SequenceNumber: &invalidBridgeAccountSeqNumber,
TransactionResult: coreum.TransactionResultInvalid,
},
Tickets: nil,
}
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, invalidTxEvidence)
require.NoError(t, err)
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[1].CoreumAddress, invalidTxEvidence)
require.NoError(t, err)
pendingOperations, err = contractClient.GetPendingOperations(ctx)
require.NoError(t, err)
require.Len(t, pendingOperations, 0)
availableTickets, err = contractClient.GetAvailableTickets(ctx)
require.NoError(t, err)
require.Empty(t, availableTickets)
// try to use the same sequence number (it should be possible)
_, err = contractClient.RecoverTickets(ctx, owner, invalidBridgeAccountSeqNumber, &numberOfTicketsToInit)
require.NoError(t, err)
// reject one more time
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, invalidTxEvidence)
require.NoError(t, err)
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[1].CoreumAddress, invalidTxEvidence)
require.NoError(t, err)
pendingOperations, err = contractClient.GetPendingOperations(ctx)
require.NoError(t, err)
require.Len(t, pendingOperations, 0)
// ********** Ticket allocation after previous failure / Recovery **********
secondBridgeAccountSeqNumber := uint32(2)
// start the process one more time
_, err = contractClient.RecoverTickets(ctx, owner, secondBridgeAccountSeqNumber, &numberOfTicketsToInit)
require.NoError(t, err)
// ********** TransactionResultEvidence / Transaction accepted **********
// we can omit the signing here since it is required only for the tx submission.
acceptedTxEvidence := coreum.XRPLTransactionResultTicketsAllocationEvidence{
XRPLTransactionResultEvidence: coreum.XRPLTransactionResultEvidence{
TxHash: genXRPLTxHash(t),
SequenceNumber: &secondBridgeAccountSeqNumber,
TransactionResult: coreum.TransactionResultAccepted,
},
Tickets: []uint32{3, 5, 6, 7},
}
// try to send with already used txHash
invalidAcceptedTxEvidence := acceptedTxEvidence
invalidAcceptedTxEvidence.TxHash = rejectedTxHash
_, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, invalidAcceptedTxEvidence)
require.True(t, coreum.IsOperationAlreadyExecutedError(err), err)
// send evidence from first relayer
txRes, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[0].CoreumAddress, acceptedTxEvidence)
require.NoError(t, err)
thresholdReached, err = event.FindStringEventAttribute(txRes.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)
require.Equal(t, strconv.FormatBool(false), thresholdReached)
// send evidence from second relayer
txRes, err = contractClient.SendXRPLTicketsAllocationTransactionResultEvidence(ctx, relayers[1].CoreumAddress, acceptedTxEvidence)
require.NoError(t, err)
thresholdReached, err = event.FindStringEventAttribute(txRes.Events, wasmtypes.ModuleName, eventAttributeThresholdReached)
require.NoError(t, err)