-
Notifications
You must be signed in to change notification settings - Fork 28
/
wasm_test.go
2453 lines (2056 loc) · 73.8 KB
/
wasm_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
package modules
import (
"context"
_ "embed"
"encoding/base64"
"encoding/json"
"math/rand"
"testing"
"time"
sdkmath "cosmossdk.io/math"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
cosmoserrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
authztypes "github.com/cosmos/cosmos-sdk/x/authz"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
govtypesv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
nfttypes "github.com/cosmos/cosmos-sdk/x/nft"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
integrationtests "github.com/CoreumFoundation/coreum/v3/integration-tests"
moduleswasm "github.com/CoreumFoundation/coreum/v3/integration-tests/contracts/modules"
"github.com/CoreumFoundation/coreum/v3/pkg/client"
"github.com/CoreumFoundation/coreum/v3/testutil/integration"
assetfttypes "github.com/CoreumFoundation/coreum/v3/x/asset/ft/types"
assetnfttypes "github.com/CoreumFoundation/coreum/v3/x/asset/nft/types"
)
// authz models
type authz struct {
Granter string `json:"granter"`
}
//nolint:tagliatelle
type authzNFTOfferRequest struct {
ClassID string `json:"class_id"`
ID string `json:"id"`
Price sdk.Coin `json:"price"`
}
//nolint:tagliatelle
type authzAcceptNFTOfferRequest struct {
ClassID string `json:"class_id"`
ID string `json:"id"`
}
type authzNFTMethod string
const (
offerNft authzNFTMethod = "offer_nft"
acceptNftOffer authzNFTMethod = "accept_nft_offer"
)
// fungible token wasm models
//
//nolint:tagliatelle
type issueFTRequest struct {
Symbol string `json:"symbol"`
Subunit string `json:"subunit"`
Precision uint32 `json:"precision"`
InitialAmount string `json:"initial_amount"`
Description string `json:"description"`
Features []assetfttypes.Feature `json:"features"`
BurnRate string `json:"burn_rate"`
SendCommissionRate string `json:"send_commission_rate"`
URI string `json:"uri"`
URIHash string `json:"uri_hash"`
}
type amountBodyFTRequest struct {
Amount string `json:"amount"`
}
type amountRecipientBodyFTRequest struct {
Amount string `json:"amount"`
Recipient string `json:"recipient"`
}
type accountAmountBodyFTRequest struct {
Account string `json:"account"`
Amount string `json:"amount"`
}
type issuerBodyFTRequest struct {
Issuer string `json:"issuer"`
}
type accountBodyFTRequest struct {
Account string `json:"account"`
}
type ftMethod string
const (
// tx.
ftMethodMint ftMethod = "mint"
ftMethodBurn ftMethod = "burn"
ftMethodFreeze ftMethod = "freeze"
ftMethodUnfreeze ftMethod = "unfreeze"
ftMethodSetFrozen ftMethod = "set_frozen"
ftMethodGloballyFreeze ftMethod = "globally_freeze"
ftMethodGloballyUnfreeze ftMethod = "globally_unfreeze"
ftMethodSetWhitelistedLimit ftMethod = "set_whitelisted_limit"
// query.
ftMethodParams ftMethod = "params"
ftMethodTokens ftMethod = "tokens"
ftMethodToken ftMethod = "token"
ftMethodBalance ftMethod = "balance"
ftMethodFrozenBalance ftMethod = "frozen_balance"
ftMethodWhitelistedBalance ftMethod = "whitelisted_balance"
ftMethodFrozenBalances ftMethod = "frozen_balances"
ftMethodWhitelistedBalances ftMethod = "whitelisted_balances"
)
// TestWASMBankSendContract runs a contract deployment flow and tests that the contract is able to use Bank module
// to disperse the native coins.
func TestWASMBankSendContract(t *testing.T) {
t.Parallel()
ctx, chain := integrationtests.NewCoreumTestingContext(t)
admin := chain.GenAccount()
nativeDenom := chain.ChainSettings.Denom
requireT := require.New(t)
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(admin, chain.NewCoin(sdkmath.NewInt(5000000000))),
)
clientCtx := chain.ClientContext
txf := chain.TxFactory().
WithSimulateAndExecute(true)
bankClient := banktypes.NewQueryClient(clientCtx)
// deployWASMContract and init contract with the initial coins amount
contractAddr, _, err := chain.Wasm.DeployAndInstantiateWASMContract(
ctx,
txf,
admin,
moduleswasm.BankSendWASM,
integration.InstantiateConfig{
AccessType: wasmtypes.AccessTypeUnspecified,
Payload: moduleswasm.EmptyPayload,
Amount: chain.NewCoin(sdkmath.NewInt(10000)),
Label: "bank_send",
},
)
requireT.NoError(err)
// send additional coins to contract directly
sdkContractAddress, err := sdk.AccAddressFromBech32(contractAddr)
requireT.NoError(err)
msg := &banktypes.MsgSend{
FromAddress: admin.String(),
ToAddress: sdkContractAddress.String(),
Amount: sdk.NewCoins(chain.NewCoin(sdkmath.NewInt(5000))),
}
_, err = client.BroadcastTx(ctx, clientCtx.WithFromAddress(admin), txf, msg)
requireT.NoError(err)
// get the contract balance and check total
contractBalance, err := bankClient.Balance(ctx,
&banktypes.QueryBalanceRequest{
Address: contractAddr,
Denom: nativeDenom,
})
requireT.NoError(err)
requireT.NotNil(contractBalance.Balance)
requireT.Equal(sdk.NewInt64Coin(nativeDenom, 15000).String(), contractBalance.Balance.String())
recipient := chain.GenAccount()
// try to withdraw more than the admin has
_, err = chain.Wasm.ExecuteWASMContract(
ctx,
txf.
WithSimulateAndExecute(false).
// the gas here is to try to execute the tx and don't fail on the gas estimation
WithGas(uint64(getFeemodelParams(ctx, t, chain.ClientContext).MaxBlockGas)),
admin,
contractAddr,
moduleswasm.BankSendExecuteWithdrawRequest(sdk.NewInt64Coin(nativeDenom, 16000), recipient),
sdk.Coin{})
requireT.True(cosmoserrors.ErrInsufficientFunds.Is(err))
// send coin from the contract to test wallet
_, err = chain.Wasm.ExecuteWASMContract(
ctx,
txf,
admin,
contractAddr,
moduleswasm.BankSendExecuteWithdrawRequest(sdk.NewInt64Coin(nativeDenom, 5000), recipient),
sdk.Coin{},
)
requireT.NoError(err)
// check contract and wallet balances
contractBalance, err = bankClient.Balance(ctx,
&banktypes.QueryBalanceRequest{
Address: contractAddr,
Denom: nativeDenom,
})
requireT.NoError(err)
requireT.NotNil(contractBalance.Balance)
requireT.Equal(sdk.NewInt64Coin(nativeDenom, 10000).String(), contractBalance.Balance.String())
recipientBalance, err := bankClient.Balance(ctx,
&banktypes.QueryBalanceRequest{
Address: recipient.String(),
Denom: nativeDenom,
})
requireT.NoError(err)
requireT.NotNil(recipientBalance.Balance)
requireT.Equal(sdk.NewInt64Coin(nativeDenom, 5000).String(), recipientBalance.Balance.String())
}
// TestWASMGasBankSendAndBankSend checks that a message containing a deterministic and a
// non-deterministic transaction takes gas within appropriate limits.
func TestWASMGasBankSendAndBankSend(t *testing.T) {
t.Parallel()
ctx, chain := integrationtests.NewCoreumTestingContext(t)
requireT := require.New(t)
admin := chain.GenAccount()
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(admin, chain.NewCoin(sdkmath.NewInt(5000000000))),
)
// deployWASMContract and init contract with the initial coins amount
clientCtx := chain.ClientContext
txf := chain.TxFactory().
WithSimulateAndExecute(true)
contractAddr, _, err := chain.Wasm.DeployAndInstantiateWASMContract(
ctx,
txf,
admin,
moduleswasm.BankSendWASM,
integration.InstantiateConfig{
AccessType: wasmtypes.AccessTypeUnspecified,
Payload: moduleswasm.EmptyPayload,
Amount: chain.NewCoin(sdkmath.NewInt(10000)),
Label: "bank_send",
},
)
requireT.NoError(err)
// Send tokens
recipient := chain.GenAccount()
wasmBankSend := &wasmtypes.MsgExecuteContract{
Sender: admin.String(),
Contract: contractAddr,
Msg: wasmtypes.RawContractMessage(moduleswasm.BankSendExecuteWithdrawRequest(sdk.NewInt64Coin(chain.ChainSettings.Denom, 5000), recipient)),
Funds: sdk.Coins{},
}
bankSend := &banktypes.MsgSend{
FromAddress: admin.String(),
ToAddress: recipient.String(),
Amount: sdk.NewCoins(sdk.NewCoin(chain.ChainSettings.Denom, sdkmath.NewInt(1000))),
}
minGasExpected := chain.GasLimitByMsgs(&banktypes.MsgSend{}, &banktypes.MsgSend{})
maxGasExpected := minGasExpected * 10
txf = chain.ChainContext.TxFactory().WithGas(maxGasExpected)
result, err := client.BroadcastTx(ctx, clientCtx.WithFromAddress(admin), txf, wasmBankSend, bankSend)
require.NoError(t, err)
assert.Greater(t, uint64(result.GasUsed), minGasExpected)
assert.Less(t, uint64(result.GasUsed), maxGasExpected)
}
// TestWASMPinningAndUnpinningSmartContractUsingGovernance deploys simple smart contract, verifies that it works properly and then tests that
// pinning and unpinning through proposals works correctly. We also verify that pinned smart contract consumes less gas.
func TestWASMPinningAndUnpinningSmartContractUsingGovernance(t *testing.T) {
t.Parallel()
ctx, chain := integrationtests.NewCoreumTestingContext(t)
admin := chain.GenAccount()
proposer := chain.GenAccount()
requireT := require.New(t)
proposerBalance, err := chain.Governance.ComputeProposerBalance(ctx)
requireT.NoError(err)
proposerBalance.Amount = proposerBalance.Amount.MulRaw(2)
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(admin, chain.NewCoin(sdkmath.NewInt(5000000000))),
integration.NewFundedAccount(proposer, proposerBalance),
)
// instantiateWASMContract the contract and set the initial counter state.
initialPayload, err := json.Marshal(moduleswasm.SimpleState{
Count: 1337,
})
requireT.NoError(err)
txf := chain.TxFactory().
WithSimulateAndExecute(true)
contractAddr, codeID, err := chain.Wasm.DeployAndInstantiateWASMContract(
ctx,
txf,
admin,
moduleswasm.SimpleStateWASM,
integration.InstantiateConfig{
AccessType: wasmtypes.AccessTypeUnspecified,
Payload: initialPayload,
Label: "simple_state",
},
)
requireT.NoError(err)
// get the current counter state
getCountPayload, err := moduleswasm.MethodToEmptyBodyPayload(moduleswasm.SimpleGetCount)
requireT.NoError(err)
queryOut, err := chain.Wasm.QueryWASMContract(ctx, contractAddr, getCountPayload)
requireT.NoError(err)
var response moduleswasm.SimpleState
requireT.NoError(json.Unmarshal(queryOut, &response))
requireT.Equal(1337, response.Count)
// execute contract to increment the count
gasUsedBeforePinning := moduleswasm.IncrementSimpleStateAndVerify(ctx, txf, admin, chain, contractAddr, requireT, 1338)
// verify that smart contract is not pinned
requireT.False(chain.Wasm.IsWASMContractPinned(ctx, codeID))
// pin smart contract
proposalMsg, err := chain.Governance.NewMsgSubmitProposal(
ctx,
proposer,
[]sdk.Msg{
&wasmtypes.MsgPinCodes{
Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(),
CodeIDs: []uint64{codeID},
},
},
"",
"Pin smart contract",
"Testing smart contract pinning",
)
requireT.NoError(err)
proposalID, err := chain.Governance.Propose(ctx, t, proposalMsg)
requireT.NoError(err)
proposal, err := chain.Governance.GetProposal(ctx, proposalID)
requireT.NoError(err)
requireT.Equal(govtypesv1.StatusVotingPeriod, proposal.Status)
err = chain.Governance.VoteAll(ctx, govtypesv1.OptionYes, proposal.Id)
requireT.NoError(err)
// Wait for proposal result.
finalStatus, err := chain.Governance.WaitForVotingToFinalize(ctx, proposalID)
requireT.NoError(err)
requireT.Equal(govtypesv1.StatusPassed, finalStatus)
requireT.True(chain.Wasm.IsWASMContractPinned(ctx, codeID))
gasUsedAfterPinning := moduleswasm.IncrementSimpleStateAndVerify(ctx, txf, admin, chain, contractAddr, requireT, 1339)
// unpin smart contract
proposalMsg, err = chain.Governance.NewMsgSubmitProposal(
ctx,
proposer,
[]sdk.Msg{
&wasmtypes.MsgUnpinCodes{
Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(),
CodeIDs: []uint64{codeID},
},
},
"",
"Unpin smart contract",
"Testing smart contract unpinning",
)
requireT.NoError(err)
requireT.NoError(err)
proposalID, err = chain.Governance.Propose(ctx, t, proposalMsg)
requireT.NoError(err)
proposal, err = chain.Governance.GetProposal(ctx, proposalID)
requireT.NoError(err)
requireT.Equal(govtypesv1.StatusVotingPeriod, proposal.Status)
err = chain.Governance.VoteAll(ctx, govtypesv1.OptionYes, proposal.Id)
requireT.NoError(err)
finalStatus, err = chain.Governance.WaitForVotingToFinalize(ctx, proposalID)
requireT.NoError(err)
requireT.Equal(govtypesv1.StatusPassed, finalStatus)
requireT.False(chain.Wasm.IsWASMContractPinned(ctx, codeID))
gasUsedAfterUnpinning := moduleswasm.IncrementSimpleStateAndVerify(ctx, txf, admin, chain, contractAddr, requireT, 1340)
t.Logf("Gas saved on pinned contract, gasBeforePinning:%d, gasAfterPinning:%d", gasUsedBeforePinning, gasUsedAfterPinning)
assertT := assert.New(t)
assertT.Less(gasUsedAfterPinning, gasUsedBeforePinning)
assertT.Greater(gasUsedAfterUnpinning, gasUsedAfterPinning)
}
// TestWASMContractUpgrade deploys simple state smart contract do its upgrade and upgrades/migrates it.
func TestWASMContractUpgrade(t *testing.T) {
t.Parallel()
ctx, chain := integrationtests.NewCoreumTestingContext(t)
admin := chain.GenAccount()
noneAdmin := chain.GenAccount()
requireT := require.New(t)
wasmClient := wasmtypes.NewQueryClient(chain.ClientContext)
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(admin, chain.NewCoin(sdkmath.NewInt(5000000))),
integration.NewFundedAccount(noneAdmin, chain.NewCoin(sdkmath.NewInt(5000000))),
)
// instantiateWASMContract the contract and set the initial counter state.
initialPayload, err := json.Marshal(moduleswasm.SimpleState{
Count: 787,
})
requireT.NoError(err)
txf := chain.TxFactory().
WithSimulateAndExecute(true)
contractAddr, _, err := chain.Wasm.DeployAndInstantiateWASMContract(
ctx,
txf,
admin,
moduleswasm.SimpleStateWASM,
integration.InstantiateConfig{
Admin: admin,
AccessType: wasmtypes.AccessTypeUnspecified,
Payload: initialPayload,
Label: "simple_state_before_upgrade",
},
)
requireT.NoError(err)
// get the current counter state before migration.
getCountPayload, err := moduleswasm.MethodToEmptyBodyPayload(moduleswasm.SimpleGetCount)
requireT.NoError(err)
queryOut, err := chain.Wasm.QueryWASMContract(ctx, contractAddr, getCountPayload)
requireT.NoError(err)
var response moduleswasm.SimpleState
requireT.NoError(json.Unmarshal(queryOut, &response))
requireT.Equal(787, response.Count)
// execute the migration.
// deploy new version of the contract
newCodeID, err := chain.Wasm.DeployWASMContract(
ctx,
txf,
admin,
moduleswasm.SimpleStateWASM,
)
requireT.NoError(err)
// prepare migration payload.
migrationPayload, err := json.Marshal(moduleswasm.SimpleState{
Count: 999,
})
requireT.NoError(err)
// try to migrate from non-admin.
err = chain.Wasm.MigrateWASMContract(ctx, txf, noneAdmin, contractAddr, newCodeID, migrationPayload)
requireT.Error(err)
requireT.Contains(err.Error(), "unauthorized")
// migrate from admin.
requireT.NoError(chain.Wasm.MigrateWASMContract(ctx, txf, admin, contractAddr, newCodeID, migrationPayload))
// check state after the migration.
queryOut, err = chain.Wasm.QueryWASMContract(ctx, contractAddr, getCountPayload)
requireT.NoError(err)
requireT.NoError(json.Unmarshal(queryOut, &response))
requireT.Equal(999, response.Count)
// check that the contract works after the migration.
_ = moduleswasm.IncrementSimpleStateAndVerify(ctx, txf, admin, chain, contractAddr, requireT, 1000)
contractInfoRes, err := wasmClient.ContractInfo(ctx, &wasmtypes.QueryContractInfoRequest{
Address: contractAddr,
})
requireT.NoError(err)
requireT.Equal(newCodeID, contractInfoRes.CodeID)
}
// TestUpdateAndClearAdminOfContract runs MsgUpdateAdmin and MsgClearAdmin tx types.
func TestUpdateAndClearAdminOfContract(t *testing.T) {
t.Parallel()
ctx, chain := integrationtests.NewCoreumTestingContext(t)
admin := chain.GenAccount()
newAdmin := chain.GenAccount()
requireT := require.New(t)
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(admin, chain.NewCoin(sdkmath.NewInt(5000000000))),
)
chain.FundAccountWithOptions(ctx, t, newAdmin, integration.BalancesOptions{
Messages: []sdk.Msg{
&wasmtypes.MsgClearAdmin{},
},
})
wasmClient := wasmtypes.NewQueryClient(chain.ClientContext)
// deployWASMContract and init contract with the initial coins amount
contractAddr, _, err := chain.Wasm.DeployAndInstantiateWASMContract(
ctx,
chain.TxFactory().WithSimulateAndExecute(true),
admin,
moduleswasm.BankSendWASM,
integration.InstantiateConfig{
AccessType: wasmtypes.AccessTypeUnspecified,
Admin: admin,
Payload: moduleswasm.EmptyPayload,
Amount: chain.NewCoin(sdkmath.NewInt(10000)),
Label: "bank_send",
},
)
requireT.NoError(err)
// query contract info
contractInfo, err := wasmClient.ContractInfo(ctx, &wasmtypes.QueryContractInfoRequest{
Address: contractAddr,
})
requireT.NoError(err)
requireT.EqualValues(admin.String(), contractInfo.Admin)
// update admin
msgUpdateAdmin := &wasmtypes.MsgUpdateAdmin{
Sender: admin.String(),
NewAdmin: newAdmin.String(),
Contract: contractAddr,
}
res, err := client.BroadcastTx(
ctx,
chain.ClientContext.WithFromAddress(admin),
chain.TxFactory().WithSimulateAndExecute(true).WithGas(chain.GasLimitByMsgs(msgUpdateAdmin)),
msgUpdateAdmin,
)
requireT.NoError(err)
requireT.NotNil(res)
contractInfo, err = wasmClient.ContractInfo(ctx, &wasmtypes.QueryContractInfoRequest{
Address: contractAddr,
})
requireT.NoError(err)
requireT.EqualValues(newAdmin.String(), contractInfo.Admin)
requireT.EqualValues(chain.GasLimitByMsgs(msgUpdateAdmin), res.GasUsed)
// clear admin
msgClearAdmin := &wasmtypes.MsgClearAdmin{
Sender: newAdmin.String(),
Contract: contractAddr,
}
res, err = client.BroadcastTx(
ctx,
chain.ClientContext.WithFromAddress(newAdmin),
chain.TxFactory().WithSimulateAndExecute(true),
msgClearAdmin,
)
requireT.NoError(err)
requireT.NotNil(res)
contractInfo, err = wasmClient.ContractInfo(ctx, &wasmtypes.QueryContractInfoRequest{
Address: contractAddr,
})
requireT.NoError(err)
requireT.EqualValues("", contractInfo.Admin)
requireT.EqualValues(chain.GasLimitByMsgs(msgClearAdmin), res.GasUsed)
}
// TestWASMAuthzContract runs a contract deployment flow and tests that the contract is able to use the Authz module
// to send native coins in place of another one.
func TestWASMAuthzContract(t *testing.T) {
t.Parallel()
ctx, chain := integrationtests.NewCoreumTestingContext(t)
requireT := require.New(t)
granter := chain.GenAccount()
receiver := chain.GenAccount()
authzClient := authztypes.NewQueryClient(chain.ClientContext)
bankClient := banktypes.NewQueryClient(chain.ClientContext)
nftClient := nfttypes.NewQueryClient(chain.ClientContext)
totalAmountToSend := sdkmath.NewInt(2_000)
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(granter, chain.NewCoin(sdkmath.NewInt(5000000000))),
)
// deployWASMContract and init contract with the granter.
initialPayload, err := json.Marshal(authz{
Granter: granter.String(),
})
requireT.NoError(err)
contractAddr, _, err := chain.Wasm.DeployAndInstantiateWASMContract(
ctx,
chain.TxFactory().WithSimulateAndExecute(true),
granter,
moduleswasm.AuthzWASM,
integration.InstantiateConfig{
AccessType: wasmtypes.AccessTypeUnspecified,
Payload: initialPayload,
Label: "authz",
},
)
requireT.NoError(err)
// ********** Test sending funds with Authz **********
// grant the bank send authorization
grantMsg, err := authztypes.NewMsgGrant(
granter,
sdk.MustAccAddressFromBech32(contractAddr),
authztypes.NewGenericAuthorization(sdk.MsgTypeURL(&banktypes.MsgSend{})),
lo.ToPtr(time.Now().Add(time.Minute)),
)
require.NoError(t, err)
txResult, err := client.BroadcastTx(
ctx,
chain.ClientContext.WithFromAddress(granter),
chain.TxFactory().WithGas(chain.GasLimitByMsgs(grantMsg)),
grantMsg,
)
requireT.NoError(err)
requireT.Equal(chain.GasLimitByMsgs(grantMsg), uint64(txResult.GasUsed))
// assert granted
gransRes, err := authzClient.Grants(ctx, &authztypes.QueryGrantsRequest{
Granter: granter.String(),
Grantee: contractAddr,
})
requireT.NoError(err)
requireT.Len(gransRes.Grants, 1)
// ********** Transfer **********
_, err = chain.Wasm.ExecuteWASMContract(
ctx,
chain.TxFactory().WithSimulateAndExecute(true),
granter,
contractAddr,
moduleswasm.AuthZExecuteTransferRequest(receiver.String(), chain.NewCoin(totalAmountToSend)),
sdk.Coin{},
)
requireT.NoError(err)
// ********** Stargate **********
msgSendAny, err := codectypes.NewAnyWithValue(&banktypes.MsgSend{
FromAddress: granter.String(),
ToAddress: receiver.String(),
Amount: sdk.NewCoins(chain.NewCoin(totalAmountToSend)),
})
requireT.NoError(err)
_, err = chain.Wasm.ExecuteWASMContract(
ctx,
chain.TxFactory().WithSimulateAndExecute(true),
granter,
contractAddr,
moduleswasm.AuthZExecuteStargateRequest(&authztypes.MsgExec{
Grantee: contractAddr,
Msgs: []*codectypes.Any{
msgSendAny,
},
}),
sdk.Coin{},
)
requireT.NoError(err)
// check receiver balance
receiverBalancesRes, err := bankClient.AllBalances(ctx, &banktypes.QueryAllBalancesRequest{
Address: receiver.String(),
})
requireT.NoError(err)
requireT.Equal(chain.NewCoin(totalAmountToSend.MulRaw(2)).String(), receiverBalancesRes.Balances.String())
// ********** Test trading an NFT for an AssetFT with Authz **********
// Issue and mind an NFT to the sender (will offer it)
issueMsg := &assetnfttypes.MsgIssueClass{
Issuer: granter.String(),
Symbol: "NFTClassSymbol",
Features: []assetnfttypes.ClassFeature{},
}
_, err = client.BroadcastTx(
ctx,
chain.ClientContext.WithFromAddress(granter),
chain.TxFactory().WithGas(chain.GasLimitByMsgs(issueMsg)),
issueMsg,
)
requireT.NoError(err)
classID := assetnfttypes.BuildClassID(issueMsg.Symbol, granter)
mintMsg := &assetnfttypes.MsgMint{
Sender: granter.String(),
Recipient: granter.String(),
ID: "id-1",
ClassID: classID,
}
_, err = client.BroadcastTx(
ctx,
chain.ClientContext.WithFromAddress(granter),
chain.TxFactory().WithGas(chain.GasLimitByMsgs(mintMsg)),
mintMsg,
)
requireT.NoError(err)
// Issue an AssetFT that will be used to buy the NFT
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(receiver, chain.NewCoin(sdkmath.NewInt(5000000000))),
)
issueAssetFTMsg := &assetfttypes.MsgIssue{
Issuer: receiver.String(),
Symbol: "ABC",
Subunit: "uabc",
Precision: 6,
Description: "ABC Description",
InitialAmount: sdkmath.NewInt(100000),
Features: []assetfttypes.Feature{},
URI: "https://my-class-meta.valid/1",
URIHash: "content-hash",
}
_, err = client.BroadcastTx(
ctx,
chain.ClientContext.WithFromAddress(receiver),
chain.TxFactory().WithGas(chain.GasLimitByMsgs(issueAssetFTMsg)),
issueAssetFTMsg,
)
requireT.NoError(err)
denom := assetfttypes.BuildDenom(issueAssetFTMsg.Subunit, receiver)
// grant the nft transfer authorization to the contract
grantMsg, err = authztypes.NewMsgGrant(
granter,
sdk.MustAccAddressFromBech32(contractAddr),
assetnfttypes.NewSendAuthorization([]assetnfttypes.NFTIdentifier{
{ClassId: classID, Id: "id-1"},
}),
lo.ToPtr(time.Now().Add(time.Minute)),
)
requireT.NoError(err)
_, err = client.BroadcastTx(
ctx,
chain.ClientContext.WithFromAddress(granter),
chain.TxFactory().WithGas(chain.GasLimitByMsgs(grantMsg)),
grantMsg,
)
requireT.NoError(err)
// assert granted
gransRes, err = authzClient.Grants(ctx, &authztypes.QueryGrantsRequest{
Granter: granter.String(),
Grantee: contractAddr,
})
requireT.NoError(err)
requireT.Len(gransRes.Grants, 2)
updatedGrant := assetnfttypes.SendAuthorization{}
chain.ClientContext.Codec().MustUnmarshal(gransRes.Grants[1].Authorization.Value, &updatedGrant)
requireT.ElementsMatch([]assetnfttypes.NFTIdentifier{
{ClassId: classID, Id: "id-1"},
}, updatedGrant.Nfts)
// Make the offer of the NFT for the AssetFT
nftOfferPayload, err := json.Marshal(map[authzNFTMethod]authzNFTOfferRequest{
offerNft: {
ClassID: classID,
ID: "id-1",
Price: sdk.NewCoin(denom, sdkmath.NewInt(10000)),
},
})
requireT.NoError(err)
_, err = chain.Wasm.ExecuteWASMContract(ctx, chain.TxFactory().WithSimulateAndExecute(true), granter, contractAddr, nftOfferPayload, sdk.Coin{})
requireT.NoError(err)
ownerResp, err := nftClient.Owner(ctx, &nfttypes.QueryOwnerRequest{
ClassId: classID,
Id: "id-1",
})
requireT.NoError(err)
requireT.EqualValues(ownerResp.Owner, contractAddr)
// Accept the offer
acceptNftOfferPayload, err := json.Marshal(map[authzNFTMethod]authzAcceptNFTOfferRequest{
acceptNftOffer: {
ClassID: classID,
ID: "id-1",
},
})
requireT.NoError(err)
_, err = chain.Wasm.ExecuteWASMContract(ctx, chain.TxFactory().WithSimulateAndExecute(true), receiver, contractAddr, acceptNftOfferPayload, sdk.Coin{Denom: denom, Amount: sdkmath.NewInt(10000)})
requireT.NoError(err)
balanceRes, err := bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: granter.String(),
Denom: denom,
})
requireT.NoError(err)
requireT.Equal("10000", balanceRes.Balance.Amount.String())
ownerResp, err = nftClient.Owner(ctx, &nfttypes.QueryOwnerRequest{
ClassId: classID,
Id: "id-1",
})
requireT.NoError(err)
requireT.EqualValues(ownerResp.Owner, receiver.String())
}
// TestWASMFungibleTokenInContract verifies that smart contract is able to execute all fungible token message and core queries.
func TestWASMFungibleTokenInContract(t *testing.T) {
t.Parallel()
ctx, chain := integrationtests.NewCoreumTestingContext(t)
admin := chain.GenAccount()
recipient1 := chain.GenAccount()
recipient2 := chain.GenAccount()
requireT := require.New(t)
chain.Faucet.FundAccounts(ctx, t,
integration.NewFundedAccount(admin, chain.NewCoin(sdkmath.NewInt(5000000000))),
)
clientCtx := chain.ClientContext
txf := chain.TxFactory().
WithSimulateAndExecute(true)
bankClient := banktypes.NewQueryClient(clientCtx)
ftClient := assetfttypes.NewQueryClient(clientCtx)
// ********** Issuance **********
burnRate := sdk.MustNewDecFromStr("0.1")
sendCommissionRate := sdk.MustNewDecFromStr("0.2")
issuanceAmount := sdkmath.NewInt(10_000)
issuanceReq := issueFTRequest{
Symbol: "symbol",
Subunit: "subunit",
Precision: 6,
InitialAmount: issuanceAmount.String(),
Description: "my wasm fungible token",
Features: []assetfttypes.Feature{
assetfttypes.Feature_minting,
assetfttypes.Feature_burning,
assetfttypes.Feature_freezing,
assetfttypes.Feature_whitelisting,
},
BurnRate: burnRate.String(),
SendCommissionRate: sendCommissionRate.String(),
URI: "https://example.com",
URIHash: "1234567890abcdef",
}
issuerFTInstantiatePayload, err := json.Marshal(issuanceReq)
requireT.NoError(err)
// instantiate new contract
contractAddr, _, err := chain.Wasm.DeployAndInstantiateWASMContract(
ctx,
txf,
admin,
moduleswasm.FTWASM,
integration.InstantiateConfig{
// we add the initial amount to let the contract issue the token on behalf of it
Amount: chain.QueryAssetFTParams(ctx, t).IssueFee,
AccessType: wasmtypes.AccessTypeUnspecified,
Payload: issuerFTInstantiatePayload,
Label: "fungible_token",
},
)
requireT.NoError(err)
denom := assetfttypes.BuildDenom(issuanceReq.Subunit, sdk.MustAccAddressFromBech32(contractAddr))
tokenRes, err := ftClient.Token(ctx, &assetfttypes.QueryTokenRequest{Denom: denom})
requireT.NoError(err)
expectedToken := assetfttypes.Token{
Denom: denom,
Issuer: contractAddr,
Symbol: issuanceReq.Symbol,
Subunit: issuanceReq.Subunit,
Precision: issuanceReq.Precision,
Description: issuanceReq.Description,
GloballyFrozen: false,
Features: []assetfttypes.Feature{
assetfttypes.Feature_minting,
assetfttypes.Feature_burning,
assetfttypes.Feature_freezing,
assetfttypes.Feature_whitelisting,
},
BurnRate: burnRate,
SendCommissionRate: sendCommissionRate,
Version: assetfttypes.CurrentTokenVersion, // test should work with any token version
URI: issuanceReq.URI,
URIHash: issuanceReq.URIHash,
}
requireT.Equal(
expectedToken, tokenRes.Token,
)
balanceRes, err := bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: contractAddr,
Denom: denom,
})
requireT.NoError(err)
requireT.Equal(issuanceReq.InitialAmount, balanceRes.Balance.Amount.String())
txf = txf.WithSimulateAndExecute(true)
// ********** Transactions **********
// ********** Mint **********
amountToMint := sdkmath.NewInt(500)
mintPayload, err := json.Marshal(map[ftMethod]amountBodyFTRequest{
ftMethodMint: {
Amount: amountToMint.String(),
},
})
requireT.NoError(err)
_, err = chain.Wasm.ExecuteWASMContract(ctx, txf, admin, contractAddr, mintPayload, sdk.Coin{})
requireT.NoError(err)
balanceRes, err = bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{
Address: contractAddr,
Denom: denom,
})
requireT.NoError(err)
newAmount := issuanceAmount.Add(amountToMint)
requireT.Equal(newAmount.String(), balanceRes.Balance.Amount.String())
// ********** Mint (sending to someone) **********
amountToMint = sdkmath.NewInt(100)
whitelistPayload, err := json.Marshal(map[ftMethod]accountAmountBodyFTRequest{
ftMethodSetWhitelistedLimit: {
Account: recipient2.String(),
Amount: amountToMint.String(),
},
})
requireT.NoError(err)
_, err = chain.Wasm.ExecuteWASMContract(ctx, txf, admin, contractAddr, whitelistPayload, sdk.Coin{})
requireT.NoError(err)
mintPayload, err = json.Marshal(map[ftMethod]amountRecipientBodyFTRequest{
ftMethodMint: {
Amount: amountToMint.String(),
Recipient: recipient2.String(),
},
})
requireT.NoError(err)
_, err = chain.Wasm.ExecuteWASMContract(ctx, txf, admin, contractAddr, mintPayload, sdk.Coin{})
requireT.NoError(err)
balanceRes, err = bankClient.Balance(ctx, &banktypes.QueryBalanceRequest{