forked from Finschia/wasmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_common.go
690 lines (609 loc) · 22.5 KB
/
test_common.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
package keeper
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"os"
"testing"
"time"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/line/ibc-go/v3/modules/apps/transfer"
ibctransfertypes "github.com/line/ibc-go/v3/modules/apps/transfer/types"
ibc "github.com/line/ibc-go/v3/modules/core"
ibchost "github.com/line/ibc-go/v3/modules/core/24-host"
ibckeeper "github.com/line/ibc-go/v3/modules/core/keeper"
"github.com/line/lbm-sdk/baseapp"
"github.com/line/lbm-sdk/codec"
"github.com/line/lbm-sdk/std"
"github.com/line/lbm-sdk/store"
sdk "github.com/line/lbm-sdk/types"
"github.com/line/lbm-sdk/types/address"
sdkerrors "github.com/line/lbm-sdk/types/errors"
"github.com/line/lbm-sdk/types/module"
"github.com/line/lbm-sdk/x/auth"
authkeeper "github.com/line/lbm-sdk/x/auth/keeper"
authtypes "github.com/line/lbm-sdk/x/auth/types"
"github.com/line/lbm-sdk/x/auth/vesting"
authzkeeper "github.com/line/lbm-sdk/x/authz/keeper"
"github.com/line/lbm-sdk/x/bank"
bankkeeper "github.com/line/lbm-sdk/x/bank/keeper"
banktypes "github.com/line/lbm-sdk/x/bank/types"
"github.com/line/lbm-sdk/x/bankplus"
bankpluskeeper "github.com/line/lbm-sdk/x/bankplus/keeper"
"github.com/line/lbm-sdk/x/capability"
capabilitykeeper "github.com/line/lbm-sdk/x/capability/keeper"
capabilitytypes "github.com/line/lbm-sdk/x/capability/types"
"github.com/line/lbm-sdk/x/crisis"
crisistypes "github.com/line/lbm-sdk/x/crisis/types"
"github.com/line/lbm-sdk/x/distribution"
distrclient "github.com/line/lbm-sdk/x/distribution/client"
distributionkeeper "github.com/line/lbm-sdk/x/distribution/keeper"
distributiontypes "github.com/line/lbm-sdk/x/distribution/types"
"github.com/line/lbm-sdk/x/evidence"
evidencetypes "github.com/line/lbm-sdk/x/evidence/types"
"github.com/line/lbm-sdk/x/feegrant"
"github.com/line/lbm-sdk/x/gov"
govkeeper "github.com/line/lbm-sdk/x/gov/keeper"
govtypes "github.com/line/lbm-sdk/x/gov/types"
"github.com/line/lbm-sdk/x/mint"
minttypes "github.com/line/lbm-sdk/x/mint/types"
"github.com/line/lbm-sdk/x/params"
paramsclient "github.com/line/lbm-sdk/x/params/client"
paramskeeper "github.com/line/lbm-sdk/x/params/keeper"
paramstypes "github.com/line/lbm-sdk/x/params/types"
paramproposal "github.com/line/lbm-sdk/x/params/types/proposal"
"github.com/line/lbm-sdk/x/slashing"
slashingtypes "github.com/line/lbm-sdk/x/slashing/types"
"github.com/line/lbm-sdk/x/staking"
stakingkeeper "github.com/line/lbm-sdk/x/staking/keeper"
stakingtypes "github.com/line/lbm-sdk/x/staking/types"
"github.com/line/lbm-sdk/x/upgrade"
upgradeclient "github.com/line/lbm-sdk/x/upgrade/client"
upgradekeeper "github.com/line/lbm-sdk/x/upgrade/keeper"
upgradetypes "github.com/line/lbm-sdk/x/upgrade/types"
"github.com/line/ostracon/crypto"
"github.com/line/ostracon/crypto/ed25519"
"github.com/line/ostracon/libs/log"
wasmappparams "github.com/line/wasmd/app/params"
wasmkeeper "github.com/line/wasmd/x/wasm/keeper"
"github.com/line/wasmd/x/wasm/keeper/wasmtesting"
wasmtypes "github.com/line/wasmd/x/wasm/types"
"github.com/line/wasmd/x/wasmplus/types"
)
var moduleBasics = module.NewBasicManager(
auth.AppModuleBasic{},
bank.AppModuleBasic{},
capability.AppModuleBasic{},
staking.AppModuleBasic{},
mint.AppModuleBasic{},
distribution.AppModuleBasic{},
gov.NewAppModuleBasic(
paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler,
),
params.AppModuleBasic{},
crisis.AppModuleBasic{},
slashing.AppModuleBasic{},
ibc.AppModuleBasic{},
upgrade.AppModuleBasic{},
evidence.AppModuleBasic{},
transfer.AppModuleBasic{},
vesting.AppModuleBasic{},
)
func MakeTestCodec(t testing.TB) codec.Codec {
return MakeEncodingConfig(t).Marshaler
}
func MakeEncodingConfig(_ testing.TB) wasmappparams.EncodingConfig {
encodingConfig := wasmappparams.MakeEncodingConfig()
amino := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
std.RegisterInterfaces(interfaceRegistry)
std.RegisterLegacyAminoCodec(amino)
moduleBasics.RegisterLegacyAminoCodec(amino)
moduleBasics.RegisterInterfaces(interfaceRegistry)
// add wasmd types
types.RegisterInterfaces(interfaceRegistry)
types.RegisterLegacyAminoCodec(amino)
return encodingConfig
}
var TestingStakeParams = stakingtypes.Params{
UnbondingTime: 100,
MaxValidators: 10,
MaxEntries: 10,
HistoricalEntries: 10,
BondDenom: "stake",
}
type TestKeepers struct {
AccountKeeper authkeeper.AccountKeeper
StakingKeeper stakingkeeper.Keeper
DistKeeper distributionkeeper.Keeper
BankKeeper bankkeeper.Keeper
GovKeeper govkeeper.Keeper
ContractKeeper types.ContractOpsKeeper
WasmKeeper *Keeper
IBCKeeper *ibckeeper.Keeper
Router *baseapp.Router
EncodingConfig wasmappparams.EncodingConfig
Faucet *wasmkeeper.TestFaucet
MultiStore sdk.CommitMultiStore
}
// CreateDefaultTestInput common settings for CreateTestInput
func CreateDefaultTestInput(t testing.TB) (sdk.Context, TestKeepers) {
return CreateTestInput(t, false, "staking")
}
// CreateTestInput encoders can be nil to accept the defaults, or set it to override some of the message handlers (like default)
func CreateTestInput(
t testing.TB,
isCheckTx bool,
availableCapabilities string,
opts ...wasmkeeper.Option,
) (sdk.Context, TestKeepers) {
// Load default wasm config
return createTestInput(t, isCheckTx, availableCapabilities, wasmtypes.DefaultWasmConfig(), dbm.NewMemDB(), opts...)
}
// encoders can be nil to accept the defaults, or set it to override some of the message handlers (like default)
func createTestInput(
t testing.TB,
isCheckTx bool,
availableCapabilities string,
wasmConfig wasmtypes.WasmConfig,
db dbm.DB,
opts ...wasmkeeper.Option,
) (sdk.Context, TestKeepers) {
tempDir := t.TempDir()
keys := sdk.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey,
minttypes.StoreKey, distributiontypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey,
evidencetypes.StoreKey, ibctransfertypes.StoreKey,
capabilitytypes.StoreKey, feegrant.StoreKey, authzkeeper.StoreKey,
types.StoreKey,
)
ms := store.NewCommitMultiStore(db)
for _, v := range keys {
ms.MountStoreWithDB(v, sdk.StoreTypeIAVL, db)
}
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
for _, v := range tkeys {
ms.MountStoreWithDB(v, sdk.StoreTypeTransient, db)
}
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
for _, v := range memKeys {
ms.MountStoreWithDB(v, sdk.StoreTypeMemory, db)
}
require.NoError(t, ms.LoadLatestVersion())
ctx := sdk.NewContext(ms, tmproto.Header{
Height: 1234567,
Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC),
}, isCheckTx, log.NewNopLogger())
ctx = wasmtypes.WithTXCounter(ctx, 0)
encodingConfig := MakeEncodingConfig(t)
appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino
paramsKeeper := paramskeeper.NewKeeper(
appCodec,
legacyAmino,
keys[paramstypes.StoreKey],
tkeys[paramstypes.TStoreKey],
)
for _, m := range []string{
authtypes.ModuleName,
banktypes.ModuleName,
stakingtypes.ModuleName,
minttypes.ModuleName,
distributiontypes.ModuleName,
slashingtypes.ModuleName,
crisistypes.ModuleName,
ibctransfertypes.ModuleName,
capabilitytypes.ModuleName,
ibchost.ModuleName,
govtypes.ModuleName,
types.ModuleName,
} {
paramsKeeper.Subspace(m)
}
subspace := func(m string) paramstypes.Subspace {
r, ok := paramsKeeper.GetSubspace(m)
require.True(t, ok)
return r
}
maccPerms := map[string][]string{ // module account permissions
authtypes.FeeCollectorName: nil,
distributiontypes.ModuleName: nil,
minttypes.ModuleName: {authtypes.Minter},
stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking},
stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking},
govtypes.ModuleName: {authtypes.Burner},
ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner},
types.ModuleName: {authtypes.Burner},
}
accountKeeper := authkeeper.NewAccountKeeper(
appCodec,
keys[authtypes.StoreKey], // target store
subspace(authtypes.ModuleName),
authtypes.ProtoBaseAccount, // prototype
maccPerms,
)
blockedAddrs := make(map[string]bool)
for acc := range maccPerms {
blockedAddrs[authtypes.NewModuleAddress(acc).String()] = true
}
bankKeeper := bankpluskeeper.NewBaseKeeper(
appCodec,
keys[banktypes.StoreKey],
accountKeeper,
subspace(banktypes.ModuleName),
blockedAddrs,
false,
)
bankKeeper.SetParams(ctx, banktypes.DefaultParams())
stakingKeeper := stakingkeeper.NewKeeper(
appCodec,
keys[stakingtypes.StoreKey],
accountKeeper,
bankKeeper,
subspace(stakingtypes.ModuleName),
)
stakingKeeper.SetParams(ctx, TestingStakeParams)
distKeeper := distributionkeeper.NewKeeper(
appCodec,
keys[distributiontypes.StoreKey],
subspace(distributiontypes.ModuleName),
accountKeeper,
bankKeeper,
stakingKeeper,
authtypes.FeeCollectorName,
nil,
)
distKeeper.SetParams(ctx, distributiontypes.DefaultParams())
stakingKeeper.SetHooks(distKeeper.Hooks())
// set genesis items required for distribution
distKeeper.SetFeePool(ctx, distributiontypes.InitialFeePool())
upgradeKeeper := upgradekeeper.NewKeeper(
map[int64]bool{},
keys[upgradetypes.StoreKey],
appCodec,
tempDir,
nil,
)
faucet := wasmkeeper.NewTestFaucet(t, ctx, bankKeeper, minttypes.ModuleName, sdk.NewCoin("stake", sdk.NewInt(100_000_000_000)))
// set some funds ot pay out validatores, based on code from:
// https://github.com/line/lbm-sdk/blob/95b22d3a685f7eb531198e0023ef06873835e632/x/distribution/keeper/keeper_test.go#L49-L56
distrAcc := distKeeper.GetDistributionAccount(ctx)
faucet.Fund(ctx, distrAcc.GetAddress(), sdk.NewCoin("stake", sdk.NewInt(2000000)))
accountKeeper.SetModuleAccount(ctx, distrAcc)
capabilityKeeper := capabilitykeeper.NewKeeper(
appCodec,
keys[capabilitytypes.StoreKey],
memKeys[capabilitytypes.MemStoreKey],
)
scopedIBCKeeper := capabilityKeeper.ScopeToModule(ibchost.ModuleName)
scopedWasmKeeper := capabilityKeeper.ScopeToModule(types.ModuleName)
ibcKeeper := ibckeeper.NewKeeper(
appCodec,
keys[ibchost.StoreKey],
subspace(ibchost.ModuleName),
stakingKeeper,
upgradeKeeper,
scopedIBCKeeper,
)
router := baseapp.NewRouter()
bh := bank.NewHandler(bankKeeper)
router.AddRoute(sdk.NewRoute(banktypes.RouterKey, bh))
sh := staking.NewHandler(stakingKeeper)
router.AddRoute(sdk.NewRoute(stakingtypes.RouterKey, sh))
dh := distribution.NewHandler(distKeeper)
router.AddRoute(sdk.NewRoute(distributiontypes.RouterKey, dh))
querier := baseapp.NewGRPCQueryRouter()
querier.SetInterfaceRegistry(encodingConfig.InterfaceRegistry)
msgRouter := baseapp.NewMsgServiceRouter()
msgRouter.SetInterfaceRegistry(encodingConfig.InterfaceRegistry)
cfg := sdk.GetConfig()
cfg.SetAddressVerifier(wasmtypes.VerifyAddressLen())
keeper := NewKeeper(
appCodec,
keys[types.StoreKey],
subspace(types.ModuleName),
accountKeeper,
bankKeeper,
stakingKeeper,
distKeeper,
ibcKeeper.ChannelKeeper,
&ibcKeeper.PortKeeper,
scopedWasmKeeper,
wasmtesting.MockIBCTransferKeeper{},
msgRouter,
querier,
tempDir,
wasmConfig,
availableCapabilities,
opts...,
)
keeper.SetParams(ctx, wasmtypes.DefaultParams())
// add wasm handler so we can loop-back (contracts calling contracts)
contractKeeper := NewPermissionedKeeper(*wasmkeeper.NewDefaultPermissionKeeper(&keeper), keeper)
router.AddRoute(sdk.NewRoute(types.RouterKey, TestHandler(contractKeeper)))
am := module.NewManager( // minimal module set that we use for message/ query tests
bankplus.NewAppModule(appCodec, bankKeeper, accountKeeper),
staking.NewAppModule(appCodec, stakingKeeper, accountKeeper, bankKeeper),
distribution.NewAppModule(appCodec, distKeeper, accountKeeper, bankKeeper, stakingKeeper),
)
am.RegisterServices(module.NewConfigurator(appCodec, msgRouter, querier))
// wasmplus service
types.RegisterMsgServer(msgRouter, NewMsgServerImpl(wasmkeeper.NewDefaultPermissionKeeper(keeper)))
types.RegisterQueryServer(querier, Querier(&keeper))
// wasm service
wasmtypes.RegisterMsgServer(msgRouter, wasmkeeper.NewMsgServerImpl(wasmkeeper.NewDefaultPermissionKeeper(keeper)))
wasmtypes.RegisterQueryServer(querier, WasmQuerier(&keeper))
govRouter := govtypes.NewRouter().
AddRoute(govtypes.RouterKey, govtypes.ProposalHandler).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)).
AddRoute(distributiontypes.RouterKey, distribution.NewCommunityPoolSpendProposalHandler(distKeeper)).
AddRoute(types.RouterKey, NewWasmProposalHandler(&keeper, types.EnableAllProposals))
govKeeper := govkeeper.NewKeeper(
appCodec,
keys[govtypes.StoreKey],
subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()),
accountKeeper,
bankKeeper,
stakingKeeper,
govRouter,
)
govKeeper.SetProposalID(ctx, govtypes.DefaultStartingProposalID)
govKeeper.SetDepositParams(ctx, govtypes.DefaultDepositParams())
govKeeper.SetVotingParams(ctx, govtypes.DefaultVotingParams())
govKeeper.SetTallyParams(ctx, govtypes.DefaultTallyParams())
keepers := TestKeepers{
AccountKeeper: accountKeeper,
StakingKeeper: stakingKeeper,
DistKeeper: distKeeper,
ContractKeeper: contractKeeper,
WasmKeeper: &keeper,
BankKeeper: bankKeeper,
GovKeeper: govKeeper,
IBCKeeper: ibcKeeper,
Router: router,
EncodingConfig: encodingConfig,
Faucet: faucet,
MultiStore: ms,
}
return ctx, keepers
}
// TestHandler returns a wasm handler for tests (to avoid circular imports)
func TestHandler(k types.ContractOpsKeeper) sdk.Handler {
return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {
ctx = ctx.WithEventManager(sdk.NewEventManager())
switch msg := msg.(type) {
case *wasmtypes.MsgStoreCode:
return handleStoreCode(ctx, k, msg)
case *wasmtypes.MsgInstantiateContract:
return handleInstantiate(ctx, k, msg)
case *wasmtypes.MsgExecuteContract:
return handleExecute(ctx, k, msg)
default:
errMsg := fmt.Sprintf("unrecognized wasm message type: %T", msg)
return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg)
}
}
}
func handleStoreCode(ctx sdk.Context, k types.ContractOpsKeeper, msg *wasmtypes.MsgStoreCode) (*sdk.Result, error) {
senderAddr, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return nil, sdkerrors.Wrap(err, "sender")
}
codeID, _, err := k.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission)
if err != nil {
return nil, err
}
return &sdk.Result{
Data: []byte(fmt.Sprintf("%d", codeID)),
Events: ctx.EventManager().ABCIEvents(),
}, nil
}
func handleInstantiate(ctx sdk.Context, k types.ContractOpsKeeper, msg *wasmtypes.MsgInstantiateContract) (*sdk.Result, error) {
senderAddr, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return nil, sdkerrors.Wrap(err, "sender")
}
var adminAddr sdk.AccAddress
if msg.Admin != "" {
if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil {
return nil, sdkerrors.Wrap(err, "admin")
}
}
contractAddr, _, err := k.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds)
if err != nil {
return nil, err
}
return &sdk.Result{
Data: contractAddr,
Events: ctx.EventManager().Events().ToABCIEvents(),
}, nil
}
func handleExecute(ctx sdk.Context, k types.ContractOpsKeeper, msg *wasmtypes.MsgExecuteContract) (*sdk.Result, error) {
senderAddr, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return nil, sdkerrors.Wrap(err, "sender")
}
contractAddr, err := sdk.AccAddressFromBech32(msg.Contract)
if err != nil {
return nil, sdkerrors.Wrap(err, "admin")
}
data, err := k.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds)
if err != nil {
return nil, err
}
return &sdk.Result{
Data: data,
Events: ctx.EventManager().Events().ToABCIEvents(),
}, nil
}
func RandomAccountAddress(_ testing.TB) sdk.AccAddress {
_, _, addr := keyPubAddr()
return addr
}
// DeterministicAccountAddress creates a test address with v repeated to valid address size
func DeterministicAccountAddress(_ testing.TB, v byte) sdk.AccAddress {
return bytes.Repeat([]byte{v}, address.Len)
}
func RandomBech32AccountAddress(t testing.TB) string {
return RandomAccountAddress(t).String()
}
type ExampleContract struct {
InitialAmount sdk.Coins
Creator crypto.PrivKey
CreatorAddr sdk.AccAddress
CodeID uint64
Checksum []byte
}
func StoreHackatomExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract {
return StoreExampleContract(t, ctx, keepers, "../../wasm/keeper/testdata/hackatom.wasm")
}
func StoreBurnerExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract {
return StoreExampleContract(t, ctx, keepers, "../../wasm/keeper/testdata/burner.wasm")
}
func StoreIBCReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract {
return StoreExampleContract(t, ctx, keepers, "../../wasm/keeper/testdata/ibc_reflect.wasm")
}
func StoreReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract {
return StoreExampleContract(t, ctx, keepers, "../../wasm/keeper/testdata/reflect.wasm")
}
func StoreExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers, wasmFile string) ExampleContract {
anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000))
creator, _, creatorAddr := keyPubAddr()
fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount)
wasmCode, err := os.ReadFile(wasmFile)
require.NoError(t, err)
codeID, _, err := keepers.ContractKeeper.Create(ctx, creatorAddr, wasmCode, nil)
require.NoError(t, err)
hash := keepers.WasmKeeper.GetCodeInfo(ctx, codeID).CodeHash
return ExampleContract{anyAmount, creator, creatorAddr, codeID, hash}
}
type ExampleContractInstance struct {
ExampleContract
Contract sdk.AccAddress
}
type HackatomExampleInstance struct {
ExampleContract
Contract sdk.AccAddress
Verifier crypto.PrivKey
VerifierAddr sdk.AccAddress
Beneficiary crypto.PrivKey
BeneficiaryAddr sdk.AccAddress
Label string
Deposit sdk.Coins
}
// InstantiateHackatomExampleContract load and instantiate the "./testdata/hackatom.wasm" contract
func InstantiateHackatomExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) HackatomExampleInstance {
contract := StoreHackatomExampleContract(t, ctx, keepers)
verifier, _, verifierAddr := keyPubAddr()
fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, verifierAddr, contract.InitialAmount)
beneficiary, _, beneficiaryAddr := keyPubAddr()
initMsgBz := HackatomExampleInitMsg{
Verifier: verifierAddr,
Beneficiary: beneficiaryAddr,
}.GetBytes(t)
initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100))
adminAddr := contract.CreatorAddr
label := "demo contract to query"
contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, contract.CodeID, contract.CreatorAddr, adminAddr, initMsgBz, label, initialAmount)
require.NoError(t, err)
return HackatomExampleInstance{
ExampleContract: contract,
Contract: contractAddr,
Verifier: verifier,
VerifierAddr: verifierAddr,
Beneficiary: beneficiary,
BeneficiaryAddr: beneficiaryAddr,
Label: label,
Deposit: initialAmount,
}
}
type ExampleInstance struct {
ExampleContract
Contract sdk.AccAddress
Label string
Deposit sdk.Coins
}
// InstantiateReflectExampleContract load and instantiate the "./testdata/reflect.wasm" contract
func InstantiateReflectExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleInstance {
example := StoreReflectContract(t, ctx, keepers)
initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100))
label := "demo contract to query"
contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, []byte("{}"), label, initialAmount)
require.NoError(t, err)
return ExampleInstance{
ExampleContract: example,
Contract: contractAddr,
Label: label,
Deposit: initialAmount,
}
}
type HackatomExampleInitMsg struct {
Verifier sdk.AccAddress `json:"verifier"`
Beneficiary sdk.AccAddress `json:"beneficiary"`
}
func (m HackatomExampleInitMsg) GetBytes(t testing.TB) []byte {
initMsgBz, err := json.Marshal(m)
require.NoError(t, err)
return initMsgBz
}
type IBCReflectExampleInstance struct {
Contract sdk.AccAddress
Admin sdk.AccAddress
CodeID uint64
ReflectCodeID uint64
}
// InstantiateIBCReflectContract load and instantiate the "./testdata/ibc_reflect.wasm" contract
func InstantiateIBCReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) IBCReflectExampleInstance {
reflectID := StoreReflectContract(t, ctx, keepers).CodeID
ibcReflectID := StoreIBCReflectContract(t, ctx, keepers).CodeID
initMsgBz := IBCReflectInitMsg{
ReflectCodeID: reflectID,
}.GetBytes(t)
adminAddr := RandomAccountAddress(t)
contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, ibcReflectID, adminAddr, adminAddr, initMsgBz, "ibc-reflect-factory", nil)
require.NoError(t, err)
return IBCReflectExampleInstance{
Admin: adminAddr,
Contract: contractAddr,
CodeID: ibcReflectID,
ReflectCodeID: reflectID,
}
}
type IBCReflectInitMsg struct {
ReflectCodeID uint64 `json:"reflect_code_id"`
}
func (m IBCReflectInitMsg) GetBytes(t testing.TB) []byte {
initMsgBz, err := json.Marshal(m)
require.NoError(t, err)
return initMsgBz
}
type BurnerExampleInitMsg struct {
Payout sdk.AccAddress `json:"payout"`
}
func (m BurnerExampleInitMsg) GetBytes(t testing.TB) []byte {
initMsgBz, err := json.Marshal(m)
require.NoError(t, err)
return initMsgBz
}
func fundAccounts(t testing.TB, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, addr sdk.AccAddress, coins sdk.Coins) {
acc := am.NewAccountWithAddress(ctx, addr)
am.SetAccount(ctx, acc)
wasmkeeper.NewTestFaucet(t, ctx, bank, minttypes.ModuleName, coins...).Fund(ctx, addr, coins...)
}
var keyCounter uint64
// we need to make this deterministic (same every test run), as encoded address size and thus gas cost,
// depends on the actual bytes (due to ugly CanonicalAddress encoding)
//
//nolint:unparam
func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) {
keyCounter++
seed := make([]byte, 8)
binary.BigEndian.PutUint64(seed, keyCounter)
key := ed25519.GenPrivKeyFromSecret(seed)
pub := key.PubKey()
addr := sdk.AccAddress(pub.Address())
return key, pub, addr
}