-
Notifications
You must be signed in to change notification settings - Fork 7
/
app.go
414 lines (347 loc) · 13.5 KB
/
app.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
package app
import (
"fmt"
"io"
stdlog "log"
"math/big"
"net/http"
"os"
"path/filepath"
"github.com/spf13/cast"
autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1"
errorsmod "cosmossdk.io/errors"
dbm "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
tmjson "github.com/cometbft/cometbft/libs/json"
"github.com/cometbft/cometbft/libs/log"
tmos "github.com/cometbft/cometbft/libs/os"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
runtimeservices "github.com/cosmos/cosmos-sdk/runtime/services"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/crisis"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
xplaante "github.com/xpladev/xpla/ante"
"github.com/xpladev/xpla/app/keepers"
"github.com/xpladev/xpla/app/openapiconsole"
xplaappparams "github.com/xpladev/xpla/app/params"
"github.com/xpladev/xpla/app/upgrades"
v1_5 "github.com/xpladev/xpla/app/upgrades/v1_5"
"github.com/xpladev/xpla/docs"
"github.com/CosmWasm/wasmd/x/wasm"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
)
var (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome string
Upgrades = []upgrades.Upgrade{
v1_5.Upgrade,
}
)
var (
_ servertypes.Application = (*XplaApp)(nil)
)
var (
// TODO: after test, take this values from appOpts
evmMaxGasWanted uint64 = 500000 //ethermintconfig.DefaultMaxTxGasWanted
)
// XplaApp extends an ABCI application, but with most of its parameters exported.
// They are exported for convenience in creating helper functions, as object
// capabilities aren't needed for testing.
type XplaApp struct { // nolint: golint
*baseapp.BaseApp
keepers.AppKeepers
legacyAmino *codec.LegacyAmino
appCodec codec.Codec
txConfig client.TxConfig
interfaceRegistry types.InterfaceRegistry
invCheckPeriod uint
// the module manager
mm *module.Manager
configurator module.Configurator
}
func init() {
userHomeDir, err := os.UserHomeDir()
if err != nil {
stdlog.Println("Failed to get home dir %2", err)
}
DefaultNodeHome = filepath.Join(userHomeDir, ".xpla")
// apply custom power reduction for 'a' base denom unit 10^18
sdk.DefaultPowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil))
}
// NewXplaApp returns a reference to an initialized Xpla.
func NewXplaApp(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
loadLatest bool,
skipUpgradeHeights map[int64]bool,
homePath string,
encodingConfig xplaappparams.EncodingConfig,
appOpts servertypes.AppOptions,
wasmOpts []wasmkeeper.Option,
baseAppOptions ...func(*baseapp.BaseApp),
) *XplaApp {
appCodec := encodingConfig.Codec
legacyAmino := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
txConfig := encodingConfig.TxConfig
// App Opts
skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants))
invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod))
bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
bApp.SetTxEncoder(txConfig.TxEncoder())
app := &XplaApp{
BaseApp: bApp,
legacyAmino: legacyAmino,
txConfig: txConfig,
appCodec: appCodec,
interfaceRegistry: interfaceRegistry,
invCheckPeriod: invCheckPeriod,
}
moduleAccountAddresses := app.ModuleAccountAddrs()
app.AppKeepers = keepers.NewAppKeeper(
appCodec,
bApp,
legacyAmino,
maccPerms,
moduleAccountAddresses,
app.BlockedModuleAccountAddrs(moduleAccountAddresses),
skipUpgradeHeights,
homePath,
invCheckPeriod,
logger,
appOpts,
wasmOpts,
)
// NOTE: Any module instantiated in the module manager that is later modified
// must be passed by reference here.
app.mm = module.NewManager(appModules(app, encodingConfig, skipGenesisInvariants)...)
// During begin block slashing happens after distr.BeginBlocker so that
// there is nothing left over in the validator fee pool, so as to keep the
// CanWithdrawInvariant invariant.
// NOTE: staking module is required if HistoricalEntries param > 0
// NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC)
// Tell the app's module manager how to set the order of BeginBlockers, which are run at the beginning of every block.
app.mm.SetOrderBeginBlockers(orderBeginBlockers()...)
app.mm.SetOrderEndBlockers(orderEndBlockers()...)
// NOTE: The genutils module must occur after staking so that pools are
// properly initialized with tokens from genesis accounts.
// NOTE: The genutils module must also occur after auth so that it can access the params from auth.
// NOTE: Capability module must occur first so that it can initialize any capabilities
// so that other modules that want to create or claim capabilities afterwards in InitChain
// can do so safely.
app.mm.SetOrderInitGenesis(orderInitBlockers()...)
// Uncomment if you want to set a custom migration order here.
// app.mm.SetOrderMigrations(custom order)
app.mm.RegisterInvariants(app.CrisisKeeper)
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
app.mm.RegisterServices(app.configurator)
autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.mm.Modules))
reflectionSvc, err := runtimeservices.NewReflectionService()
if err != nil {
panic(err)
}
reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc)
// initialize stores
app.MountKVStores(app.GetKVStoreKey())
app.MountTransientStores(app.GetTransientStoreKey())
app.MountMemoryStores(app.GetMemoryStoreKey())
wasmConfig, err := wasm.ReadWasmConfig(appOpts)
if err != nil {
panic("error while reading wasm config: " + err.Error())
}
anteHandler, err := xplaante.NewAnteHandler(
xplaante.HandlerOptions{
Cdc: app.appCodec,
AccountKeeper: app.AccountKeeper,
BankKeeper: app.BankKeeper,
IBCKeeper: app.IBCKeeper,
EvmKeeper: app.EvmKeeper,
FeegrantKeeper: app.FeeGrantKeeper,
VolunteerKeeper: app.VolunteerKeeper,
SignModeHandler: encodingConfig.TxConfig.SignModeHandler(),
SigGasConsumer: xplaante.SigVerificationGasConsumer,
FeeMarketKeeper: app.FeeMarketKeeper,
MaxTxGasWanted: evmMaxGasWanted,
TxFeeChecker: noOpTxFeeChecker,
BypassMinFeeMsgTypes: cast.ToStringSlice(appOpts.Get(xplaappparams.BypassMinFeeMsgTypesKey)),
TxCounterStoreKey: app.GetKey(wasm.StoreKey),
WasmKeeper: &app.WasmKeeper,
WasmConfig: wasmConfig,
},
)
if err != nil {
panic(fmt.Errorf("failed to create AnteHandler: %s", err))
}
app.SetAnteHandler(anteHandler)
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
app.SetEndBlocker(app.EndBlocker)
app.setUpgradeHandlers()
app.setUpgradeStoreLoaders()
if manager := app.SnapshotManager(); manager != nil {
err = manager.RegisterExtensions(
wasmkeeper.NewWasmSnapshotter(app.CommitMultiStore(), &app.WasmKeeper),
)
if err != nil {
panic("failed to register snapshot extension: " + err.Error())
}
}
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err))
}
}
return app
}
// Name returns the name of the App
func (app *XplaApp) Name() string { return app.BaseApp.Name() }
// BeginBlocker application updates every begin block
func (app *XplaApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
return app.mm.BeginBlock(ctx, req)
}
// EndBlocker application updates every end block
func (app *XplaApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
return app.mm.EndBlock(ctx, req)
}
// InitChainer application update at chain initialization
func (app *XplaApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var genesisState GenesisState
if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}
// LoadHeight loads a particular height
func (app *XplaApp) LoadHeight(height int64) error {
return app.LoadVersion(height)
}
// ModuleAccountAddrs returns all the app's module account addresses.
func (app *XplaApp) ModuleAccountAddrs() map[string]bool {
modAccAddrs := make(map[string]bool)
for acc := range maccPerms {
modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true
}
return modAccAddrs
}
// BlockedModuleAccountAddrs returns all the app's blocked module account
// addresses.
func (app *XplaApp) BlockedModuleAccountAddrs(modAccAddrs map[string]bool) map[string]bool {
// remove module accounts that are ALLOWED to received funds
delete(modAccAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String())
return modAccAddrs
}
// LegacyAmino returns XplaApp's amino codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *XplaApp) LegacyAmino() *codec.LegacyAmino {
return app.legacyAmino
}
// AppCodec returns Xpla's app codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *XplaApp) AppCodec() codec.Codec {
return app.appCodec
}
// InterfaceRegistry returns Xpla's InterfaceRegistry
func (app *XplaApp) InterfaceRegistry() types.InterfaceRegistry {
return app.interfaceRegistry
}
// RegisterAPIRoutes registers all application module routes with the provided
// API server.
func (app *XplaApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) {
clientCtx := apiSvr.ClientCtx
// Register new tx routes from grpc-gateway.
authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register new tendermint queries routes from grpc-gateway.
tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register nodeservice grpc-gateway routes.
nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// register app's OpenAPI routes.
if apiConfig.Swagger {
apiSvr.Router.Handle("/static/openapi.yml", http.FileServer(http.FS(docs.Docs)))
apiSvr.Router.PathPrefix("/swagger/").Handler(openapiconsole.Handler(appName, "/static/openapi.yml"))
}
}
// RegisterTxService implements the Application.RegisterTxService method.
func (app *XplaApp) RegisterTxService(clientCtx client.Context) {
authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry)
}
// RegisterTendermintService implements the Application.RegisterTendermintService method.
func (app *XplaApp) RegisterTendermintService(clientCtx client.Context) {
tmservice.RegisterTendermintService(
clientCtx,
app.BaseApp.GRPCQueryRouter(),
app.interfaceRegistry,
app.Query,
)
}
// RegisterTxService allows query minimum-gas-prices in app.toml
func (app *XplaApp) RegisterNodeService(clientCtx client.Context) {
nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter())
}
// configure store loader that checks if version == upgradeHeight and applies store upgrades
func (app *XplaApp) setUpgradeStoreLoaders() {
// When a planned update height is reached, the old binary will panic
// writing on disk the height and name of the update that triggered it
// This will read that value, and execute the preparations for the upgrade.
upgradeInfo, err := app.AppKeepers.UpgradeKeeper.ReadUpgradeInfoFromDisk()
if err != nil {
panic(fmt.Errorf("failed to read upgrade info from disk: %w", err))
}
if app.AppKeepers.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) {
return
}
for _, upgrade := range Upgrades {
upgrade := upgrade
if upgradeInfo.Name == upgrade.UpgradeName {
storeUpgrades := upgrade.StoreUpgrades
app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades))
}
}
}
func (app *XplaApp) setUpgradeHandlers() {
for _, upgrade := range Upgrades {
app.AppKeepers.UpgradeKeeper.SetUpgradeHandler(
upgrade.UpgradeName,
upgrade.CreateUpgradeHandler(
app.mm,
app.configurator,
&app.AppKeepers,
app.appCodec,
),
)
}
}
// noOpTxFeeChecker is an ante TxFeeChecker for the DeductFeeDecorator, see x/auth/ante/fee.go,
// it performs a no-op by not checking tx fees and always returns a zero tx priority
func noOpTxFeeChecker(_ sdk.Context, tx sdk.Tx) (sdk.Coins, int64, error) {
feeTx, ok := tx.(sdk.FeeTx)
if !ok {
return nil, 0, errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx")
}
return feeTx.GetFee(), 0, nil
}