-
Notifications
You must be signed in to change notification settings - Fork 410
/
keeper_test.go
2813 lines (2556 loc) · 99.8 KB
/
keeper_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
package keeper
import (
"bytes"
_ "embed"
"encoding/json"
"errors"
"fmt"
stdrand "math/rand"
"os"
"testing"
"time"
wasmvm "github.com/CosmWasm/wasmvm/v2"
wasmvmtypes "github.com/CosmWasm/wasmvm/v2/types"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/rand"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
fuzz "github.com/google/gofuzz"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
sdkmath "cosmossdk.io/math"
"cosmossdk.io/store"
storemetrics "cosmossdk.io/store/metrics"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/auth/vesting"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/CosmWasm/wasmd/x/wasm/keeper/testdata"
"github.com/CosmWasm/wasmd/x/wasm/keeper/wasmtesting"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
//go:embed testdata/hackatom.wasm
var hackatomWasm []byte
var AvailableCapabilities = []string{
"iterator", "staking", "stargate", "cosmwasm_1_1", "cosmwasm_1_2", "cosmwasm_1_3",
"cosmwasm_1_4", "cosmwasm_2_0", "cosmwasm_2_1", "cosmwasm_2_2",
}
func TestNewKeeper(t *testing.T) {
_, keepers := CreateTestInput(t, false, AvailableCapabilities)
require.NotNil(t, keepers.ContractKeeper)
}
func TestCreateSuccess(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
keeper := keepers.ContractKeeper
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
em := sdk.NewEventManager()
contractID, _, err := keeper.Create(ctx.WithEventManager(em), creator, hackatomWasm, nil)
require.NoError(t, err)
require.Equal(t, uint64(1), contractID)
// and verify content
storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID)
require.NoError(t, err)
require.Equal(t, hackatomWasm, storedCode)
// and events emitted
codeHash := testdata.ChecksumHackatom
exp := sdk.Events{sdk.NewEvent("store_code", sdk.NewAttribute("code_checksum", codeHash), sdk.NewAttribute("code_id", "1"))}
assert.Equal(t, exp, em.Events())
}
func TestCreateNilCreatorAddress(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
_, _, err := keepers.ContractKeeper.Create(ctx, nil, hackatomWasm, nil)
require.Error(t, err, "nil creator is not allowed")
}
func TestWasmLimits(t *testing.T) {
one := uint32(1)
cfg := types.DefaultNodeConfig()
ctx, keepers := createTestInput(t, false, AvailableCapabilities, cfg, types.VMConfig{
WasmLimits: wasmvmtypes.WasmLimits{
MaxImports: &one, // very low limit that every contract will fail
},
}, dbm.NewMemDB())
keeper := keepers.ContractKeeper
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 1))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
_, _, err := keeper.Create(ctx, creator, hackatomWasm, nil)
assert.Error(t, err)
assert.ErrorContains(t, err, "Import")
}
func TestCreateNilWasmCode(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
_, _, err := keepers.ContractKeeper.Create(ctx, creator, nil, nil)
require.Error(t, err, "nil WASM code is not allowed")
}
func TestCreateInvalidWasmCode(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
_, _, err := keepers.ContractKeeper.Create(ctx, creator, []byte("potatoes"), nil)
require.Error(t, err, "potatoes are not valid WASM code")
}
func TestCreateStoresInstantiatePermission(t *testing.T) {
var (
deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
myAddr sdk.AccAddress = bytes.Repeat([]byte{1}, types.SDKAddrLen)
)
specs := map[string]struct {
srcPermission types.AccessType
expInstConf types.AccessConfig
}{
"default": {
srcPermission: types.DefaultParams().InstantiateDefaultPermission,
expInstConf: types.AllowEverybody,
},
"everybody": {
srcPermission: types.AccessTypeEverybody,
expInstConf: types.AllowEverybody,
},
"nobody": {
srcPermission: types.AccessTypeNobody,
expInstConf: types.AllowNobody,
},
"anyAddress with matching address": {
srcPermission: types.AccessTypeAnyOfAddresses,
expInstConf: types.AccessConfig{Permission: types.AccessTypeAnyOfAddresses, Addresses: []string{myAddr.String()}},
},
}
for msg, spec := range specs {
t.Run(msg, func(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper
err := keepers.WasmKeeper.SetParams(ctx, types.Params{
CodeUploadAccess: types.AllowEverybody,
InstantiateDefaultPermission: spec.srcPermission,
})
require.NoError(t, err)
fundAccounts(t, ctx, accKeeper, bankKeeper, myAddr, deposit)
codeID, _, err := keeper.Create(ctx, myAddr, hackatomWasm, nil)
require.NoError(t, err)
codeInfo := keepers.WasmKeeper.GetCodeInfo(ctx, codeID)
require.NotNil(t, codeInfo)
assert.True(t, spec.expInstConf.Equals(codeInfo.InstantiateConfig), "got %#v", codeInfo.InstantiateConfig)
})
}
}
func TestCreateWithParamPermissions(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
otherAddr := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
specs := map[string]struct {
policy types.AuthorizationPolicy
chainUpload types.AccessConfig
expError *errorsmod.Error
}{
"default": {
policy: DefaultAuthorizationPolicy{},
chainUpload: types.DefaultUploadAccess,
},
"everybody": {
policy: DefaultAuthorizationPolicy{},
chainUpload: types.AllowEverybody,
},
"nobody": {
policy: DefaultAuthorizationPolicy{},
chainUpload: types.AllowNobody,
expError: sdkerrors.ErrUnauthorized,
},
"anyAddress with matching address": {
policy: DefaultAuthorizationPolicy{},
chainUpload: types.AccessTypeAnyOfAddresses.With(creator),
},
"anyAddress with non matching address": {
policy: DefaultAuthorizationPolicy{},
chainUpload: types.AccessTypeAnyOfAddresses.With(otherAddr),
expError: sdkerrors.ErrUnauthorized,
},
"gov: always allowed": {
policy: GovAuthorizationPolicy{},
chainUpload: types.AllowNobody,
},
}
for msg, spec := range specs {
t.Run(msg, func(t *testing.T) {
params := types.DefaultParams()
params.CodeUploadAccess = spec.chainUpload
err := keepers.WasmKeeper.SetParams(ctx, params)
require.NoError(t, err)
keeper := NewPermissionedKeeper(keepers.WasmKeeper, spec.policy)
_, _, err = keeper.Create(ctx, creator, hackatomWasm, nil)
require.True(t, spec.expError.Is(err), err)
if spec.expError != nil {
return
}
})
}
}
// ensure that the user cannot set the code instantiate permission to something more permissive
// than the default
func TestEnforceValidPermissionsOnCreate(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
keeper := keepers.WasmKeeper
contractKeeper := keepers.ContractKeeper
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
other := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
onlyCreator := types.AccessTypeAnyOfAddresses.With(creator)
onlyOther := types.AccessTypeAnyOfAddresses.With(other)
specs := map[string]struct {
defaultPermission types.AccessType
requestedPermission *types.AccessConfig
// grantedPermission is set iff no error
grantedPermission types.AccessConfig
// expError is nil iff the request is allowed
expError *errorsmod.Error
}{
"override everybody": {
defaultPermission: types.AccessTypeEverybody,
requestedPermission: &onlyCreator,
grantedPermission: onlyCreator,
},
"default to everybody": {
defaultPermission: types.AccessTypeEverybody,
requestedPermission: nil,
grantedPermission: types.AccessConfig{Permission: types.AccessTypeEverybody},
},
"explicitly set everybody": {
defaultPermission: types.AccessTypeEverybody,
requestedPermission: &types.AccessConfig{Permission: types.AccessTypeEverybody},
grantedPermission: types.AccessConfig{Permission: types.AccessTypeEverybody},
},
"cannot override nobody": {
defaultPermission: types.AccessTypeNobody,
requestedPermission: &onlyCreator,
expError: sdkerrors.ErrUnauthorized,
},
"default to nobody": {
defaultPermission: types.AccessTypeNobody,
requestedPermission: nil,
grantedPermission: types.AccessConfig{Permission: types.AccessTypeNobody},
},
"only defaults to code creator": {
defaultPermission: types.AccessTypeAnyOfAddresses,
requestedPermission: nil,
grantedPermission: onlyCreator,
},
"can explicitly set to code creator": {
defaultPermission: types.AccessTypeAnyOfAddresses,
requestedPermission: &onlyCreator,
grantedPermission: onlyCreator,
},
"cannot override which address in only": {
defaultPermission: types.AccessTypeAnyOfAddresses,
requestedPermission: &onlyOther,
expError: sdkerrors.ErrUnauthorized,
},
}
for msg, spec := range specs {
t.Run(msg, func(t *testing.T) {
params := types.DefaultParams()
params.InstantiateDefaultPermission = spec.defaultPermission
err := keeper.SetParams(ctx, params)
require.NoError(t, err)
codeID, _, err := contractKeeper.Create(ctx, creator, hackatomWasm, spec.requestedPermission)
require.True(t, spec.expError.Is(err), err)
if spec.expError == nil {
codeInfo := keeper.GetCodeInfo(ctx, codeID)
require.Equal(t, codeInfo.InstantiateConfig, spec.grantedPermission)
}
})
}
}
func TestCreateDuplicate(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
keeper := keepers.ContractKeeper
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
// create one copy
contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil)
require.NoError(t, err)
require.Equal(t, uint64(1), contractID)
// create second copy
duplicateID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil)
require.NoError(t, err)
require.Equal(t, uint64(2), duplicateID)
// and verify both content is proper
storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID)
require.NoError(t, err)
require.Equal(t, hackatomWasm, storedCode)
storedCode, err = keepers.WasmKeeper.GetByteCode(ctx, duplicateID)
require.NoError(t, err)
require.Equal(t, hackatomWasm, storedCode)
}
func TestCreateWithSimulation(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
ctx = ctx.WithBlockHeader(tmproto.Header{Height: 1}).
WithGasMeter(storetypes.NewInfiniteGasMeter())
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
// create this once in simulation mode
contractID, _, err := keepers.ContractKeeper.Create(ctx, creator, hackatomWasm, nil)
require.NoError(t, err)
require.Equal(t, uint64(1), contractID)
// then try to create it in non-simulation mode (should not fail)
ctx, keepers = CreateTestInput(t, false, AvailableCapabilities)
ctx = ctx.WithGasMeter(storetypes.NewGasMeter(10_000_000))
creator = keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
contractID, _, err = keepers.ContractKeeper.Create(ctx, creator, hackatomWasm, nil)
require.NoError(t, err)
require.Equal(t, uint64(1), contractID)
// and verify content
code, err := keepers.WasmKeeper.GetByteCode(ctx, contractID)
require.NoError(t, err)
require.Equal(t, code, hackatomWasm)
}
func TestCreateWithGzippedPayload(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
keeper := keepers.ContractKeeper
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
wasmCode, err := os.ReadFile("./testdata/hackatom.wasm.gzip")
require.NoError(t, err, "reading gzipped WASM code")
contractID, _, err := keeper.Create(ctx, creator, wasmCode, nil)
require.NoError(t, err)
require.Equal(t, uint64(1), contractID)
// and verify content
storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID)
require.NoError(t, err)
require.Equal(t, hackatomWasm, storedCode)
}
func TestCreateWithBrokenGzippedPayload(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
keeper := keepers.ContractKeeper
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
wasmCode, err := os.ReadFile("./testdata/broken_crc.gzip")
require.NoError(t, err, "reading gzipped WASM code")
gm := storetypes.NewInfiniteGasMeter()
codeID, checksum, err := keeper.Create(ctx.WithGasMeter(gm), creator, wasmCode, nil)
require.Error(t, err)
assert.Empty(t, codeID)
assert.Empty(t, checksum)
assert.GreaterOrEqual(t, gm.GasConsumed(), storetypes.Gas(121384)) // 809232 * 0.15 (default uncompress costs) = 121384
}
func TestInstantiate(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len))
keepers.Faucet.Fund(ctx, creator, deposit...)
example := StoreHackatomExampleContract(t, ctx, keepers)
initMsg := HackatomExampleInitMsg{
Verifier: RandomAccountAddress(t),
Beneficiary: RandomAccountAddress(t),
}
initMsgBz, err := json.Marshal(initMsg)
require.NoError(t, err)
gasBefore := ctx.GasMeter().GasConsumed()
em := sdk.NewEventManager()
// create with no balance is also legal
gotContractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil)
require.NoError(t, err)
require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", gotContractAddr.String())
gasAfter := ctx.GasMeter().GasConsumed()
if types.EnableGasVerification {
require.Equal(t, uint64(0x1bca5), gasAfter-gasBefore)
}
// ensure it is stored properly
info := keepers.WasmKeeper.GetContractInfo(ctx, gotContractAddr)
require.NotNil(t, info)
assert.Equal(t, creator.String(), info.Creator)
assert.Equal(t, example.CodeID, info.CodeID)
assert.Equal(t, "demo contract 1", info.Label)
exp := []types.ContractCodeHistoryEntry{{
Operation: types.ContractCodeHistoryOperationTypeInit,
CodeID: example.CodeID,
Updated: types.NewAbsoluteTxPosition(ctx),
Msg: initMsgBz,
}}
assert.Equal(t, exp, keepers.WasmKeeper.GetContractHistory(ctx, gotContractAddr))
// and events emitted
expEvt := sdk.Events{
sdk.NewEvent("instantiate",
sdk.NewAttribute("_contract_address", gotContractAddr.String()), sdk.NewAttribute("code_id", "1")),
sdk.NewEvent("wasm",
sdk.NewAttribute("_contract_address", gotContractAddr.String()), sdk.NewAttribute("Let the", "hacking begin")),
}
assert.Equal(t, expEvt, em.Events())
}
func TestInstantiateWithDeposit(t *testing.T) {
var (
bob = bytes.Repeat([]byte{1}, types.SDKAddrLen)
fred = bytes.Repeat([]byte{2}, types.SDKAddrLen)
deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100))
initMsg = mustMarshal(t, HackatomExampleInitMsg{Verifier: fred, Beneficiary: bob})
)
specs := map[string]struct {
srcActor sdk.AccAddress
expError bool
fundAddr bool
}{
"address with funds": {
srcActor: bob,
fundAddr: true,
},
"address without funds": {
srcActor: bob,
expError: true,
},
"blocked address": {
srcActor: authtypes.NewModuleAddress(authtypes.FeeCollectorName),
fundAddr: true,
expError: false,
},
}
for msg, spec := range specs {
t.Run(msg, func(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper
if spec.fundAddr {
fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200)))
}
contractID, _, err := keeper.Create(ctx, spec.srcActor, hackatomWasm, nil)
require.NoError(t, err)
// when
addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsg, "my label", deposit)
// then
if spec.expError {
require.Error(t, err)
return
}
require.NoError(t, err)
balances := bankKeeper.GetAllBalances(ctx, addr)
assert.Equal(t, deposit, balances)
})
}
}
func TestInstantiateWithPermissions(t *testing.T) {
var (
deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
myAddr = bytes.Repeat([]byte{1}, types.SDKAddrLen)
otherAddr = bytes.Repeat([]byte{2}, types.SDKAddrLen)
anyAddr = bytes.Repeat([]byte{3}, types.SDKAddrLen)
)
initMsg := HackatomExampleInitMsg{
Verifier: anyAddr,
Beneficiary: anyAddr,
}
initMsgBz, err := json.Marshal(initMsg)
require.NoError(t, err)
specs := map[string]struct {
srcPermission types.AccessConfig
srcActor sdk.AccAddress
expError *errorsmod.Error
}{
"default": {
srcPermission: types.DefaultUploadAccess,
srcActor: anyAddr,
},
"everybody": {
srcPermission: types.AllowEverybody,
srcActor: anyAddr,
},
"nobody": {
srcPermission: types.AllowNobody,
srcActor: myAddr,
expError: sdkerrors.ErrUnauthorized,
},
"anyAddress with matching address": {
srcPermission: types.AccessTypeAnyOfAddresses.With(myAddr),
srcActor: myAddr,
},
"anyAddress with non matching address": {
srcActor: myAddr,
srcPermission: types.AccessTypeAnyOfAddresses.With(otherAddr),
expError: sdkerrors.ErrUnauthorized,
},
}
for msg, spec := range specs {
t.Run(msg, func(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper
fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, deposit)
contractID, _, err := keeper.Create(ctx, myAddr, hackatomWasm, &spec.srcPermission) //nolint:gosec
require.NoError(t, err)
_, _, err = keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsgBz, "demo contract 1", nil)
assert.True(t, spec.expError.Is(err), "got %+v", err)
})
}
}
func TestInstantiateWithAccounts(t *testing.T) {
parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities)
example := StoreHackatomExampleContract(t, parentCtx, keepers)
require.Equal(t, uint64(1), example.CodeID)
initMsg := mustMarshal(t, HackatomExampleInitMsg{Verifier: RandomAccountAddress(t), Beneficiary: RandomAccountAddress(t)})
senderAddr := DeterministicAccountAddress(t, 1)
keepers.Faucet.Fund(parentCtx, senderAddr, sdk.NewInt64Coin("denom", 100000000))
myTestLabel := "testing"
mySalt := []byte(`my salt`)
contractAddr := BuildContractAddressPredictable(example.Checksum, senderAddr, mySalt, []byte{})
lastAccountNumber := keepers.AccountKeeper.GetAccount(parentCtx, senderAddr).GetAccountNumber()
specs := map[string]struct {
option Option
account sdk.AccountI
initBalance sdk.Coin
deposit sdk.Coins
expErr error
expAccount sdk.AccountI
expBalance sdk.Coins
}{
"unused BaseAccount exists": {
account: authtypes.NewBaseAccount(contractAddr, nil, 0, 0),
initBalance: sdk.NewInt64Coin("denom", 100000000),
expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq
expBalance: sdk.NewCoins(sdk.NewInt64Coin("denom", 100000000)),
},
"BaseAccount with sequence exists": {
account: authtypes.NewBaseAccount(contractAddr, nil, 0, 1),
expErr: types.ErrAccountExists,
},
"BaseAccount with pubkey exists": {
account: authtypes.NewBaseAccount(contractAddr, &ed25519.PubKey{}, 0, 0),
expErr: types.ErrAccountExists,
},
"no account existed": {
expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq,
expBalance: sdk.NewCoins(),
},
"no account existed before create with deposit": {
expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq
deposit: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_000))),
expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_000))),
},
"prunable DelayedVestingAccount gets overwritten": {
account: must(vestingtypes.NewDelayedVestingAccount(
authtypes.NewBaseAccount(contractAddr, nil, 0, 0),
sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix())),
initBalance: sdk.NewCoin("denom", sdkmath.NewInt(1_000)),
deposit: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1))),
expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created
expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1))),
},
"prunable ContinuousVestingAccount gets overwritten": {
account: must(vestingtypes.NewContinuousVestingAccount(
authtypes.NewBaseAccount(contractAddr, nil, 0, 0),
sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_000))), time.Now().Add(time.Hour).Unix(), time.Now().Add(2*time.Hour).Unix())),
initBalance: sdk.NewCoin("denom", sdkmath.NewInt(1_000)),
deposit: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1))),
expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created
expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1))),
},
// "prunable account without balance gets overwritten": { // todo : can not initialize vesting with empty balance
// account: must(vestingtypes.NewContinuousVestingAccount(
// authtypes.NewBaseAccount(contractAddr, nil, 0, 0),
// sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(0))), time.Now().Add(time.Hour).Unix(), time.Now().Add(2*time.Hour).Unix())),
// expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created
// expBalance: sdk.NewCoins(),
// },
"unknown account type is rejected with error": {
account: authtypes.NewModuleAccount(
authtypes.NewBaseAccount(contractAddr, nil, 0, 0),
"testing",
),
initBalance: sdk.NewCoin("denom", sdkmath.NewInt(1_000)),
expErr: types.ErrAccountExists,
},
"with option used to set non default type to accept list": {
option: WithAcceptedAccountTypesOnContractInstantiation(&vestingtypes.DelayedVestingAccount{}),
account: must(vestingtypes.NewDelayedVestingAccount(
authtypes.NewBaseAccount(contractAddr, nil, 0, 0),
sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix())),
initBalance: sdk.NewCoin("denom", sdkmath.NewInt(1_000)),
deposit: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1))),
expAccount: must(vestingtypes.NewDelayedVestingAccount(authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0),
sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix())),
expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_001))),
},
"pruning account fails": {
option: WithAccountPruner(wasmtesting.AccountPrunerMock{CleanupExistingAccountFn: func(ctx sdk.Context, existingAccount sdk.AccountI) (handled bool, err error) {
return false, types.ErrUnsupportedForContract.Wrap("testing")
}}),
account: must(vestingtypes.NewDelayedVestingAccount(
authtypes.NewBaseAccount(contractAddr, nil, 0, 0),
sdk.NewCoins(sdk.NewCoin("denom", sdkmath.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix())),
expErr: types.ErrUnsupportedForContract,
},
}
for name, spec := range specs {
t.Run(name, func(t *testing.T) {
ctx, _ := parentCtx.CacheContext()
if spec.account != nil {
keepers.AccountKeeper.SetAccount(ctx, keepers.AccountKeeper.NewAccount(ctx, spec.account))
}
if !spec.initBalance.IsNil() {
keepers.Faucet.Fund(ctx, spec.account.GetAddress(), spec.initBalance)
}
if spec.option != nil {
spec.option.apply(keepers.WasmKeeper)
}
defer func() {
if spec.option != nil { // reset
WithAcceptedAccountTypesOnContractInstantiation(&authtypes.BaseAccount{}).apply(keepers.WasmKeeper)
WithAccountPruner(NewVestingCoinBurner(keepers.BankKeeper)).apply(keepers.WasmKeeper)
}
}()
// when
gotAddr, _, gotErr := keepers.ContractKeeper.Instantiate2(ctx, 1, senderAddr, nil, initMsg, myTestLabel, spec.deposit, mySalt, false)
if spec.expErr != nil {
assert.ErrorIs(t, gotErr, spec.expErr)
return
}
require.NoError(t, gotErr)
assert.Equal(t, contractAddr, gotAddr)
// and
gotAcc := keepers.AccountKeeper.GetAccount(ctx, contractAddr)
assert.Equal(t, spec.expAccount, gotAcc)
// and
gotBalance := keepers.BankKeeper.GetAllBalances(ctx, contractAddr)
assert.Equal(t, spec.expBalance, gotBalance)
})
}
}
func TestInstantiateWithNonExistingCodeID(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...)
initMsg := HackatomExampleInitMsg{}
initMsgBz, err := json.Marshal(initMsg)
require.NoError(t, err)
const nonExistingCodeID = 9999
addr, _, err := keepers.ContractKeeper.Instantiate(ctx, nonExistingCodeID, creator, nil, initMsgBz, "demo contract 2", nil)
require.Equal(t, types.ErrNoSuchCodeFn(nonExistingCodeID).Wrapf("code id %d", nonExistingCodeID).Error(), err.Error())
require.Nil(t, addr)
}
func TestContractErrorRedacting(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len))
keepers.Faucet.Fund(ctx, creator, deposit...)
example := StoreHackatomExampleContract(t, ctx, keepers)
initMsg := HackatomExampleInitMsg{
Verifier: []byte{1, 2, 3}, // invalid length
Beneficiary: RandomAccountAddress(t),
}
initMsgBz, err := json.Marshal(initMsg)
require.NoError(t, err)
em := sdk.NewEventManager()
_, _, err = keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil)
require.Error(t, err)
require.Contains(t, err.Error(), "addr_validate errored: invalid address")
err = redactError(err)
// contract error should not be redacted
require.Contains(t, err.Error(), "addr_validate errored: invalid address")
}
func TestContractErrorGetsForwarded(t *testing.T) {
// This test makes sure that a contract gets the error message from its submessage execution
// in a non-redacted form if that error comes from the contract in the submessage.
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
reflect1 := InstantiateReflectExampleContract(t, ctx, keepers)
// reflect2 will be the contract that errors. It is owned by the other reflect contract.
// This is necessary because the reflect contract only accepts messages from its owner.
reflect2, _, err := keepers.ContractKeeper.Instantiate(ctx, reflect1.CodeID, reflect1.Contract, reflect1.Contract, []byte("{}"), "reflect2", sdk.NewCoins())
require.NoError(t, err)
const SubMsgID = 1
// Make the reflect1 contract send a submessage to reflect2. That sub-message will error.
execMsg := testdata.ReflectHandleMsg{
ReflectSubMsg: &testdata.ReflectSubPayload{
Msgs: []wasmvmtypes.SubMsg{
{
ID: SubMsgID,
Msg: wasmvmtypes.CosmosMsg{
Wasm: &wasmvmtypes.WasmMsg{
Execute: &wasmvmtypes.ExecuteMsg{
ContractAddr: reflect2.String(),
// This message will error in the reflect contract as an empty "msgs" array is not allowed
Msg: mustMarshal(t, testdata.ReflectHandleMsg{
Reflect: &testdata.ReflectPayload{
Msgs: []wasmvmtypes.CosmosMsg{},
},
}),
},
},
},
ReplyOn: wasmvmtypes.ReplyError, // we want to see the error
},
},
},
}
execMsgBz := mustMarshal(t, execMsg)
em := sdk.NewEventManager()
_, err = keepers.ContractKeeper.Execute(
ctx.WithEventManager(em),
reflect1.Contract,
reflect1.CreatorAddr,
execMsgBz,
nil,
)
require.NoError(t, err)
// now query the submessage reply
queryMsgBz := mustMarshal(t, testdata.ReflectQueryMsg{
SubMsgResult: &testdata.SubCall{
ID: SubMsgID,
},
})
queryResponse, err := keepers.WasmKeeper.QuerySmart(ctx, reflect1.Contract, queryMsgBz)
require.NoError(t, err)
var submsgReply wasmvmtypes.Reply
mustUnmarshal(t, queryResponse, &submsgReply)
assert.Equal(t, "Messages empty. Must reflect at least one message: execute wasm contract failed", submsgReply.Result.Err)
}
func TestInstantiateWithContractDataResponse(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
wasmEngineMock := &wasmtesting.MockWasmEngine{
InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.ContractResult, uint64, error) {
return &wasmvmtypes.ContractResult{Ok: &wasmvmtypes.Response{Data: []byte("my-response-data")}}, 0, nil
},
AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn,
StoreCodeFn: wasmtesting.NoOpStoreCodeFn,
}
example := StoreRandomContract(t, ctx, keepers, wasmEngineMock)
_, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil)
require.NoError(t, err)
assert.Equal(t, []byte("my-response-data"), data)
}
func TestInstantiateWithContractFactoryChildQueriesParent(t *testing.T) {
// Scenario:
// given a factory contract stored
// when instantiated, the contract creates a new child contract instance
// and the child contracts queries the senders ContractInfo on instantiation
// then the factory contract's ContractInfo should be returned to the child contract
//
// see also: https://github.com/CosmWasm/wasmd/issues/896
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
keeper := keepers.WasmKeeper
var instantiationCount int
callbacks := make([]func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.ContractResult, uint64, error), 2)
wasmEngineMock := &wasmtesting.MockWasmEngine{
// dispatch instantiation calls to callbacks
InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.ContractResult, uint64, error) {
require.Greater(t, len(callbacks), instantiationCount, "unexpected call to instantiation")
do := callbacks[instantiationCount]
instantiationCount++
return do(codeID, env, info, initMsg, store, goapi, querier, gasMeter, gasLimit, deserCost)
},
AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn,
StoreCodeFn: wasmtesting.NoOpStoreCodeFn,
}
// overwrite wasmvm in router
router := baseapp.NewMsgServiceRouter()
router.SetInterfaceRegistry(keepers.EncodingConfig.InterfaceRegistry)
types.RegisterMsgServer(router, NewMsgServerImpl(keeper))
keeper.messenger = NewDefaultMessageHandler(nil, router, nil, nil, nil, nil, keepers.EncodingConfig.Codec, nil)
// overwrite wasmvm in response handler
keeper.wasmVMResponseHandler = NewDefaultWasmVMContractResponseHandler(NewMessageDispatcher(keeper.messenger, keeper))
example := StoreRandomContract(t, ctx, keepers, wasmEngineMock)
// factory contract
callbacks[0] = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.ContractResult, uint64, error) {
t.Log("called factory")
return &wasmvmtypes.ContractResult{
Ok: &wasmvmtypes.Response{
Data: []byte("parent"),
Messages: []wasmvmtypes.SubMsg{
{
ID: 1, ReplyOn: wasmvmtypes.ReplyNever,
Msg: wasmvmtypes.CosmosMsg{
Wasm: &wasmvmtypes.WasmMsg{
Instantiate: &wasmvmtypes.InstantiateMsg{CodeID: example.CodeID, Msg: []byte(`{}`), Label: "child"},
},
},
},
},
},
}, 0, nil
}
// child contract
var capturedSenderAddr string
var capturedCodeInfo []byte
callbacks[1] = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.ContractResult, uint64, error) {
t.Log("called child")
capturedSenderAddr = info.Sender
var err error
capturedCodeInfo, err = querier.Query(wasmvmtypes.QueryRequest{
Wasm: &wasmvmtypes.WasmQuery{
ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: info.Sender},
},
}, gasLimit)
require.NoError(t, err)
return &wasmvmtypes.ContractResult{Ok: &wasmvmtypes.Response{Data: []byte("child")}}, 0, nil
}
// when
parentAddr, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil)
// then
require.NoError(t, err)
assert.Equal(t, []byte("parent"), data)
require.Equal(t, parentAddr.String(), capturedSenderAddr)
expCodeInfo := fmt.Sprintf(`{"code_id":%d,"creator":%q,"pinned":false}`, example.CodeID, example.CreatorAddr.String())
assert.JSONEq(t, expCodeInfo, string(capturedCodeInfo))
}
func TestExecute(t *testing.T) {
ctx, keepers := CreateTestInput(t, false, AvailableCapabilities)
accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000))
creator := DeterministicAccountAddress(t, 1)
keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...)
fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...)
bob := RandomAccountAddress(t)
contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil)
require.NoError(t, err)
initMsg := HackatomExampleInitMsg{
Verifier: fred,
Beneficiary: bob,
}
initMsgBz, err := json.Marshal(initMsg)
require.NoError(t, err)
addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit)
require.NoError(t, err)
require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", addr.String())
// ensure bob doesn't exist
bobAcct := accKeeper.GetAccount(ctx, bob)
require.Nil(t, bobAcct)
// ensure funder has reduced balance
creatorAcct := accKeeper.GetAccount(ctx, creator)
require.NotNil(t, creatorAcct)
// we started at 2*deposit, should have spent one above
assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, creatorAcct.GetAddress()))
// ensure contract has updated balance
contractAcct := accKeeper.GetAccount(ctx, addr)
require.NotNil(t, contractAcct)
assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress()))
// unauthorized - trialCtx so we don't change state
trialCtx := ctx.WithMultiStore(ctx.MultiStore().CacheWrap().(storetypes.MultiStore))
_, err = keepers.ContractKeeper.Execute(trialCtx, addr, creator, []byte(`{"release":{}}`), nil)
require.Error(t, err)
require.True(t, errors.Is(err, types.ErrExecuteFailed))
require.Equal(t, "Unauthorized: execute wasm contract failed", err.Error())
// verifier can execute, and get proper gas amount
start := time.Now()
gasBefore := ctx.GasMeter().GasConsumed()
em := sdk.NewEventManager()
// when
res, err := keepers.ContractKeeper.Execute(ctx.WithEventManager(em), addr, fred, []byte(`{"release":{}}`), topUp)
diff := time.Since(start)
require.NoError(t, err)
require.NotNil(t, res)
// make sure gas is properly deducted from ctx
gasAfter := ctx.GasMeter().GasConsumed()
if types.EnableGasVerification {
require.Equal(t, uint64(0x1acdb), gasAfter-gasBefore)
}
// ensure bob now exists and got both payments released
bobAcct = accKeeper.GetAccount(ctx, bob)
require.NotNil(t, bobAcct)
balance := bankKeeper.GetAllBalances(ctx, bobAcct.GetAddress())
assert.Equal(t, deposit.Add(topUp...), balance)
// ensure contract has updated balance
contractAcct = accKeeper.GetAccount(ctx, addr)
require.NotNil(t, contractAcct)
assert.Equal(t, sdk.Coins{}, bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress()))
// and events emitted
require.Len(t, em.Events(), 9)
expEvt := sdk.NewEvent("execute",
sdk.NewAttribute("_contract_address", addr.String()))
assert.Equal(t, expEvt, em.Events()[3], prettyEvents(t, em.Events()))
t.Logf("Duration: %v (%d gas)\n", diff, gasAfter-gasBefore)
}
func TestExecuteWithDeposit(t *testing.T) {
var (
bob = bytes.Repeat([]byte{1}, types.SDKAddrLen)
fred = bytes.Repeat([]byte{2}, types.SDKAddrLen)
blockedAddr = authtypes.NewModuleAddress(distributiontypes.ModuleName)
deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100))
)
specs := map[string]struct {
srcActor sdk.AccAddress
beneficiary sdk.AccAddress
newBankParams *banktypes.Params
expError bool
fundAddr bool
}{
"actor with funds": {
srcActor: bob,
fundAddr: true,
beneficiary: fred,