/
root.go
738 lines (638 loc) · 24.9 KB
/
root.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
package cmd
import (
// "fmt"
"embed"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/merlins-labs/merlins/v17/app/params"
"github.com/spf13/cast"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
tmcmds "github.com/tendermint/tendermint/cmd/tendermint/commands"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/debug"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/server"
serverconfig "github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/snapshots"
snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/crisis"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
"github.com/CosmWasm/wasmd/x/wasm"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
"github.com/joho/godotenv"
"github.com/cosmos/cosmos-sdk/client/config"
merlins "github.com/merlins-labs/merlins/v17/app"
)
type AssetList struct {
Assets []Asset `json:"assets"`
}
type Asset struct {
DenomUnits []DenomUnit `json:"denom_units"`
Symbol string `json:"symbol"`
Base string `json:"base"`
Traces []Trace `json:"traces"`
}
type DenomUnit struct {
Denom string `json:"denom"`
Exponent uint64 `json:"exponent"`
Aliases []string `json:"aliases"`
}
type Trace struct {
Type string `json:"type"`
Counterparty struct {
BaseDenom string `json:"base_denom"`
} `json:"counterparty"`
}
type DenomUnitMap struct {
Base string
Exponent uint64 `json:"exponent"`
}
var (
//go:embed "merlins-1-assetlist.json" "fury-test-5-assetlist.json"
assetFS embed.FS
mainnetId = "merlins-1"
testnetId = "fury-test-5"
)
func loadAssetList(initClientCtx client.Context, cmd *cobra.Command, basedenomToIBC, IBCtoBasedenom bool) (map[string]DenomUnitMap, map[string]string) {
var assetList AssetList
chainId := GetChainId(initClientCtx, cmd)
fileName := ""
if chainId == mainnetId || chainId == "" {
fileName = "cmd/merlins/cmd/merlins-1-assetlist-manual.json"
} else if chainId == testnetId {
fileName = "cmd/merlins/cmd/fury-test-5-assetlist-manual.json"
} else {
return nil, nil
}
// The order of precedence for asset list is:
// - If the manually generated asset list (generated via the `update-asset-list` cli cmd) exists (noted by -manual.json ending), use it.
// - If the manually generated asset list does not exist, fall back to the embedded asset list.
localFile, err := os.Open(fileName)
if err != nil {
// If we can't open the local file, fall back to the embedded file.
if chainId == mainnetId || chainId == "" {
fileName = "merlins-1-assetlist.json"
} else if chainId == testnetId {
fileName = "fury-test-5-assetlist.json"
} else {
return nil, nil
}
embeddedFile, err := assetFS.Open(fileName)
if err != nil {
return nil, nil
}
defer embeddedFile.Close()
byteValue, _ := io.ReadAll(embeddedFile)
err = json.Unmarshal(byteValue, &assetList)
if err != nil {
return nil, nil
}
} else {
// If the local file opens successfully, use it instead of the embedded file.
defer localFile.Close()
byteValue, _ := io.ReadAll(localFile)
err = json.Unmarshal(byteValue, &assetList)
if err != nil {
return nil, nil
}
}
baseMap := make(map[string]DenomUnitMap)
baseMapRev := make(map[string]string)
if basedenomToIBC {
for _, asset := range assetList.Assets {
// Each asset has a list of denom units. A majority of them have 2 entries, one being the base 0 exponent denom and the other being a larger exponent denom.
// An example for tether:
// * Exponent 0: uusdt
// * Exponent 6: usdt
// This implies that if a usdt value is given, in order to convert it to it's base denom (uusdt), we need to multiply the provided value by 10^6.
for i, denomUnit := range asset.DenomUnits {
DenomUnitMap := DenomUnitMap{
Base: asset.Base,
Exponent: asset.DenomUnits[i].Exponent,
}
// The 0 exponent denom is the base denom.
if asset.DenomUnits[i].Exponent == 0 {
// To make everyone's life harder, some assets have multiple base denom aliases. For example, the asset list has the following base aliases for the asset "luna":
// * uluna
// * microluna
for _, alias := range denomUnit.Aliases {
baseMap[strings.ToLower(alias)] = DenomUnitMap
}
} else {
// Otherwise we just store the denom alias for that exponent.
baseMap[strings.ToLower(denomUnit.Denom)] = DenomUnitMap
}
}
}
}
if IBCtoBasedenom {
// We just store a link from the first base denom alias to the IBC denom. This is just used for display purposes on the terminal's output.
for _, asset := range assetList.Assets {
if len(asset.DenomUnits) > 0 && asset.DenomUnits[0].Exponent == 0 && len(asset.DenomUnits[0].Aliases) > 0 {
baseDenom := asset.DenomUnits[0].Aliases[0]
baseMapRev[asset.Base] = strings.ToLower(baseDenom)
}
}
}
return baseMap, baseMapRev
}
type customWriter struct {
originalOut io.Writer
baseMap map[string]string
}
func (cw *customWriter) Write(p []byte) (n int, err error) {
// Convert byte slice to string.
s := string(p)
// Buffer to hold the new string.
var buf strings.Builder
// Index where the current denom starts. -1 if we're not currently in a denom.
denomStart := -1
// Counter for slashes encountered
slashCounter := 0
re, err := regexp.Compile("[^a-zA-Z0-9/-]")
if err != nil {
return 0, err
}
for i := 0; i < len(s); i++ {
if denomStart == -1 {
// If we're not currently in a denom, check if this character starts a new denom.
// Check for "ibc/" or "factory/" prefix.
if strings.HasPrefix(s[i:], "ibc/") || strings.HasPrefix(s[i:], "factory/") {
slashCounter = 0
denomStart = i
continue
}
// Write the character to the buffer.
buf.WriteByte(s[i])
} else {
// For factory denoms, we keep track of slashes to find the second slash.
if s[i] == '/' {
slashCounter++
}
// For "ibc/" we find the end by length, for "factory/" we find the end by second slash and regex.
if (strings.HasPrefix(s[denomStart:], "ibc/") && i-denomStart == 68) || (strings.HasPrefix(s[denomStart:], "factory/") && slashCounter == 2 && re.MatchString(string(s[i]))) {
// We've reached the end of the line containing the denom.
denom := s[denomStart:i]
if replacement, ok := cw.baseMap[denom]; ok {
// If the denom is in the map, write the replacement to the buffer.
buf.WriteString(replacement)
} else {
// If the denom is not in the map, write the original denom to the buffer.
buf.WriteString(denom)
}
// Write the new line character to the buffer.
buf.WriteByte(s[i])
// We're no longer in a denom.
denomStart = -1
slashCounter = 0
}
}
}
// If we're still in a denom at the end of the string, write the rest of the denom to the buffer.
if denomStart != -1 {
denom := s[denomStart:]
if replacement, ok := cw.baseMap[denom]; ok {
buf.WriteString(replacement)
} else {
buf.WriteString(denom)
}
}
// Write the new string to the original output.
return cw.originalOut.Write([]byte(buf.String()))
}
// NewRootCmd creates a new root command for simd. It is called once in the
// main function.
func NewRootCmd() (*cobra.Command, params.EncodingConfig) {
encodingConfig := merlins.MakeEncodingConfig()
homeEnvironment := getHomeEnvironment()
homeDir, err := environmentNameToPath(homeEnvironment)
if err != nil {
// Failed to convert home environment to home path, using default home
homeDir = merlins.DefaultNodeHome
}
initClientCtx := client.Context{}.
WithCodec(encodingConfig.Marshaler).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}).
WithBroadcastMode(flags.BroadcastBlock).
WithHomeDir(homeDir).
WithViper("MERLINS")
// Allows you to add extra params to your client.toml
// gas, gas-price, gas-adjustment, and human-readable-denoms
SetCustomEnvVariablesFromClientToml(initClientCtx)
humanReadableDenomsInput, humanReadableDenomsOutput := GetHumanReadableDenomEnvVariables()
rootCmd := &cobra.Command{
Use: "merlins",
Short: "Start merlins app",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// If not calling the set-env command, this is a no-op.
err := changeEnvPriorToSetup(cmd, &initClientCtx, args, homeDir)
if err != nil {
return err
}
initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags())
if err != nil {
return err
}
initClientCtx, err = config.ReadFromClientConfig(initClientCtx)
if err != nil {
return err
}
// Only loads asset list into a map if human readable denoms are enabled.
assetMap, assetMapRev := map[string]DenomUnitMap{}, map[string]string{}
if humanReadableDenomsInput || humanReadableDenomsOutput {
assetMap, assetMapRev = loadAssetList(initClientCtx, cmd, humanReadableDenomsInput, humanReadableDenomsOutput)
}
// If enabled, CLI output will be parsed and human readable denominations will be used in place of ibc denoms.
if humanReadableDenomsOutput {
initClientCtx.Output = &customWriter{originalOut: os.Stdout, baseMap: assetMapRev}
}
if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil {
return err
}
customAppTemplate, customAppConfig := initAppConfig()
// If enabled, CLI input will be parsed and human readable denominations will be automatically converted to ibc denoms.
if humanReadableDenomsInput {
// Parse and replace denoms in args
for i, arg := range args {
lowerCaseArg := strings.ToLower(arg)
lowerCaseArgArray := strings.Split(lowerCaseArg, ",")
re := regexp.MustCompile(`^([\d.]+)(\D+)$`)
for i, lowerCaseArg := range lowerCaseArgArray {
match := re.FindStringSubmatch(lowerCaseArg)
if len(match) == 3 {
value, denom := match[1], match[2]
// If the index has a length of 3 then it has a number and a denom (this is a coin object)
// Note, index 0 is the entire string, index 1 is the number, and index 2 is the denom
transformedCoin, err := transformCoinValueToBaseInt(value, denom, assetMap)
if err != nil {
continue
}
lowerCaseArgArray[i] = transformedCoin
} else {
if _, ok := assetMap[lowerCaseArg]; ok {
// In this case, we just need to replace the denom with the base denom
lowerCaseArgArray[i] = assetMap[lowerCaseArg].Base
}
}
}
args[i] = strings.Join(lowerCaseArgArray, ",")
}
// Parse and replace denoms in flags
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
lowerCaseFlagValue := strings.ToLower(flag.Value.String())
lowerCaseFlagValueArray := strings.Split(lowerCaseFlagValue, ",")
re := regexp.MustCompile(`^([\d.]+)(\D+)$`)
for i, lowerCaseFlagValue := range lowerCaseFlagValueArray {
match := re.FindStringSubmatch(lowerCaseFlagValue)
if len(match) == 3 {
value, denom := match[1], match[2]
// If the index has a length of 3 then it has a number and a denom (this is a coin object)
// Note, index 0 is the entire string, index 1 is the number, and index 2 is the denom
transformedCoin, err := transformCoinValueToBaseInt(value, denom, assetMap)
if err != nil {
continue
}
lowerCaseFlagValueArray[i] = transformedCoin
} else {
if _, ok := assetMap[lowerCaseFlagValue]; ok {
// Otherwise, we just need to replace the denom with the base denom
lowerCaseFlagValueArray[i] = assetMap[lowerCaseFlagValue].Base
}
}
}
newLowerCaseFlagValue := strings.Join(lowerCaseFlagValueArray, ",")
if lowerCaseFlagValue != newLowerCaseFlagValue {
if err := cmd.Flags().Set(flag.Name, newLowerCaseFlagValue); err != nil {
fmt.Println("Failed to set flag:", err)
}
}
})
}
return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig)
},
SilenceUsage: true,
}
genAutoCompleteCmd(rootCmd)
initRootCmd(rootCmd, encodingConfig)
return rootCmd, encodingConfig
}
func getHomeEnvironment() string {
envPath := filepath.Join(merlins.DefaultNodeHome, ".env")
// Use default node home if can't get environment.
// Overload must be used here in the event that the .env gets updated.
err := godotenv.Overload(envPath)
if err != nil {
// Failed to load, using default home directory
return EnvMainnet
}
val := os.Getenv(EnvVariable)
return val
}
// initAppConfig helps to override default appConfig template and configs.
// return "", nil if no custom configuration is required for the application.
func initAppConfig() (string, interface{}) {
type MerlinsMempoolConfig struct {
ArbitrageMinGasPrice string `mapstructure:"arbitrage-min-gas-fee"`
}
type CustomAppConfig struct {
serverconfig.Config
MerlinsMempoolConfig MerlinsMempoolConfig `mapstructure:"merlins-mempool"`
}
// Optionally allow the chain developer to overwrite the SDK's default
// server config.
srvCfg := serverconfig.DefaultConfig()
srvCfg.API.Enable = true
srvCfg.StateSync.SnapshotInterval = 1500
srvCfg.StateSync.SnapshotKeepRecent = 2
srvCfg.MinGasPrices = "0ufury"
// 128MB IAVL cache
srvCfg.IAVLCacheSize = 781250
memCfg := MerlinsMempoolConfig{ArbitrageMinGasPrice: "0.01"}
MerlinsAppCfg := CustomAppConfig{Config: *srvCfg, MerlinsMempoolConfig: memCfg}
MerlinsAppTemplate := serverconfig.DefaultConfigTemplate + `
###############################################################################
### Merlins Mempool Configuration ###
###############################################################################
[merlins-mempool]
# This is the max allowed gas any tx.
# This is only for local mempool purposes, and thus is only ran on check tx.
max-gas-wanted-per-tx = "25000000"
# This is the minimum gas fee any arbitrage tx should have, denominated in ufury per gas
# Default value of ".005" then means that a tx with 1 million gas costs (.005 ufury/gas) * 1_000_000 gas = .005 fury
arbitrage-min-gas-fee = ".005"
# This is the minimum gas fee any tx with high gas demand should have, denominated in ufury per gas
# Default value of ".0025" then means that a tx with 1 million gas costs (.0025 ufury/gas) * 1_000_000 gas = .0025 fury
min-gas-price-for-high-gas-tx = ".0025"
`
return MerlinsAppTemplate, MerlinsAppCfg
}
// initRootCmd initializes root commands when creating a new root command for simd.
func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {
cfg := sdk.GetConfig()
cfg.Seal()
debugCmd := debug.Cmd()
debugCmd.AddCommand(ConvertBech32Cmd())
debugCmd.AddCommand(DebugProtoMarshalledBytes())
rootCmd.AddCommand(
// genutilcli.InitCmd(merlins.ModuleBasics, merlins.DefaultNodeHome),
forceprune(),
InitCmd(merlins.ModuleBasics, merlins.DefaultNodeHome),
genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, merlins.DefaultNodeHome),
genutilcli.MigrateGenesisCmd(),
ExportDeriveBalancesCmd(),
StakedToCSVCmd(),
AddGenesisAccountCmd(merlins.DefaultNodeHome),
genutilcli.GenTxCmd(merlins.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, merlins.DefaultNodeHome),
genutilcli.ValidateGenesisCmd(merlins.ModuleBasics),
PrepareGenesisCmd(merlins.DefaultNodeHome, merlins.ModuleBasics),
tmcli.NewCompletionCmd(rootCmd, true),
testnetCmd(merlins.ModuleBasics, banktypes.GenesisBalancesIterator{}),
tmcmds.RollbackStateCmd,
debugCmd,
ConfigCmd(),
ChangeEnvironmentCmd(),
PrintEnvironmentCmd(),
UpdateAssetListCmd(merlins.DefaultNodeHome, merlins.ModuleBasics),
)
server.AddCommands(rootCmd, merlins.DefaultNodeHome, newApp, createMerlinsAppAndExport, addModuleInitFlags)
// add keybase, auxiliary RPC, query, and tx child commands
rootCmd.AddCommand(
rpc.StatusCommand(),
queryCommand(),
txCommand(),
keys.Commands(merlins.DefaultNodeHome),
)
// add rosetta
rootCmd.AddCommand(server.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler))
}
func addModuleInitFlags(startCmd *cobra.Command) {
crisis.AddModuleInitFlags(startCmd)
wasm.AddModuleInitFlags(startCmd)
}
// queryCommand adds transaction and account querying commands.
func queryCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "query",
Aliases: []string{"q"},
Short: "Querying subcommands",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
authcmd.GetAccountCmd(),
rpc.ValidatorCommand(),
rpc.BlockCommand(),
authcmd.QueryTxsByEventsCmd(),
authcmd.QueryTxCmd(),
)
merlins.ModuleBasics.AddQueryCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")
return cmd
}
// txCommand adds transaction signing, encoding / decoding, and broadcasting commands.
func txCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "tx",
Short: "Transactions subcommands",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
authcmd.GetSignCommand(),
authcmd.GetSignBatchCommand(),
authcmd.GetMultiSignCommand(),
authcmd.GetValidateSignaturesCommand(),
flags.LineBreak,
authcmd.GetBroadcastCommand(),
authcmd.GetEncodeCommand(),
authcmd.GetDecodeCommand(),
)
merlins.ModuleBasics.AddTxCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")
return cmd
}
// newApp initializes and returns a new Merlins app.
func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
var cache sdk.MultiStorePersistentCache
if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) {
cache = store.NewCommitKVStoreCacheManager()
}
skipUpgradeHeights := make(map[int64]bool)
for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) {
skipUpgradeHeights[int64(h)] = true
}
pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts)
if err != nil {
panic(err)
}
snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots")
snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir)
if err != nil {
panic(err)
}
snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir)
if err != nil {
panic(err)
}
var wasmOpts []wasm.Option
if cast.ToBool(appOpts.Get("telemetry.enabled")) {
wasmOpts = append(wasmOpts, wasmkeeper.WithVMCacheMetrics(prometheus.DefaultRegisterer))
}
return merlins.NewMerlinsApp(
logger, db, traceStore, true, skipUpgradeHeights,
cast.ToString(appOpts.Get(flags.FlagHome)),
cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
appOpts,
wasmOpts,
baseapp.SetPruning(pruningOpts),
baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))),
baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))),
baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))),
baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))),
baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))),
baseapp.SetInterBlockCache(cache),
baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))),
baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))),
baseapp.SetSnapshot(snapshotStore, snapshottypes.NewSnapshotOptions(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval)), cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent)))),
)
}
// createMerlinsAppAndExport creates and exports the new Merlins app, returns the state of the new Merlins app for a genesis file.
func createMerlinsAppAndExport(
logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string,
appOpts servertypes.AppOptions, modulesToExport []string,
) (servertypes.ExportedApp, error) {
encCfg := merlins.MakeEncodingConfig() // Ideally, we would reuse the one created by NewRootCmd.
encCfg.Marshaler = codec.NewProtoCodec(encCfg.InterfaceRegistry)
loadLatest := height == -1
homeDir := cast.ToString(appOpts.Get(flags.FlagHome))
app := merlins.NewMerlinsApp(logger, db, traceStore, loadLatest, map[int64]bool{}, homeDir, 0, appOpts, merlins.EmptyWasmOpts)
if !loadLatest {
if err := app.LoadHeight(height); err != nil {
return servertypes.ExportedApp{}, err
}
}
return app.ExportAppStateAndValidators(forZeroHeight, jailWhiteList, modulesToExport)
}
func UpdateAssetListCmd(defaultNodeHome string, mbm module.BasicManager) *cobra.Command {
cmd := &cobra.Command{
Use: "update-asset-list [chain-id]",
Short: "Updates asset list used by the CLI to replace ibc denoms with human readable names",
Long: `Updates asset list used by the CLI to replace ibc denoms with human readable names.
Outputs:
- cmd/merlins/cmd/merlins-1-assetlist-manual.json for merlins-1
- cmd/merlins/cmd/fury-test-5-assetlist-manual.json for fury-test-5
`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
assetListURL := ""
fileName := ""
if args[0] == mainnetId || args[0] == "" {
assetListURL = "https://raw.githubusercontent.com/merlins-labs/assetlists/main/merlins-1/merlins-1.assetlist.json"
fileName = "cmd/merlins/cmd/merlins-1-assetlist-manual.json"
} else if args[0] == testnetId {
assetListURL = "https://raw.githubusercontent.com/merlins-labs/assetlists/main/fury-test-5/fury-test-5.assetlist.json"
fileName = "cmd/merlins/cmd/fury-test-5-assetlist-manual.json"
} else {
return nil
}
// Try to fetch the asset list from the URL
resp, err := http.Get(assetListURL)
if err != nil {
return err
}
defer resp.Body.Close()
// Create a new file
out, err := os.Create(fileName)
if err != nil {
return err
}
defer out.Close()
// Copy the response body to the new file
_, err = io.Copy(out, resp.Body)
return err
},
}
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
return cmd
}
func genAutoCompleteCmd(rootCmd *cobra.Command) {
rootCmd.AddCommand(&cobra.Command{
Use: "enable-cli-autocomplete [bash|zsh|fish|powershell]",
Short: "Generates cli completion scripts",
Long: `To configure your shell to load completions for each session, add to your profile:
# bash example
echo '. <(merlins enable-cli-autocomplete bash)' >> ~/.profile
source ~/.profile
# zsh example
echo '. <(merlins enable-cli-autocomplete zsh)' >> ~/.zshrc
source ~/.zshrc
`,
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
_ = cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
_ = cmd.Root().GenZshCompletion(os.Stdout)
case "fish":
_ = cmd.Root().GenFishCompletion(os.Stdout, true)
case "powershell":
_ = cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
}
},
})
}
// transformCoinValueToBaseInt transforms a cli input that has been split into a number and a denom into it's base int value and base denom.
// i.e. 10.7fury -> 10700000ufury
// 12atom -> 12000000uatom
// 15000000uakt -> 15000000uakt (does nothing since it's already in base denom format)
func transformCoinValueToBaseInt(coinValue, coinDenom string, assetMap map[string]DenomUnitMap) (string, error) {
// If the index has a length of 3 then it has a number and a denom (this is a coin object)
// Note, index 0 is the entire string, index 1 is the number, and index 2 is the denom
if denomUnitMap, ok := assetMap[coinDenom]; ok {
// In this case, we just need to replace the denom with the base denom and retain the number
if denomUnitMap.Exponent != 0 {
coinDec, err := sdk.NewDecFromStr(coinValue)
if err != nil {
return "", err
}
transformedCoinValue := coinDec.Mul(sdk.MustNewDecFromStr("10").Power(denomUnitMap.Exponent))
transformedCoinValueInt := transformedCoinValue.TruncateInt()
transformedCoinValueStr := transformedCoinValueInt.String()
return transformedCoinValueStr + assetMap[coinDenom].Base, nil
} else {
return coinValue + assetMap[coinDenom].Base, nil
}
}
return "", fmt.Errorf("denom %s not found in asset map", coinDenom)
}