Initialized with Ignite CLI

master
Developer Experience team at Tendermint 2022-08-25 23:51:14 +00:00
commit 4ea2b97c14
417 changed files with 298980 additions and 0 deletions

53
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,53 @@
# This workflow is useful if you want to automate the process of:
#
# a) Creating a new prelease when you push a new tag with a "v" prefix (version).
#
# This type of prerelease is meant to be used for production: alpha, beta, rc, etc. types of releases.
# After the prerelease is created, you need to make your changes on the release page at the relevant
# Github page and publish your release.
#
# b) Creating/updating the "latest" prerelease when you push to your default branch.
#
# This type of prelease is useful to make your bleeding-edge binaries available to advanced users.
#
# The workflow will not run if there is no tag pushed with a "v" prefix and no change pushed to your
# default branch.
on: push
jobs:
might_release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Prepare Release Variables
id: vars
uses: ignite-hq/cli/actions/release/vars@develop
- name: Issue Release Assets
uses: ignite-hq/cli/actions/cli@develop
if: ${{ steps.vars.outputs.should_release == 'true' }}
with:
args: chain build --release --release.prefix ${{ steps.vars.outputs.tarball_prefix }} -t linux:amd64 -t darwin:amd64 -t darwin:arm64
- name: Delete the "latest" Release
uses: dev-drprasad/delete-tag-and-release@v0.2.0
if: ${{ steps.vars.outputs.is_release_type_latest == 'true' }}
with:
tag_name: ${{ steps.vars.outputs.tag_name }}
delete_release: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Publish the Release
uses: softprops/action-gh-release@v1
if: ${{ steps.vars.outputs.should_release == 'true' }}
with:
tag_name: ${{ steps.vars.outputs.tag_name }}
files: release/*
prerelease: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
vue/node_modules
vue/dist
release/
.idea/
.vscode/
.DS_Store

746
app/app.go Normal file
View File

@ -0,0 +1,746 @@
package app
import (
"io"
"net/http"
"os"
"path/filepath"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
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"
"github.com/cosmos/cosmos-sdk/x/authz"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module"
"github.com/cosmos/cosmos-sdk/x/bank"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/capability"
capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
"github.com/cosmos/cosmos-sdk/x/crisis"
crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper"
crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
distr "github.com/cosmos/cosmos-sdk/x/distribution"
distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client"
distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/evidence"
evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
"github.com/cosmos/cosmos-sdk/x/feegrant"
feegrantkeeper "github.com/cosmos/cosmos-sdk/x/feegrant/keeper"
feegrantmodule "github.com/cosmos/cosmos-sdk/x/feegrant/module"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/gov"
govclient "github.com/cosmos/cosmos-sdk/x/gov/client"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
"github.com/cosmos/cosmos-sdk/x/mint"
mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/cosmos/cosmos-sdk/x/params"
paramsclient "github.com/cosmos/cosmos-sdk/x/params/client"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
"github.com/cosmos/cosmos-sdk/x/slashing"
slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/cosmos/cosmos-sdk/x/upgrade"
upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client"
upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
"github.com/cosmos/ibc-go/v3/modules/apps/transfer"
ibctransferkeeper "github.com/cosmos/ibc-go/v3/modules/apps/transfer/keeper"
ibctransfertypes "github.com/cosmos/ibc-go/v3/modules/apps/transfer/types"
ibc "github.com/cosmos/ibc-go/v3/modules/core"
ibcclient "github.com/cosmos/ibc-go/v3/modules/core/02-client"
ibcclientclient "github.com/cosmos/ibc-go/v3/modules/core/02-client/client"
ibcclienttypes "github.com/cosmos/ibc-go/v3/modules/core/02-client/types"
ibcporttypes "github.com/cosmos/ibc-go/v3/modules/core/05-port/types"
ibchost "github.com/cosmos/ibc-go/v3/modules/core/24-host"
ibckeeper "github.com/cosmos/ibc-go/v3/modules/core/keeper"
"github.com/spf13/cast"
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
dbm "github.com/tendermint/tm-db"
"github.com/ignite/cli/ignite/pkg/cosmoscmd"
"github.com/ignite/cli/ignite/pkg/openapiconsole"
monitoringp "github.com/tendermint/spn/x/monitoringp"
monitoringpkeeper "github.com/tendermint/spn/x/monitoringp/keeper"
monitoringptypes "github.com/tendermint/spn/x/monitoringp/types"
"cosmos-test/docs"
cosmostestmodule "cosmos-test/x/cosmostest"
cosmostestmodulekeeper "cosmos-test/x/cosmostest/keeper"
cosmostestmoduletypes "cosmos-test/x/cosmostest/types"
// this line is used by starport scaffolding # stargate/app/moduleImport
)
const (
AccountAddressPrefix = "cosmos"
Name = "cosmos-test"
)
// this line is used by starport scaffolding # stargate/wasm/app/enabledProposals
func getGovProposalHandlers() []govclient.ProposalHandler {
var govProposalHandlers []govclient.ProposalHandler
// this line is used by starport scaffolding # stargate/app/govProposalHandlers
govProposalHandlers = append(govProposalHandlers,
paramsclient.ProposalHandler,
distrclient.ProposalHandler,
upgradeclient.ProposalHandler,
upgradeclient.CancelProposalHandler,
ibcclientclient.UpdateClientProposalHandler,
ibcclientclient.UpgradeProposalHandler,
// this line is used by starport scaffolding # stargate/app/govProposalHandler
)
return govProposalHandlers
}
var (
// DefaultNodeHome default home directories for the application daemon
DefaultNodeHome string
// ModuleBasics defines the module BasicManager is in charge of setting up basic,
// non-dependant module elements, such as codec registration
// and genesis verification.
ModuleBasics = module.NewBasicManager(
auth.AppModuleBasic{},
authzmodule.AppModuleBasic{},
genutil.AppModuleBasic{},
bank.AppModuleBasic{},
capability.AppModuleBasic{},
staking.AppModuleBasic{},
mint.AppModuleBasic{},
distr.AppModuleBasic{},
gov.NewAppModuleBasic(getGovProposalHandlers()...),
params.AppModuleBasic{},
crisis.AppModuleBasic{},
slashing.AppModuleBasic{},
feegrantmodule.AppModuleBasic{},
ibc.AppModuleBasic{},
upgrade.AppModuleBasic{},
evidence.AppModuleBasic{},
transfer.AppModuleBasic{},
vesting.AppModuleBasic{},
monitoringp.AppModuleBasic{},
cosmostestmodule.AppModuleBasic{},
// this line is used by starport scaffolding # stargate/app/moduleBasic
)
// module account permissions
maccPerms = map[string][]string{
authtypes.FeeCollectorName: nil,
distrtypes.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},
// this line is used by starport scaffolding # stargate/app/maccPerms
}
)
var (
_ cosmoscmd.App = (*App)(nil)
_ servertypes.Application = (*App)(nil)
_ simapp.App = (*App)(nil)
)
func init() {
userHomeDir, err := os.UserHomeDir()
if err != nil {
panic(err)
}
DefaultNodeHome = filepath.Join(userHomeDir, "."+Name)
}
// App 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 App struct {
*baseapp.BaseApp
cdc *codec.LegacyAmino
appCodec codec.Codec
interfaceRegistry types.InterfaceRegistry
invCheckPeriod uint
// keys to access the substores
keys map[string]*sdk.KVStoreKey
tkeys map[string]*sdk.TransientStoreKey
memKeys map[string]*sdk.MemoryStoreKey
// keepers
AccountKeeper authkeeper.AccountKeeper
AuthzKeeper authzkeeper.Keeper
BankKeeper bankkeeper.Keeper
CapabilityKeeper *capabilitykeeper.Keeper
StakingKeeper stakingkeeper.Keeper
SlashingKeeper slashingkeeper.Keeper
MintKeeper mintkeeper.Keeper
DistrKeeper distrkeeper.Keeper
GovKeeper govkeeper.Keeper
CrisisKeeper crisiskeeper.Keeper
UpgradeKeeper upgradekeeper.Keeper
ParamsKeeper paramskeeper.Keeper
IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly
EvidenceKeeper evidencekeeper.Keeper
TransferKeeper ibctransferkeeper.Keeper
FeeGrantKeeper feegrantkeeper.Keeper
MonitoringKeeper monitoringpkeeper.Keeper
// make scoped keepers public for test purposes
ScopedIBCKeeper capabilitykeeper.ScopedKeeper
ScopedTransferKeeper capabilitykeeper.ScopedKeeper
ScopedMonitoringKeeper capabilitykeeper.ScopedKeeper
CosmostestKeeper cosmostestmodulekeeper.Keeper
// this line is used by starport scaffolding # stargate/app/keeperDeclaration
// mm is the module manager
mm *module.Manager
// sm is the simulation manager
sm *module.SimulationManager
}
// New returns a reference to an initialized blockchain app
func New(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
loadLatest bool,
skipUpgradeHeights map[int64]bool,
homePath string,
invCheckPeriod uint,
encodingConfig cosmoscmd.EncodingConfig,
appOpts servertypes.AppOptions,
baseAppOptions ...func(*baseapp.BaseApp),
) cosmoscmd.App {
appCodec := encodingConfig.Marshaler
cdc := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
bApp := baseapp.NewBaseApp(Name, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
keys := sdk.NewKVStoreKeys(
authtypes.StoreKey, authz.ModuleName, banktypes.StoreKey, stakingtypes.StoreKey,
minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey,
evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, monitoringptypes.StoreKey,
cosmostestmoduletypes.StoreKey,
// this line is used by starport scaffolding # stargate/app/storeKey
)
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
app := &App{
BaseApp: bApp,
cdc: cdc,
appCodec: appCodec,
interfaceRegistry: interfaceRegistry,
invCheckPeriod: invCheckPeriod,
keys: keys,
tkeys: tkeys,
memKeys: memKeys,
}
app.ParamsKeeper = initParamsKeeper(appCodec, cdc, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey])
// set the BaseApp's parameter store
bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramskeeper.ConsensusParamsKeyTable()))
// add capability keeper and ScopeToModule for ibc module
app.CapabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey])
// grant capabilities for the ibc and ibc-transfer modules
scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibchost.ModuleName)
scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName)
// this line is used by starport scaffolding # stargate/app/scopedKeeper
// add keepers
app.AccountKeeper = authkeeper.NewAccountKeeper(
appCodec, keys[authtypes.StoreKey], app.GetSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms,
)
app.AuthzKeeper = authzkeeper.NewKeeper(
keys[authz.ModuleName], appCodec, app.MsgServiceRouter(),
)
app.BankKeeper = bankkeeper.NewBaseKeeper(
appCodec, keys[banktypes.StoreKey], app.AccountKeeper, app.GetSubspace(banktypes.ModuleName), app.ModuleAccountAddrs(),
)
stakingKeeper := stakingkeeper.NewKeeper(
appCodec, keys[stakingtypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName),
)
app.MintKeeper = mintkeeper.NewKeeper(
appCodec, keys[minttypes.StoreKey], app.GetSubspace(minttypes.ModuleName), &stakingKeeper,
app.AccountKeeper, app.BankKeeper, authtypes.FeeCollectorName,
)
app.DistrKeeper = distrkeeper.NewKeeper(
appCodec, keys[distrtypes.StoreKey], app.GetSubspace(distrtypes.ModuleName), app.AccountKeeper, app.BankKeeper,
&stakingKeeper, authtypes.FeeCollectorName, app.ModuleAccountAddrs(),
)
app.SlashingKeeper = slashingkeeper.NewKeeper(
appCodec, keys[slashingtypes.StoreKey], &stakingKeeper, app.GetSubspace(slashingtypes.ModuleName),
)
app.CrisisKeeper = crisiskeeper.NewKeeper(
app.GetSubspace(crisistypes.ModuleName), invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName,
)
app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper)
app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath, app.BaseApp)
// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
app.StakingKeeper = *stakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()),
)
// ... other modules keepers
// Create IBC Keeper
app.IBCKeeper = ibckeeper.NewKeeper(
appCodec, keys[ibchost.StoreKey], app.GetSubspace(ibchost.ModuleName), app.StakingKeeper, app.UpgradeKeeper, scopedIBCKeeper,
)
// register the proposal types
govRouter := govtypes.NewRouter()
govRouter.AddRoute(govtypes.RouterKey, govtypes.ProposalHandler).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)).
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)).
AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper))
// Create Transfer Keepers
app.TransferKeeper = ibctransferkeeper.NewKeeper(
appCodec, keys[ibctransfertypes.StoreKey], app.GetSubspace(ibctransfertypes.ModuleName),
app.IBCKeeper.ChannelKeeper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper,
app.AccountKeeper, app.BankKeeper, scopedTransferKeeper,
)
var (
transferModule = transfer.NewAppModule(app.TransferKeeper)
transferIBCModule = transfer.NewIBCModule(app.TransferKeeper)
)
// Create evidence Keeper for to register the IBC light client misbehaviour evidence route
evidenceKeeper := evidencekeeper.NewKeeper(
appCodec, keys[evidencetypes.StoreKey], &app.StakingKeeper, app.SlashingKeeper,
)
// If evidence needs to be handled for the app, set routes in router here and seal
app.EvidenceKeeper = *evidenceKeeper
app.GovKeeper = govkeeper.NewKeeper(
appCodec, keys[govtypes.StoreKey], app.GetSubspace(govtypes.ModuleName), app.AccountKeeper, app.BankKeeper,
&stakingKeeper, govRouter,
)
scopedMonitoringKeeper := app.CapabilityKeeper.ScopeToModule(monitoringptypes.ModuleName)
app.MonitoringKeeper = *monitoringpkeeper.NewKeeper(
appCodec,
keys[monitoringptypes.StoreKey],
keys[monitoringptypes.MemStoreKey],
app.GetSubspace(monitoringptypes.ModuleName),
app.StakingKeeper,
app.IBCKeeper.ClientKeeper,
app.IBCKeeper.ConnectionKeeper,
app.IBCKeeper.ChannelKeeper,
&app.IBCKeeper.PortKeeper,
scopedMonitoringKeeper,
)
monitoringModule := monitoringp.NewAppModule(appCodec, app.MonitoringKeeper)
app.CosmostestKeeper = *cosmostestmodulekeeper.NewKeeper(
appCodec,
keys[cosmostestmoduletypes.StoreKey],
keys[cosmostestmoduletypes.MemStoreKey],
app.GetSubspace(cosmostestmoduletypes.ModuleName),
)
cosmostestModule := cosmostestmodule.NewAppModule(appCodec, app.CosmostestKeeper, app.AccountKeeper, app.BankKeeper)
// this line is used by starport scaffolding # stargate/app/keeperDefinition
// Create static IBC router, add transfer route, then set and seal it
ibcRouter := ibcporttypes.NewRouter()
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferIBCModule)
ibcRouter.AddRoute(monitoringptypes.ModuleName, monitoringModule)
// this line is used by starport scaffolding # ibc/app/router
app.IBCKeeper.SetRouter(ibcRouter)
/**** Module Options ****/
// NOTE: we may consider parsing `appOpts` inside module constructors. For the moment
// we prefer to be more strict in what arguments the modules expect.
var skipGenesisInvariants = cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants))
// NOTE: Any module instantiated in the module manager that is later modified
// must be passed by reference here.
app.mm = module.NewManager(
genutil.NewAppModule(
app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx,
encodingConfig.TxConfig,
),
auth.NewAppModule(appCodec, app.AccountKeeper, nil),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
vesting.NewAppModule(app.AccountKeeper, app.BankKeeper),
bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper),
capability.NewAppModule(appCodec, *app.CapabilityKeeper),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper),
upgrade.NewAppModule(app.UpgradeKeeper),
evidence.NewAppModule(app.EvidenceKeeper),
ibc.NewAppModule(app.IBCKeeper),
params.NewAppModule(app.ParamsKeeper),
transferModule,
monitoringModule,
cosmostestModule,
// this line is used by starport scaffolding # stargate/app/appModule
)
// 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
app.mm.SetOrderBeginBlockers(
upgradetypes.ModuleName,
capabilitytypes.ModuleName,
minttypes.ModuleName,
distrtypes.ModuleName,
slashingtypes.ModuleName,
evidencetypes.ModuleName,
stakingtypes.ModuleName,
vestingtypes.ModuleName,
ibchost.ModuleName,
ibctransfertypes.ModuleName,
authtypes.ModuleName,
authz.ModuleName,
banktypes.ModuleName,
govtypes.ModuleName,
crisistypes.ModuleName,
genutiltypes.ModuleName,
feegrant.ModuleName,
paramstypes.ModuleName,
monitoringptypes.ModuleName,
cosmostestmoduletypes.ModuleName,
// this line is used by starport scaffolding # stargate/app/beginBlockers
)
app.mm.SetOrderEndBlockers(
crisistypes.ModuleName,
govtypes.ModuleName,
stakingtypes.ModuleName,
capabilitytypes.ModuleName,
authtypes.ModuleName,
authz.ModuleName,
banktypes.ModuleName,
distrtypes.ModuleName,
slashingtypes.ModuleName,
vestingtypes.ModuleName,
minttypes.ModuleName,
genutiltypes.ModuleName,
evidencetypes.ModuleName,
feegrant.ModuleName,
paramstypes.ModuleName,
upgradetypes.ModuleName,
ibchost.ModuleName,
ibctransfertypes.ModuleName,
monitoringptypes.ModuleName,
cosmostestmoduletypes.ModuleName,
// this line is used by starport scaffolding # stargate/app/endBlockers
)
// NOTE: The genutils module must occur after staking so that pools are
// properly initialized with tokens from genesis accounts.
// 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(
capabilitytypes.ModuleName,
authtypes.ModuleName,
authz.ModuleName,
banktypes.ModuleName,
distrtypes.ModuleName,
stakingtypes.ModuleName,
vestingtypes.ModuleName,
slashingtypes.ModuleName,
govtypes.ModuleName,
minttypes.ModuleName,
crisistypes.ModuleName,
ibchost.ModuleName,
genutiltypes.ModuleName,
evidencetypes.ModuleName,
paramstypes.ModuleName,
upgradetypes.ModuleName,
ibctransfertypes.ModuleName,
feegrant.ModuleName,
monitoringptypes.ModuleName,
cosmostestmoduletypes.ModuleName,
// this line is used by starport scaffolding # stargate/app/initGenesis
)
app.mm.RegisterInvariants(&app.CrisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.mm.RegisterServices(module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()))
// create the simulation manager and define the order of the modules for deterministic simulations
app.sm = module.NewSimulationManager(
auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper),
capability.NewAppModule(appCodec, *app.CapabilityKeeper),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
params.NewAppModule(app.ParamsKeeper),
evidence.NewAppModule(app.EvidenceKeeper),
ibc.NewAppModule(app.IBCKeeper),
transferModule,
monitoringModule,
cosmostestModule,
// this line is used by starport scaffolding # stargate/app/appModule
)
app.sm.RegisterStoreDecoders()
// initialize stores
app.MountKVStores(keys)
app.MountTransientStores(tkeys)
app.MountMemoryStores(memKeys)
// initialize BaseApp
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
anteHandler, err := ante.NewAnteHandler(
ante.HandlerOptions{
AccountKeeper: app.AccountKeeper,
BankKeeper: app.BankKeeper,
SignModeHandler: encodingConfig.TxConfig.SignModeHandler(),
FeegrantKeeper: app.FeeGrantKeeper,
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
},
)
if err != nil {
panic(err)
}
app.SetAnteHandler(anteHandler)
app.SetEndBlocker(app.EndBlocker)
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
tmos.Exit(err.Error())
}
}
app.ScopedIBCKeeper = scopedIBCKeeper
app.ScopedTransferKeeper = scopedTransferKeeper
app.ScopedMonitoringKeeper = scopedMonitoringKeeper
// this line is used by starport scaffolding # stargate/app/beforeInitReturn
return app
}
// Name returns the name of the App
func (app *App) Name() string { return app.BaseApp.Name() }
// GetBaseApp returns the base app of the application
func (app App) GetBaseApp() *baseapp.BaseApp { return app.BaseApp }
// BeginBlocker application updates every begin block
func (app *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
return app.mm.BeginBlock(ctx, req)
}
// EndBlocker application updates every end block
func (app *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
return app.mm.EndBlock(ctx, req)
}
// InitChainer application update at chain initialization
func (app *App) 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 *App) LoadHeight(height int64) error {
return app.LoadVersion(height)
}
// ModuleAccountAddrs returns all the app's module account addresses.
func (app *App) ModuleAccountAddrs() map[string]bool {
modAccAddrs := make(map[string]bool)
for acc := range maccPerms {
modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true
}
return modAccAddrs
}
// LegacyAmino returns SimApp'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 *App) LegacyAmino() *codec.LegacyAmino {
return app.cdc
}
// AppCodec returns an 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 *App) AppCodec() codec.Codec {
return app.appCodec
}
// InterfaceRegistry returns an InterfaceRegistry
func (app *App) InterfaceRegistry() types.InterfaceRegistry {
return app.interfaceRegistry
}
// GetKey returns the KVStoreKey for the provided store key.
//
// NOTE: This is solely to be used for testing purposes.
func (app *App) GetKey(storeKey string) *sdk.KVStoreKey {
return app.keys[storeKey]
}
// GetTKey returns the TransientStoreKey for the provided store key.
//
// NOTE: This is solely to be used for testing purposes.
func (app *App) GetTKey(storeKey string) *sdk.TransientStoreKey {
return app.tkeys[storeKey]
}
// GetMemKey returns the MemStoreKey for the provided mem key.
//
// NOTE: This is solely used for testing purposes.
func (app *App) GetMemKey(storeKey string) *sdk.MemoryStoreKey {
return app.memKeys[storeKey]
}
// GetSubspace returns a param subspace for a given module name.
//
// NOTE: This is solely to be used for testing purposes.
func (app *App) GetSubspace(moduleName string) paramstypes.Subspace {
subspace, _ := app.ParamsKeeper.GetSubspace(moduleName)
return subspace
}
// RegisterAPIRoutes registers all application module routes with the provided
// API server.
func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) {
clientCtx := apiSvr.ClientCtx
rpc.RegisterRoutes(clientCtx, apiSvr.Router)
// Register legacy tx routes.
authrest.RegisterTxRoutes(clientCtx, apiSvr.Router)
// 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)
// Register legacy and grpc-gateway routes for all modules.
ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router)
ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// register app's OpenAPI routes.
apiSvr.Router.Handle("/static/openapi.yml", http.FileServer(http.FS(docs.Docs)))
apiSvr.Router.HandleFunc("/", openapiconsole.Handler(Name, "/static/openapi.yml"))
}
// RegisterTxService implements the Application.RegisterTxService method.
func (app *App) RegisterTxService(clientCtx client.Context) {
authtx.RegisterTxService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.BaseApp.Simulate, app.interfaceRegistry)
}
// RegisterTendermintService implements the Application.RegisterTendermintService method.
func (app *App) RegisterTendermintService(clientCtx client.Context) {
tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry)
}
// GetMaccPerms returns a copy of the module account permissions
func GetMaccPerms() map[string][]string {
dupMaccPerms := make(map[string][]string)
for k, v := range maccPerms {
dupMaccPerms[k] = v
}
return dupMaccPerms
}
// initParamsKeeper init params keeper and its subspaces
func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper {
paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey)
paramsKeeper.Subspace(authtypes.ModuleName)
paramsKeeper.Subspace(banktypes.ModuleName)
paramsKeeper.Subspace(stakingtypes.ModuleName)
paramsKeeper.Subspace(minttypes.ModuleName)
paramsKeeper.Subspace(distrtypes.ModuleName)
paramsKeeper.Subspace(slashingtypes.ModuleName)
paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable())
paramsKeeper.Subspace(crisistypes.ModuleName)
paramsKeeper.Subspace(ibctransfertypes.ModuleName)
paramsKeeper.Subspace(ibchost.ModuleName)
paramsKeeper.Subspace(monitoringptypes.ModuleName)
paramsKeeper.Subspace(cosmostestmoduletypes.ModuleName)
// this line is used by starport scaffolding # stargate/app/paramSubspace
return paramsKeeper
}
// SimulationManager implements the SimulationApp interface
func (app *App) SimulationManager() *module.SimulationManager {
return app.sm
}

185
app/export.go Normal file
View File

@ -0,0 +1,185 @@
package app
import (
"encoding/json"
"log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// ExportAppStateAndValidators exports the state of the application for a genesis
// file.
func (app *App) ExportAppStateAndValidators(
forZeroHeight bool, jailAllowedAddrs []string,
) (servertypes.ExportedApp, error) {
// as if they could withdraw from the start of the next block
ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})
// We export at last height + 1, because that's the height at which
// Tendermint will start InitChain.
height := app.LastBlockHeight() + 1
if forZeroHeight {
height = 0
app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs)
}
genState := app.mm.ExportGenesis(ctx, app.appCodec)
appState, err := json.MarshalIndent(genState, "", " ")
if err != nil {
return servertypes.ExportedApp{}, err
}
validators, err := staking.WriteValidators(ctx, app.StakingKeeper)
if err != nil {
return servertypes.ExportedApp{}, err
}
return servertypes.ExportedApp{
AppState: appState,
Validators: validators,
Height: height,
ConsensusParams: app.BaseApp.GetConsensusParams(ctx),
}, nil
}
// prepare for fresh start at zero height
// NOTE zero height genesis is a temporary feature which will be deprecated
// in favour of export at a block height
func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) {
applyAllowedAddrs := false
// check if there is a allowed address list
if len(jailAllowedAddrs) > 0 {
applyAllowedAddrs = true
}
allowedAddrsMap := make(map[string]bool)
for _, addr := range jailAllowedAddrs {
_, err := sdk.ValAddressFromBech32(addr)
if err != nil {
log.Fatal(err)
}
allowedAddrsMap[addr] = true
}
/* Just to be safe, assert the invariants on current state. */
app.CrisisKeeper.AssertInvariants(ctx)
/* Handle fee distribution state. */
// withdraw all validator commission
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
_, err := app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator())
if err != nil {
panic(err)
}
return false
})
// withdraw all delegator rewards
dels := app.StakingKeeper.GetAllDelegations(ctx)
for _, delegation := range dels {
_, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, delegation.GetDelegatorAddr(), delegation.GetValidatorAddr())
if err != nil {
panic(err)
}
}
// clear validator slash events
app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx)
// clear validator historical rewards
app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
// set context height to zero
height := ctx.BlockHeight()
ctx = ctx.WithBlockHeight(0)
// reinitialize all validators
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
// donate any unwithdrawn outstanding reward fraction tokens to the community pool
scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator())
feePool := app.DistrKeeper.GetFeePool(ctx)
feePool.CommunityPool = feePool.CommunityPool.Add(scraps...)
app.DistrKeeper.SetFeePool(ctx, feePool)
app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator())
return false
})
// reinitialize all delegations
for _, del := range dels {
app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr())
app.DistrKeeper.Hooks().AfterDelegationModified(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr())
}
// reset context height
ctx = ctx.WithBlockHeight(height)
/* Handle staking state. */
// iterate through redelegations, reset creation height
app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) {
for i := range red.Entries {
red.Entries[i].CreationHeight = 0
}
app.StakingKeeper.SetRedelegation(ctx, red)
return false
})
// iterate through unbonding delegations, reset creation height
app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) {
for i := range ubd.Entries {
ubd.Entries[i].CreationHeight = 0
}
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
return false
})
// Iterate through validators by power descending, reset bond heights, and
// update bond intra-tx counters.
store := ctx.KVStore(app.keys[stakingtypes.StoreKey])
iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey)
counter := int16(0)
for ; iter.Valid(); iter.Next() {
addr := sdk.ValAddress(iter.Key()[1:])
validator, found := app.StakingKeeper.GetValidator(ctx, addr)
if !found {
panic("expected validator, not found")
}
validator.UnbondingHeight = 0
if applyAllowedAddrs && !allowedAddrsMap[addr.String()] {
validator.Jailed = true
}
app.StakingKeeper.SetValidator(ctx, validator)
counter++
}
iter.Close()
if _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx); err != nil {
panic(err)
}
/* Handle slashing state. */
// reset start height on signing infos
app.SlashingKeeper.IterateValidatorSigningInfos(
ctx,
func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) {
info.StartHeight = 0
app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info)
return false
},
)
}

21
app/genesis.go Normal file
View File

@ -0,0 +1,21 @@
package app
import (
"encoding/json"
"github.com/cosmos/cosmos-sdk/codec"
)
// The genesis state of the blockchain is represented here as a map of raw json
// messages key'd by a identifier string.
// The identifier is used to determine which module genesis information belongs
// to so it may be appropriately routed during init chain.
// Within this application default genesis information is retrieved from
// the ModuleBasicManager which populates json from each BasicModule
// object provided to it during init.
type GenesisState map[string]json.RawMessage
// NewDefaultGenesisState generates the default state for the application.
func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState {
return ModuleBasics.DefaultGenesis(cdc)
}

113
app/simulation_test.go Normal file
View File

@ -0,0 +1,113 @@
package app_test
import (
"os"
"testing"
"time"
"cosmos-test/app"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
simulationtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/simulation"
"github.com/ignite/cli/ignite/pkg/cosmoscmd"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtypes "github.com/tendermint/tendermint/types"
)
func init() {
simapp.GetSimulatorFlags()
}
type SimApp interface {
cosmoscmd.App
GetBaseApp() *baseapp.BaseApp
AppCodec() codec.Codec
SimulationManager() *module.SimulationManager
ModuleAccountAddrs() map[string]bool
Name() string
LegacyAmino() *codec.LegacyAmino
BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock
EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock
InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain
}
var defaultConsensusParams = &abci.ConsensusParams{
Block: &abci.BlockParams{
MaxBytes: 200000,
MaxGas: 2000000,
},
Evidence: &tmproto.EvidenceParams{
MaxAgeNumBlocks: 302400,
MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration
MaxBytes: 10000,
},
Validator: &tmproto.ValidatorParams{
PubKeyTypes: []string{
tmtypes.ABCIPubKeyTypeEd25519,
},
},
}
// BenchmarkSimulation run the chain simulation
// Running using starport command:
// `starport chain simulate -v --numBlocks 200 --blockSize 50`
// Running as go benchmark test:
// `go test -benchmem -run=^$ -bench ^BenchmarkSimulation ./app -NumBlocks=200 -BlockSize 50 -Commit=true -Verbose=true -Enabled=true`
func BenchmarkSimulation(b *testing.B) {
simapp.FlagEnabledValue = true
simapp.FlagCommitValue = true
config, db, dir, logger, _, err := simapp.SetupSimulation("goleveldb-app-sim", "Simulation")
require.NoError(b, err, "simulation setup failed")
b.Cleanup(func() {
db.Close()
err = os.RemoveAll(dir)
require.NoError(b, err)
})
encoding := cosmoscmd.MakeEncodingConfig(app.ModuleBasics)
app := app.New(
logger,
db,
nil,
true,
map[int64]bool{},
app.DefaultNodeHome,
0,
encoding,
simapp.EmptyAppOptions{},
)
simApp, ok := app.(SimApp)
require.True(b, ok, "can't use simapp")
// Run randomized simulations
_, simParams, simErr := simulation.SimulateFromSeed(
b,
os.Stdout,
simApp.GetBaseApp(),
simapp.AppStateFn(simApp.AppCodec(), simApp.SimulationManager()),
simulationtypes.RandomAccounts,
simapp.SimulationOperations(simApp, simApp.AppCodec(), config),
simApp.ModuleAccountAddrs(),
config,
simApp.AppCodec(),
)
// export state and simParams before the simulation error is checked
err = simapp.CheckExportSimulation(simApp, config, simParams)
require.NoError(b, err)
require.NoError(b, simErr)
if config.Commit {
simapp.PrintStats(db)
}
}

24
cmd/cosmos-testd/main.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"os"
"cosmos-test/app"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
"github.com/ignite/cli/ignite/pkg/cosmoscmd"
)
func main() {
rootCmd, _ := cosmoscmd.NewRootCmd(
app.Name,
app.AccountAddressPrefix,
app.DefaultNodeHome,
app.Name,
app.ModuleBasics,
app.New,
// this line is used by starport scaffolding # root/arguments
)
if err := svrcmd.Execute(rootCmd, app.DefaultNodeHome); err != nil {
os.Exit(1)
}
}

16
config.yml Normal file
View File

@ -0,0 +1,16 @@
accounts:
- name: alice
coins: ["20000token", "200000000stake"]
- name: bob
coins: ["10000token", "100000000stake"]
validator:
name: alice
staked: "100000000stake"
client:
openapi:
path: "docs/static/openapi.yml"
vuex:
path: "vue/src/store"
faucet:
name: bob
coins: ["5token", "100000stake"]

6
docs/docs.go Normal file
View File

@ -0,0 +1,6 @@
package docs
import "embed"
//go:embed static
var Docs embed.FS

51824
docs/static/openapi.yml vendored Normal file

File diff suppressed because it is too large Load Diff

178
go.mod Normal file
View File

@ -0,0 +1,178 @@
module cosmos-test
go 1.18
require (
github.com/cosmos/cosmos-sdk v0.45.5
github.com/cosmos/ibc-go/v3 v3.0.1
github.com/gogo/protobuf v1.3.3
github.com/golang/protobuf v1.5.2
github.com/gorilla/mux v1.8.0
github.com/grpc-ecosystem/grpc-gateway v1.16.0
github.com/ignite/cli v0.23.0
github.com/spf13/cast v1.4.1
github.com/spf13/cobra v1.4.0
github.com/stretchr/testify v1.7.1
github.com/tendermint/spn v0.2.1-0.20220708132853-26a17f03c072
github.com/tendermint/tendermint v0.34.19
github.com/tendermint/tm-db v0.6.7
google.golang.org/genproto v0.0.0-20220822174746-9e6da59bd2fc
google.golang.org/grpc v1.48.0
gopkg.in/yaml.v2 v2.4.0
)
require (
filippo.io/edwards25519 v1.0.0-beta.2 // indirect
github.com/99designs/keyring v1.1.6 // indirect
github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect
github.com/DataDog/zstd v1.4.5 // indirect
github.com/Microsoft/go-winio v0.5.1 // indirect
github.com/Microsoft/hcsshim v0.9.2 // indirect
github.com/Workiva/go-datastructures v1.0.53 // indirect
github.com/andrew-d/go-termutil v0.0.0-20150726205930-009166a695a2 // indirect
github.com/armon/go-metrics v0.3.10 // indirect
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/blang/semver v3.5.1+incompatible // indirect
github.com/btcsuite/btcd v0.22.0-beta // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cenkalti/backoff v2.2.1+incompatible // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect
github.com/confio/ics23/go v0.7.0 // indirect
github.com/containerd/cgroups v1.0.3 // indirect
github.com/containerd/containerd v1.6.2 // indirect
github.com/cosmos/btcutil v1.0.4 // indirect
github.com/cosmos/go-bip39 v1.0.0 // indirect
github.com/cosmos/gorocksdb v1.2.0 // indirect
github.com/cosmos/iavl v0.17.3 // indirect
github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect
github.com/cosmos/ledger-go v0.9.2 // indirect
github.com/danieljoos/wincred v1.0.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect
github.com/dgraph-io/badger/v2 v2.2007.2 // indirect
github.com/dgraph-io/ristretto v0.0.3 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/docker/docker v20.10.7+incompatible // indirect
github.com/docker/go-units v0.4.0 // indirect
github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac // indirect
github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect
github.com/emicklei/proto v1.9.0 // indirect
github.com/emirpasic/gods v1.12.0 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/felixge/httpsnoop v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/go-git/gcfg v1.5.0 // indirect
github.com/go-git/go-billy/v5 v5.0.0 // indirect
github.com/go-git/go-git/v5 v5.1.0 // indirect
github.com/go-kit/kit v0.12.0 // indirect
github.com/go-kit/log v0.2.0 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/goccy/go-yaml v1.9.4 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gogo/gateway v1.1.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/snappy v0.0.3 // indirect
github.com/google/btree v1.0.0 // indirect
github.com/google/orderedcode v0.0.1 // indirect
github.com/gookit/color v1.5.0 // indirect
github.com/gorilla/handlers v1.5.1 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/gtank/merlin v0.1.1 // indirect
github.com/gtank/ristretto255 v0.1.2 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/improbable-eng/grpc-web v0.14.1 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/jpillora/ansi v1.0.2 // indirect
github.com/jpillora/backoff v1.0.0 // indirect
github.com/jpillora/chisel v1.7.7 // indirect
github.com/jpillora/requestlog v1.0.0 // indirect
github.com/jpillora/sizestr v1.0.0 // indirect
github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd // indirect
github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/lib/pq v1.10.4 // indirect
github.com/libp2p/go-buffer-pool v0.0.2 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mattn/go-zglob v0.0.3 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect
github.com/minio/highwayhash v1.0.2 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/moby/sys/mount v0.3.1 // indirect
github.com/moby/sys/mountinfo v0.6.0 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.2 // indirect
github.com/opencontainers/runc v1.1.0 // indirect
github.com/otiai10/copy v1.6.0 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.12.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/radovskyb/watcher v1.0.7 // indirect
github.com/rakyll/statik v0.1.7 // indirect
github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect
github.com/regen-network/cosmos-proto v0.3.1 // indirect
github.com/rs/cors v1.8.2 // indirect
github.com/rs/zerolog v1.26.1 // indirect
github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa // indirect
github.com/sergi/go-diff v1.1.0 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/spf13/afero v1.8.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.10.1 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca // indirect
github.com/takuoki/gocase v1.0.0 // indirect
github.com/tendermint/btcd v0.1.1 // indirect
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // indirect
github.com/tendermint/fundraising v0.3.1-0.20220613014523-03b4a2d4481a // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce // indirect
github.com/xanzy/ssh-agent v0.2.1 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
github.com/zondax/hid v0.9.0 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
go.opencensus.io v0.23.0 // indirect
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce // indirect
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect
golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.66.3 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.6 // indirect
)
replace (
github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1
github.com/keybase/go-keychain => github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4
google.golang.org/grpc => google.golang.org/grpc v1.33.2
)

2064
go.sum Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
syntax = "proto3";
package cosmostest.cosmostest;
import "gogoproto/gogo.proto";
import "cosmostest/params.proto";
// this line is used by starport scaffolding # genesis/proto/import
option go_package = "cosmos-test/x/cosmostest/types";
// GenesisState defines the cosmostest module's genesis state.
message GenesisState {
Params params = 1 [(gogoproto.nullable) = false];
// this line is used by starport scaffolding # genesis/proto/state
}

View File

@ -0,0 +1,12 @@
syntax = "proto3";
package cosmostest.cosmostest;
import "gogoproto/gogo.proto";
option go_package = "cosmos-test/x/cosmostest/types";
// Params defines the parameters for the module.
message Params {
option (gogoproto.goproto_stringer) = false;
}

View File

@ -0,0 +1,30 @@
syntax = "proto3";
package cosmostest.cosmostest;
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "cosmostest/params.proto";
// this line is used by starport scaffolding # 1
option go_package = "cosmos-test/x/cosmostest/types";
// Query defines the gRPC querier service.
service Query {
// Parameters queries the parameters of the module.
rpc Params(QueryParamsRequest) returns (QueryParamsResponse) {
option (google.api.http).get = "/cosmos-test/cosmostest/params";
}
// this line is used by starport scaffolding # 2
}
// QueryParamsRequest is request type for the Query/Params RPC method.
message QueryParamsRequest {}
// QueryParamsResponse is response type for the Query/Params RPC method.
message QueryParamsResponse {
// params holds all the parameters of this module.
Params params = 1 [(gogoproto.nullable) = false];
}
// this line is used by starport scaffolding # 3

13
proto/cosmostest/tx.proto Normal file
View File

@ -0,0 +1,13 @@
syntax = "proto3";
package cosmostest.cosmostest;
// this line is used by starport scaffolding # proto/tx/import
option go_package = "cosmos-test/x/cosmostest/types";
// Msg defines the Msg service.
service Msg {
// this line is used by starport scaffolding # proto/tx/rpc
}
// this line is used by starport scaffolding # proto/tx/message

52
readme.md Normal file
View File

@ -0,0 +1,52 @@
# cosmostest
**cosmostest** is a blockchain built using Cosmos SDK and Tendermint and created with [Ignite CLI](https://ignite.com/cli).
## Get started
```
ignite chain serve
```
`serve` command installs dependencies, builds, initializes, and starts your blockchain in development.
### Configure
Your blockchain in development can be configured with `config.yml`. To learn more, see the [Ignite CLI docs](https://docs.ignite.com).
### Web Frontend
Ignite CLI has scaffolded a Vue.js-based web app in the `vue` directory. Run the following commands to install dependencies and start the app:
```
cd vue
npm install
npm run serve
```
The frontend app is built using the `@starport/vue` and `@starport/vuex` packages. For details, see the [monorepo for Ignite front-end development](https://github.com/ignite/web).
## Release
To release a new version of your blockchain, create and push a new tag with `v` prefix. A new draft release with the configured targets will be created.
```
git tag v0.1
git push origin v0.1
```
After a draft release is created, make your final changes from the release page and publish it.
### Install
To install the latest version of your blockchain node's binary, execute the following command on your machine:
```
curl https://get.ignite.com/username/cosmos-test@latest! | sudo bash
```
`username/cosmos-test` should match the `username` and `repo_name` of the Github repository to which the source code was pushed. Learn more about [the install process](https://github.com/allinbits/starport-installer).
## Learn more
- [Ignite CLI](https://ignite.com/cli)
- [Tutorials](https://docs.ignite.com/guide)
- [Ignite CLI docs](https://docs.ignite.com)
- [Cosmos SDK docs](https://docs.cosmos.network)
- [Developer Chat](https://discord.gg/ignite)

View File

@ -0,0 +1,52 @@
package keeper
import (
"testing"
"cosmos-test/x/cosmostest/keeper"
"cosmos-test/x/cosmostest/types"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/store"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
typesparams "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmdb "github.com/tendermint/tm-db"
)
func CosmostestKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) {
storeKey := sdk.NewKVStoreKey(types.StoreKey)
memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey)
db := tmdb.NewMemDB()
stateStore := store.NewCommitMultiStore(db)
stateStore.MountStoreWithDB(storeKey, sdk.StoreTypeIAVL, db)
stateStore.MountStoreWithDB(memStoreKey, sdk.StoreTypeMemory, nil)
require.NoError(t, stateStore.LoadLatestVersion())
registry := codectypes.NewInterfaceRegistry()
cdc := codec.NewProtoCodec(registry)
paramsSubspace := typesparams.NewSubspace(cdc,
types.Amino,
storeKey,
memStoreKey,
"CosmostestParams",
)
k := keeper.NewKeeper(
cdc,
storeKey,
memStoreKey,
paramsSubspace,
)
ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger())
// Initialize params
k.SetParams(ctx, types.DefaultParams())
return k, ctx
}

View File

@ -0,0 +1,79 @@
package network
import (
"fmt"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
"github.com/cosmos/cosmos-sdk/testutil/network"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/ignite/cli/ignite/pkg/cosmoscmd"
tmrand "github.com/tendermint/tendermint/libs/rand"
tmdb "github.com/tendermint/tm-db"
"cosmos-test/app"
)
type (
Network = network.Network
Config = network.Config
)
// New creates instance with fully configured cosmos network.
// Accepts optional config, that will be used in place of the DefaultConfig() if provided.
func New(t *testing.T, configs ...network.Config) *network.Network {
if len(configs) > 1 {
panic("at most one config should be provided")
}
var cfg network.Config
if len(configs) == 0 {
cfg = DefaultConfig()
} else {
cfg = configs[0]
}
net := network.New(t, cfg)
t.Cleanup(net.Cleanup)
return net
}
// DefaultConfig will initialize config for the network with custom application,
// genesis and single validator. All other parameters are inherited from cosmos-sdk/testutil/network.DefaultConfig
func DefaultConfig() network.Config {
encoding := cosmoscmd.MakeEncodingConfig(app.ModuleBasics)
return network.Config{
Codec: encoding.Marshaler,
TxConfig: encoding.TxConfig,
LegacyAmino: encoding.Amino,
InterfaceRegistry: encoding.InterfaceRegistry,
AccountRetriever: authtypes.AccountRetriever{},
AppConstructor: func(val network.Validator) servertypes.Application {
return app.New(
val.Ctx.Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.Ctx.Config.RootDir, 0,
encoding,
simapp.EmptyAppOptions{},
baseapp.SetPruning(storetypes.NewPruningOptionsFromString(val.AppConfig.Pruning)),
baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices),
)
},
GenesisState: app.ModuleBasics.DefaultGenesis(encoding.Marshaler),
TimeoutCommit: 2 * time.Second,
ChainID: "chain-" + tmrand.NewRand().Str(6),
NumValidators: 1,
BondDenom: sdk.DefaultBondDenom,
MinGasPrices: fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom),
AccountTokens: sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction),
StakingTokens: sdk.TokensFromConsensusPower(500, sdk.DefaultPowerReduction),
BondedTokens: sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction),
PruningStrategy: storetypes.PruningOptionNothing,
CleanupDir: true,
SigningAlgo: string(hd.Secp256k1Type),
KeyringOptions: []keyring.Option{},
}
}

View File

@ -0,0 +1,57 @@
// Package nullify provides methods to init nil values structs for test assertion.
package nullify
import (
"reflect"
"unsafe"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var (
coinType = reflect.TypeOf(sdk.Coin{})
coinsType = reflect.TypeOf(sdk.Coins{})
)
// Fill analyze all struct fields and slices with
// reflection and initialize the nil and empty slices,
// structs, and pointers.
func Fill(x interface{}) interface{} {
v := reflect.Indirect(reflect.ValueOf(x))
switch v.Kind() {
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
obj := v.Index(i)
objPt := reflect.NewAt(obj.Type(), unsafe.Pointer(obj.UnsafeAddr())).Interface()
objPt = Fill(objPt)
obj.Set(reflect.ValueOf(objPt))
}
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
f := reflect.Indirect(v.Field(i))
if !f.CanSet() {
continue
}
switch f.Kind() {
case reflect.Slice:
f.Set(reflect.MakeSlice(f.Type(), 0, 0))
case reflect.Struct:
switch f.Type() {
case coinType:
coin := reflect.New(coinType).Interface()
s := reflect.ValueOf(coin).Elem()
f.Set(s)
case coinsType:
coins := reflect.New(coinsType).Interface()
s := reflect.ValueOf(coins).Elem()
f.Set(s)
default:
objPt := reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Interface()
s := Fill(objPt)
f.Set(reflect.ValueOf(s))
}
}
}
}
return reflect.Indirect(v).Interface()
}

13
testutil/sample/sample.go Normal file
View File

@ -0,0 +1,13 @@
package sample
import (
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// AccAddress returns a sample account address
func AccAddress() string {
pk := ed25519.GenPrivKey().PubKey()
addr := pk.Address()
return sdk.AccAddress(addr).String()
}

25
vue/README.md Normal file
View File

@ -0,0 +1,25 @@
## App UI Template
[Vue.js](https://vuejs.org/)-based web app template for your Cosmos SDK blockchain. Use the template to quickly bootstrap your app. To learn more, check out the components in `@starport/vue` and the [Starport documentation](https://docs.starport.network/).
## Project setup
```
npm install
```
### Compiles and reloads the app on save for development
```
npm run dev
```
### Compiles and minifies for production
```
npm run build
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

19
vue/index.html Normal file
View File

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title> </title>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

3469
vue/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

34
vue/package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "@starport/template",
"version": "0.3.5",
"description": "A Vue 3 boilerplate project utilizing @starport/vue and @starport/vuex",
"author": "Tendermint, Inc <hello@tendermint.com>",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"dependencies": {
"@cosmjs/launchpad": "0.27.0",
"@cosmjs/proto-signing": "0.27.0",
"@cosmjs/stargate": "0.27.0",
"@starport/vue": "^0.3.5",
"@starport/vuex": "^0.3.5",
"buffer": "^6.0.3",
"core-js": "^3.18.2",
"vue": "^3.2.6",
"vue-router": "^4.0.3",
"vuex": "^4.0.2"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^21.0.1",
"@rollup/plugin-dynamic-import-vars": "^1.4.1",
"@rollup/plugin-node-resolve": "^13.1.1",
"@vitejs/plugin-vue": "^2.0.1",
"sass": "^1.47.0",
"vite": "^2.7.6",
"vite-plugin-dynamic-import": "^0.1.1",
"vite-plugin-env-compatible": "^1.1.1"
}
}

BIN
vue/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

60
vue/src/App.vue Normal file
View File

@ -0,0 +1,60 @@
<template>
<div>
<SpTheme>
<SpNavbar
:links="navbarLinks"
:active-route="router.currentRoute.value.path"
/>
<router-view />
</SpTheme>
</div>
</template>
<script lang="ts">
import { SpNavbar, SpTheme } from '@starport/vue'
import { computed, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
export default {
components: { SpTheme, SpNavbar },
setup() {
// store
let $s = useStore()
// router
let router = useRouter()
// state
let navbarLinks = [
{ name: 'Portfolio', url: '/portfolio' },
{ name: 'Data', url: '/data' }
]
// computed
let address = computed(() => $s.getters['common/wallet/address'])
// lh
onBeforeMount(async () => {
await $s.dispatch('common/env/init')
router.push('portfolio')
})
return {
navbarLinks,
// router
router,
// computed
address
}
}
}
</script>
<style scoped lang="scss">
body {
margin: 0;
}
</style>

9
vue/src/main.js Normal file
View File

@ -0,0 +1,9 @@
import starportLibrary from '@starport/vue'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const app = createApp(App)
app.use(store).use(router).use(starportLibrary).mount('#app')

18
vue/src/router/index.js Normal file
View File

@ -0,0 +1,18 @@
import { createRouter, createWebHistory } from 'vue-router'
import Data from '../views/Data.vue'
import Portfolio from '../views/Portfolio.vue'
const routerHistory = createWebHistory()
const routes = [
{ path: '/', component: Portfolio },
{ path: '/portfolio', component: Portfolio },
{ path: '/data', component: Data }
]
const router = createRouter({
history: routerHistory,
routes
})
export default router

11
vue/src/store/config.ts Normal file
View File

@ -0,0 +1,11 @@
import { blocks, env, wallet } from '@starport/vuex'
import generated from './generated'
export default function init(store) {
for (const moduleInit of Object.values(generated)) {
moduleInit(store)
}
blocks(store)
env(store)
wallet(store)
}

View File

@ -0,0 +1,141 @@
import { txClient, queryClient, MissingWalletError , registry} from './module'
import { Params } from "./module/types/cosmostest/params"
export { Params };
async function initTxClient(vuexGetters) {
return await txClient(vuexGetters['common/wallet/signer'], {
addr: vuexGetters['common/env/apiTendermint']
})
}
async function initQueryClient(vuexGetters) {
return await queryClient({
addr: vuexGetters['common/env/apiCosmos']
})
}
function mergeResults(value, next_values) {
for (let prop of Object.keys(next_values)) {
if (Array.isArray(next_values[prop])) {
value[prop]=[...value[prop], ...next_values[prop]]
}else{
value[prop]=next_values[prop]
}
}
return value
}
function getStructure(template) {
let structure = { fields: [] }
for (const [key, value] of Object.entries(template)) {
let field: any = {}
field.name = key
field.type = typeof value
structure.fields.push(field)
}
return structure
}
const getDefaultState = () => {
return {
Params: {},
_Structure: {
Params: getStructure(Params.fromPartial({})),
},
_Registry: registry,
_Subscriptions: new Set(),
}
}
// initial state
const state = getDefaultState()
export default {
namespaced: true,
state,
mutations: {
RESET_STATE(state) {
Object.assign(state, getDefaultState())
},
QUERY(state, { query, key, value }) {
state[query][JSON.stringify(key)] = value
},
SUBSCRIBE(state, subscription) {
state._Subscriptions.add(JSON.stringify(subscription))
},
UNSUBSCRIBE(state, subscription) {
state._Subscriptions.delete(JSON.stringify(subscription))
}
},
getters: {
getParams: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.Params[JSON.stringify(params)] ?? {}
},
getTypeStructure: (state) => (type) => {
return state._Structure[type].fields
},
getRegistry: (state) => {
return state._Registry
}
},
actions: {
init({ dispatch, rootGetters }) {
console.log('Vuex module: cosmostest.cosmostest initialized!')
if (rootGetters['common/env/client']) {
rootGetters['common/env/client'].on('newblock', () => {
dispatch('StoreUpdate')
})
}
},
resetState({ commit }) {
commit('RESET_STATE')
},
unsubscribe({ commit }, subscription) {
commit('UNSUBSCRIBE', subscription)
},
async StoreUpdate({ state, dispatch }) {
state._Subscriptions.forEach(async (subscription) => {
try {
const sub=JSON.parse(subscription)
await dispatch(sub.action, sub.payload)
}catch(e) {
throw new Error('Subscriptions: ' + e.message)
}
})
},
async QueryParams({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryParams()).data
commit('QUERY', { query: 'Params', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryParams', payload: { options: { all }, params: {...key},query }})
return getters['getParams']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryParams API Node Unavailable. Could not perform query: ' + e.message)
}
},
}
}

View File

@ -0,0 +1,57 @@
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT MODIFY.
import { StdFee } from "@cosmjs/launchpad";
import { SigningStargateClient } from "@cosmjs/stargate";
import { Registry, OfflineSigner, EncodeObject, DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { Api } from "./rest";
const types = [
];
export const MissingWalletError = new Error("wallet is required");
export const registry = new Registry(<any>types);
const defaultFee = {
amount: [],
gas: "200000",
};
interface TxClientOptions {
addr: string
}
interface SignAndBroadcastOptions {
fee: StdFee,
memo?: string
}
const txClient = async (wallet: OfflineSigner, { addr: addr }: TxClientOptions = { addr: "http://localhost:26657" }) => {
if (!wallet) throw MissingWalletError;
let client;
if (addr) {
client = await SigningStargateClient.connectWithSigner(addr, wallet, { registry });
}else{
client = await SigningStargateClient.offline( wallet, { registry });
}
const { address } = (await wallet.getAccounts())[0];
return {
signAndBroadcast: (msgs: EncodeObject[], { fee, memo }: SignAndBroadcastOptions = {fee: defaultFee, memo: ""}) => client.signAndBroadcast(address, msgs, fee,memo),
};
};
interface QueryClientOptions {
addr: string
}
const queryClient = async ({ addr: addr }: QueryClientOptions = { addr: "http://localhost:1317" }) => {
return new Api({ baseUrl: addr });
};
export {
txClient,
queryClient,
};

View File

@ -0,0 +1,247 @@
/* eslint-disable */
/* tslint:disable */
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
/**
* Params defines the parameters for the module.
*/
export type CosmostestParams = object;
/**
* QueryParamsResponse is response type for the Query/Params RPC method.
*/
export interface CosmostestQueryParamsResponse {
/** params holds all the parameters of this module. */
params?: CosmostestParams;
}
export interface ProtobufAny {
"@type"?: string;
}
export interface RpcStatus {
/** @format int32 */
code?: number;
message?: string;
details?: ProtobufAny[];
}
export type QueryParamsType = Record<string | number, any>;
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
export interface FullRequestParams extends Omit<RequestInit, "body"> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: keyof Omit<Body, "body" | "bodyUsed">;
/** request body */
body?: unknown;
/** base url */
baseUrl?: string;
/** request cancellation token */
cancelToken?: CancelToken;
}
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
export interface ApiConfig<SecurityDataType = unknown> {
baseUrl?: string;
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
securityWorker?: (securityData: SecurityDataType) => RequestParams | void;
}
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
data: D;
error: E;
}
type CancelToken = Symbol | string | number;
export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
}
export class HttpClient<SecurityDataType = unknown> {
public baseUrl: string = "";
private securityData: SecurityDataType = null as any;
private securityWorker: null | ApiConfig<SecurityDataType>["securityWorker"] = null;
private abortControllers = new Map<CancelToken, AbortController>();
private baseApiParams: RequestParams = {
credentials: "same-origin",
headers: {},
redirect: "follow",
referrerPolicy: "no-referrer",
};
constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
Object.assign(this, apiConfig);
}
public setSecurityData = (data: SecurityDataType) => {
this.securityData = data;
};
private addQueryParam(query: QueryParamsType, key: string) {
const value = query[key];
return (
encodeURIComponent(key) +
"=" +
encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`)
);
}
protected toQueryString(rawQuery?: QueryParamsType): string {
const query = rawQuery || {};
const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
return keys
.map((key) =>
typeof query[key] === "object" && !Array.isArray(query[key])
? this.toQueryString(query[key] as QueryParamsType)
: this.addQueryParam(query, key),
)
.join("&");
}
protected addQueryParams(rawQuery?: QueryParamsType): string {
const queryString = this.toQueryString(rawQuery);
return queryString ? `?${queryString}` : "";
}
private contentFormatters: Record<ContentType, (input: any) => any> = {
[ContentType.Json]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
[ContentType.FormData]: (input: any) =>
Object.keys(input || {}).reduce((data, key) => {
data.append(key, input[key]);
return data;
}, new FormData()),
[ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
};
private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
return {
...this.baseApiParams,
...params1,
...(params2 || {}),
headers: {
...(this.baseApiParams.headers || {}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
if (this.abortControllers.has(cancelToken)) {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
return abortController.signal;
}
return void 0;
}
const abortController = new AbortController();
this.abortControllers.set(cancelToken, abortController);
return abortController.signal;
};
public abortRequest = (cancelToken: CancelToken) => {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
abortController.abort();
this.abortControllers.delete(cancelToken);
}
};
public request = <T = any, E = any>({
body,
secure,
path,
type,
query,
format = "json",
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
...requestParams,
headers: {
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
...(requestParams.headers || {}),
},
signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
}).then(async (response) => {
const r = response as HttpResponse<T, E>;
r.data = (null as unknown) as T;
r.error = (null as unknown) as E;
const data = await response[format]()
.then((data) => {
if (r.ok) {
r.data = data;
} else {
r.error = data;
}
return r;
})
.catch((e) => {
r.error = e;
return r;
});
if (cancelToken) {
this.abortControllers.delete(cancelToken);
}
if (!response.ok) throw data;
return data;
});
};
}
/**
* @title cosmostest/genesis.proto
* @version version not set
*/
export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
/**
* No description
*
* @tags Query
* @name QueryParams
* @summary Parameters queries the parameters of the module.
* @request GET:/cosmos-test/cosmostest/params
*/
queryParams = (params: RequestParams = {}) =>
this.request<CosmostestQueryParamsResponse, RpcStatus>({
path: `/cosmos-test/cosmostest/params`,
method: "GET",
format: "json",
...params,
});
}

View File

@ -0,0 +1,300 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.base.query.v1beta1";
/**
* PageRequest is to be embedded in gRPC request messages for efficient
* pagination. Ex:
*
* message SomeRequest {
* Foo some_parameter = 1;
* PageRequest pagination = 2;
* }
*/
export interface PageRequest {
/**
* key is a value returned in PageResponse.next_key to begin
* querying the next page most efficiently. Only one of offset or key
* should be set.
*/
key: Uint8Array;
/**
* offset is a numeric offset that can be used when key is unavailable.
* It is less efficient than using key. Only one of offset or key should
* be set.
*/
offset: number;
/**
* limit is the total number of results to be returned in the result page.
* If left empty it will default to a value to be set by each app.
*/
limit: number;
/**
* count_total is set to true to indicate that the result set should include
* a count of the total number of items available for pagination in UIs.
* count_total is only respected when offset is used. It is ignored when key
* is set.
*/
count_total: boolean;
}
/**
* PageResponse is to be embedded in gRPC response messages where the
* corresponding request message has used PageRequest.
*
* message SomeResponse {
* repeated Bar results = 1;
* PageResponse page = 2;
* }
*/
export interface PageResponse {
/**
* next_key is the key to be passed to PageRequest.key to
* query the next page most efficiently
*/
next_key: Uint8Array;
/**
* total is total number of results available if PageRequest.count_total
* was set, its value is undefined otherwise
*/
total: number;
}
const basePageRequest: object = { offset: 0, limit: 0, count_total: false };
export const PageRequest = {
encode(message: PageRequest, writer: Writer = Writer.create()): Writer {
if (message.key.length !== 0) {
writer.uint32(10).bytes(message.key);
}
if (message.offset !== 0) {
writer.uint32(16).uint64(message.offset);
}
if (message.limit !== 0) {
writer.uint32(24).uint64(message.limit);
}
if (message.count_total === true) {
writer.uint32(32).bool(message.count_total);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageRequest } as PageRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.bytes();
break;
case 2:
message.offset = longToNumber(reader.uint64() as Long);
break;
case 3:
message.limit = longToNumber(reader.uint64() as Long);
break;
case 4:
message.count_total = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = bytesFromBase64(object.key);
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = Number(object.offset);
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = Number(object.limit);
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = Boolean(object.count_total);
} else {
message.count_total = false;
}
return message;
},
toJSON(message: PageRequest): unknown {
const obj: any = {};
message.key !== undefined &&
(obj.key = base64FromBytes(
message.key !== undefined ? message.key : new Uint8Array()
));
message.offset !== undefined && (obj.offset = message.offset);
message.limit !== undefined && (obj.limit = message.limit);
message.count_total !== undefined &&
(obj.count_total = message.count_total);
return obj;
},
fromPartial(object: DeepPartial<PageRequest>): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = new Uint8Array();
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = object.offset;
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = object.limit;
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = object.count_total;
} else {
message.count_total = false;
}
return message;
},
};
const basePageResponse: object = { total: 0 };
export const PageResponse = {
encode(message: PageResponse, writer: Writer = Writer.create()): Writer {
if (message.next_key.length !== 0) {
writer.uint32(10).bytes(message.next_key);
}
if (message.total !== 0) {
writer.uint32(16).uint64(message.total);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageResponse } as PageResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.next_key = reader.bytes();
break;
case 2:
message.total = longToNumber(reader.uint64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = bytesFromBase64(object.next_key);
}
if (object.total !== undefined && object.total !== null) {
message.total = Number(object.total);
} else {
message.total = 0;
}
return message;
},
toJSON(message: PageResponse): unknown {
const obj: any = {};
message.next_key !== undefined &&
(obj.next_key = base64FromBytes(
message.next_key !== undefined ? message.next_key : new Uint8Array()
));
message.total !== undefined && (obj.total = message.total);
return obj;
},
fromPartial(object: DeepPartial<PageResponse>): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = object.next_key;
} else {
message.next_key = new Uint8Array();
}
if (object.total !== undefined && object.total !== null) {
message.total = object.total;
} else {
message.total = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,78 @@
/* eslint-disable */
import { Params } from "../cosmostest/params";
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmostest.cosmostest";
/** GenesisState defines the cosmostest module's genesis state. */
export interface GenesisState {
/** this line is used by starport scaffolding # genesis/proto/state */
params: Params | undefined;
}
const baseGenesisState: object = {};
export const GenesisState = {
encode(message: GenesisState, writer: Writer = Writer.create()): Writer {
if (message.params !== undefined) {
Params.encode(message.params, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): GenesisState {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseGenesisState } as GenesisState;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.params = Params.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): GenesisState {
const message = { ...baseGenesisState } as GenesisState;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromJSON(object.params);
} else {
message.params = undefined;
}
return message;
},
toJSON(message: GenesisState): unknown {
const obj: any = {};
message.params !== undefined &&
(obj.params = message.params ? Params.toJSON(message.params) : undefined);
return obj;
},
fromPartial(object: DeepPartial<GenesisState>): GenesisState {
const message = { ...baseGenesisState } as GenesisState;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromPartial(object.params);
} else {
message.params = undefined;
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,56 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmostest.cosmostest";
/** Params defines the parameters for the module. */
export interface Params {}
const baseParams: object = {};
export const Params = {
encode(_: Params, writer: Writer = Writer.create()): Writer {
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Params {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseParams } as Params;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): Params {
const message = { ...baseParams } as Params;
return message;
},
toJSON(_: Params): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<Params>): Params {
const message = { ...baseParams } as Params;
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,152 @@
/* eslint-disable */
import { Reader, Writer } from "protobufjs/minimal";
import { Params } from "../cosmostest/params";
export const protobufPackage = "cosmostest.cosmostest";
/** QueryParamsRequest is request type for the Query/Params RPC method. */
export interface QueryParamsRequest {}
/** QueryParamsResponse is response type for the Query/Params RPC method. */
export interface QueryParamsResponse {
/** params holds all the parameters of this module. */
params: Params | undefined;
}
const baseQueryParamsRequest: object = {};
export const QueryParamsRequest = {
encode(_: QueryParamsRequest, writer: Writer = Writer.create()): Writer {
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryParamsRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryParamsRequest } as QueryParamsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): QueryParamsRequest {
const message = { ...baseQueryParamsRequest } as QueryParamsRequest;
return message;
},
toJSON(_: QueryParamsRequest): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<QueryParamsRequest>): QueryParamsRequest {
const message = { ...baseQueryParamsRequest } as QueryParamsRequest;
return message;
},
};
const baseQueryParamsResponse: object = {};
export const QueryParamsResponse = {
encode(
message: QueryParamsResponse,
writer: Writer = Writer.create()
): Writer {
if (message.params !== undefined) {
Params.encode(message.params, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryParamsResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryParamsResponse } as QueryParamsResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.params = Params.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): QueryParamsResponse {
const message = { ...baseQueryParamsResponse } as QueryParamsResponse;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromJSON(object.params);
} else {
message.params = undefined;
}
return message;
},
toJSON(message: QueryParamsResponse): unknown {
const obj: any = {};
message.params !== undefined &&
(obj.params = message.params ? Params.toJSON(message.params) : undefined);
return obj;
},
fromPartial(object: DeepPartial<QueryParamsResponse>): QueryParamsResponse {
const message = { ...baseQueryParamsResponse } as QueryParamsResponse;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromPartial(object.params);
} else {
message.params = undefined;
}
return message;
},
};
/** Query defines the gRPC querier service. */
export interface Query {
/** Parameters queries the parameters of the module. */
Params(request: QueryParamsRequest): Promise<QueryParamsResponse>;
}
export class QueryClientImpl implements Query {
private readonly rpc: Rpc;
constructor(rpc: Rpc) {
this.rpc = rpc;
}
Params(request: QueryParamsRequest): Promise<QueryParamsResponse> {
const data = QueryParamsRequest.encode(request).finish();
const promise = this.rpc.request(
"cosmostest.cosmostest.Query",
"Params",
data
);
return promise.then((data) => QueryParamsResponse.decode(new Reader(data)));
}
}
interface Rpc {
request(
service: string,
method: string,
data: Uint8Array
): Promise<Uint8Array>;
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,20 @@
/* eslint-disable */
export const protobufPackage = "cosmostest.cosmostest";
/** Msg defines the Msg service. */
export interface Msg {}
export class MsgClientImpl implements Msg {
private readonly rpc: Rpc;
constructor(rpc: Rpc) {
this.rpc = rpc;
}
}
interface Rpc {
request(
service: string,
method: string,
data: Uint8Array
): Promise<Uint8Array>;
}

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "gogoproto";

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "google.api";

View File

@ -0,0 +1,706 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "google.api";
/**
* Defines the HTTP configuration for an API service. It contains a list of
* [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
* to one or more HTTP REST API methods.
*/
export interface Http {
/**
* A list of HTTP configuration rules that apply to individual API methods.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
*/
rules: HttpRule[];
/**
* When set to true, URL path parmeters will be fully URI-decoded except in
* cases of single segment matches in reserved expansion, where "%2F" will be
* left encoded.
*
* The default behavior is to not decode RFC 6570 reserved characters in multi
* segment matches.
*/
fully_decode_reserved_expansion: boolean;
}
/**
* `HttpRule` defines the mapping of an RPC method to one or more HTTP
* REST API methods. The mapping specifies how different portions of the RPC
* request message are mapped to URL path, URL query parameters, and
* HTTP request body. The mapping is typically specified as an
* `google.api.http` annotation on the RPC method,
* see "google/api/annotations.proto" for details.
*
* The mapping consists of a field specifying the path template and
* method kind. The path template can refer to fields in the request
* message, as in the example below which describes a REST GET
* operation on a resource collection of messages:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* SubMessage sub = 2; // `sub.subfield` is url-mapped
* }
* message Message {
* string text = 1; // content of the resource
* }
*
* The same http annotation can alternatively be expressed inside the
* `GRPC API Configuration` YAML file.
*
* http:
* rules:
* - selector: <proto_package_name>.Messaging.GetMessage
* get: /v1/messages/{message_id}/{sub.subfield}
*
* This definition enables an automatic, bidrectional mapping of HTTP
* JSON to RPC. Example:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))`
*
* In general, not only fields but also field paths can be referenced
* from a path pattern. Fields mapped to the path pattern cannot be
* repeated and must have a primitive (non-message) type.
*
* Any fields in the request message which are not bound by the path
* pattern automatically become (optional) HTTP query
* parameters. Assume the following definition of the request message:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* int64 revision = 2; // becomes a parameter
* SubMessage sub = 3; // `sub.subfield` becomes a parameter
* }
*
*
* This enables a HTTP JSON to RPC mapping as below:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))`
*
* Note that fields which are mapped to HTTP parameters must have a
* primitive type or a repeated primitive type. Message types are not
* allowed. In the case of a repeated type, the parameter can be
* repeated in the URL, as in `...?param=A&param=B`.
*
* For HTTP method kinds which allow a request body, the `body` field
* specifies the mapping. Consider a REST update method on the
* message resource collection:
*
*
* service Messaging {
* rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "message"
* };
* }
* }
* message UpdateMessageRequest {
* string message_id = 1; // mapped to the URL
* Message message = 2; // mapped to the body
* }
*
*
* The following HTTP JSON to RPC mapping is enabled, where the
* representation of the JSON in the request body is determined by
* protos JSON encoding:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
*
* The special name `*` can be used in the body mapping to define that
* every field not bound by the path template should be mapped to the
* request body. This enables the following alternative definition of
* the update method:
*
* service Messaging {
* rpc UpdateMessage(Message) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "*"
* };
* }
* }
* message Message {
* string message_id = 1;
* string text = 2;
* }
*
*
* The following HTTP JSON to RPC mapping is enabled:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")`
*
* Note that when using `*` in the body mapping, it is not possible to
* have HTTP parameters, as all fields not bound by the path end in
* the body. This makes this option more rarely used in practice of
* defining REST APIs. The common usage of `*` is in custom methods
* which don't use the URL at all for transferring data.
*
* It is possible to define multiple HTTP methods for one RPC by using
* the `additional_bindings` option. Example:
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http) = {
* get: "/v1/messages/{message_id}"
* additional_bindings {
* get: "/v1/users/{user_id}/messages/{message_id}"
* }
* };
* }
* }
* message GetMessageRequest {
* string message_id = 1;
* string user_id = 2;
* }
*
*
* This enables the following two alternative HTTP JSON to RPC
* mappings:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
* `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")`
*
* # Rules for HTTP mapping
*
* The rules for mapping HTTP path, query parameters, and body fields
* to the request message are as follows:
*
* 1. The `body` field specifies either `*` or a field path, or is
* omitted. If omitted, it indicates there is no HTTP request body.
* 2. Leaf fields (recursive expansion of nested messages in the
* request) can be classified into three types:
* (a) Matched in the URL template.
* (b) Covered by body (if body is `*`, everything except (a) fields;
* else everything under the body field)
* (c) All other fields.
* 3. URL query parameters found in the HTTP request are mapped to (c) fields.
* 4. Any body sent with an HTTP request can contain only (b) fields.
*
* The syntax of the path template is as follows:
*
* Template = "/" Segments [ Verb ] ;
* Segments = Segment { "/" Segment } ;
* Segment = "*" | "**" | LITERAL | Variable ;
* Variable = "{" FieldPath [ "=" Segments ] "}" ;
* FieldPath = IDENT { "." IDENT } ;
* Verb = ":" LITERAL ;
*
* The syntax `*` matches a single path segment. The syntax `**` matches zero
* or more path segments, which must be the last part of the path except the
* `Verb`. The syntax `LITERAL` matches literal text in the path.
*
* The syntax `Variable` matches part of the URL path as specified by its
* template. A variable template must not contain other variables. If a variable
* matches a single path segment, its template may be omitted, e.g. `{var}`
* is equivalent to `{var=*}`.
*
* If a variable contains exactly one path segment, such as `"{var}"` or
* `"{var=*}"`, when such a variable is expanded into a URL path, all characters
* except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the
* Discovery Document as `{var}`.
*
* If a variable contains one or more path segments, such as `"{var=foo/*}"`
* or `"{var=**}"`, when such a variable is expanded into a URL path, all
* characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables
* show up in the Discovery Document as `{+var}`.
*
* NOTE: While the single segment variable matches the semantics of
* [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2
* Simple String Expansion, the multi segment variable **does not** match
* RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion
* does not expand special characters like `?` and `#`, which would lead
* to invalid URLs.
*
* NOTE: the field paths in variables and in the `body` must not refer to
* repeated fields or map fields.
*/
export interface HttpRule {
/**
* Selects methods to which this rule applies.
*
* Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
*/
selector: string;
/** Used for listing and getting information about resources. */
get: string | undefined;
/** Used for updating a resource. */
put: string | undefined;
/** Used for creating a resource. */
post: string | undefined;
/** Used for deleting a resource. */
delete: string | undefined;
/** Used for updating a resource. */
patch: string | undefined;
/**
* The custom pattern is used for specifying an HTTP method that is not
* included in the `pattern` field, such as HEAD, or "*" to leave the
* HTTP method unspecified for this rule. The wild-card rule is useful
* for services that provide content to Web (HTML) clients.
*/
custom: CustomHttpPattern | undefined;
/**
* The name of the request field whose value is mapped to the HTTP body, or
* `*` for mapping all fields not captured by the path pattern to the HTTP
* body. NOTE: the referred field must not be a repeated field and must be
* present at the top-level of request message type.
*/
body: string;
/**
* Optional. The name of the response field whose value is mapped to the HTTP
* body of response. Other response fields are ignored. When
* not set, the response message will be used as HTTP body of response.
*/
response_body: string;
/**
* Additional HTTP bindings for the selector. Nested bindings must
* not contain an `additional_bindings` field themselves (that is,
* the nesting may only be one level deep).
*/
additional_bindings: HttpRule[];
}
/** A custom pattern is used for defining custom HTTP verb. */
export interface CustomHttpPattern {
/** The name of this custom HTTP verb. */
kind: string;
/** The path matched by this custom verb. */
path: string;
}
const baseHttp: object = { fully_decode_reserved_expansion: false };
export const Http = {
encode(message: Http, writer: Writer = Writer.create()): Writer {
for (const v of message.rules) {
HttpRule.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.fully_decode_reserved_expansion === true) {
writer.uint32(16).bool(message.fully_decode_reserved_expansion);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Http {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttp } as Http;
message.rules = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.rules.push(HttpRule.decode(reader, reader.uint32()));
break;
case 2:
message.fully_decode_reserved_expansion = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromJSON(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion = Boolean(
object.fully_decode_reserved_expansion
);
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
toJSON(message: Http): unknown {
const obj: any = {};
if (message.rules) {
obj.rules = message.rules.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.rules = [];
}
message.fully_decode_reserved_expansion !== undefined &&
(obj.fully_decode_reserved_expansion =
message.fully_decode_reserved_expansion);
return obj;
},
fromPartial(object: DeepPartial<Http>): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromPartial(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion =
object.fully_decode_reserved_expansion;
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
};
const baseHttpRule: object = { selector: "", body: "", response_body: "" };
export const HttpRule = {
encode(message: HttpRule, writer: Writer = Writer.create()): Writer {
if (message.selector !== "") {
writer.uint32(10).string(message.selector);
}
if (message.get !== undefined) {
writer.uint32(18).string(message.get);
}
if (message.put !== undefined) {
writer.uint32(26).string(message.put);
}
if (message.post !== undefined) {
writer.uint32(34).string(message.post);
}
if (message.delete !== undefined) {
writer.uint32(42).string(message.delete);
}
if (message.patch !== undefined) {
writer.uint32(50).string(message.patch);
}
if (message.custom !== undefined) {
CustomHttpPattern.encode(
message.custom,
writer.uint32(66).fork()
).ldelim();
}
if (message.body !== "") {
writer.uint32(58).string(message.body);
}
if (message.response_body !== "") {
writer.uint32(98).string(message.response_body);
}
for (const v of message.additional_bindings) {
HttpRule.encode(v!, writer.uint32(90).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): HttpRule {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.selector = reader.string();
break;
case 2:
message.get = reader.string();
break;
case 3:
message.put = reader.string();
break;
case 4:
message.post = reader.string();
break;
case 5:
message.delete = reader.string();
break;
case 6:
message.patch = reader.string();
break;
case 8:
message.custom = CustomHttpPattern.decode(reader, reader.uint32());
break;
case 7:
message.body = reader.string();
break;
case 12:
message.response_body = reader.string();
break;
case 11:
message.additional_bindings.push(
HttpRule.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = String(object.selector);
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = String(object.get);
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = String(object.put);
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = String(object.post);
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = String(object.delete);
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = String(object.patch);
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromJSON(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = String(object.body);
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = String(object.response_body);
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromJSON(e));
}
}
return message;
},
toJSON(message: HttpRule): unknown {
const obj: any = {};
message.selector !== undefined && (obj.selector = message.selector);
message.get !== undefined && (obj.get = message.get);
message.put !== undefined && (obj.put = message.put);
message.post !== undefined && (obj.post = message.post);
message.delete !== undefined && (obj.delete = message.delete);
message.patch !== undefined && (obj.patch = message.patch);
message.custom !== undefined &&
(obj.custom = message.custom
? CustomHttpPattern.toJSON(message.custom)
: undefined);
message.body !== undefined && (obj.body = message.body);
message.response_body !== undefined &&
(obj.response_body = message.response_body);
if (message.additional_bindings) {
obj.additional_bindings = message.additional_bindings.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.additional_bindings = [];
}
return obj;
},
fromPartial(object: DeepPartial<HttpRule>): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = object.selector;
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = object.get;
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = object.put;
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = object.post;
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = object.delete;
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = object.patch;
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromPartial(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = object.body;
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = object.response_body;
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromPartial(e));
}
}
return message;
},
};
const baseCustomHttpPattern: object = { kind: "", path: "" };
export const CustomHttpPattern = {
encode(message: CustomHttpPattern, writer: Writer = Writer.create()): Writer {
if (message.kind !== "") {
writer.uint32(10).string(message.kind);
}
if (message.path !== "") {
writer.uint32(18).string(message.path);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): CustomHttpPattern {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.kind = reader.string();
break;
case 2:
message.path = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = String(object.kind);
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = String(object.path);
} else {
message.path = "";
}
return message;
},
toJSON(message: CustomHttpPattern): unknown {
const obj: any = {};
message.kind !== undefined && (obj.kind = message.kind);
message.path !== undefined && (obj.path = message.path);
return obj;
},
fromPartial(object: DeepPartial<CustomHttpPattern>): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = object.kind;
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = object.path;
} else {
message.path = "";
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,18 @@
{
"name": "cosmostest-cosmostest-js",
"version": "0.1.0",
"description": "Autogenerated vuex store for Cosmos module cosmostest.cosmostest",
"author": "Starport Codegen <hello@tendermint.com>",
"homepage": "http://cosmos-test/x/cosmostest/types",
"license": "Apache-2.0",
"licenses": [
{
"type": "Apache-2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
],
"main": "index.js",
"publishConfig": {
"access": "public"
}
}

View File

@ -0,0 +1 @@
THIS FILE IS GENERATED AUTOMATICALLY. DO NOT DELETE.

View File

@ -0,0 +1,207 @@
import { txClient, queryClient, MissingWalletError , registry} from './module'
import { BaseAccount } from "./module/types/cosmos/auth/v1beta1/auth"
import { ModuleAccount } from "./module/types/cosmos/auth/v1beta1/auth"
import { Params } from "./module/types/cosmos/auth/v1beta1/auth"
export { BaseAccount, ModuleAccount, Params };
async function initTxClient(vuexGetters) {
return await txClient(vuexGetters['common/wallet/signer'], {
addr: vuexGetters['common/env/apiTendermint']
})
}
async function initQueryClient(vuexGetters) {
return await queryClient({
addr: vuexGetters['common/env/apiCosmos']
})
}
function mergeResults(value, next_values) {
for (let prop of Object.keys(next_values)) {
if (Array.isArray(next_values[prop])) {
value[prop]=[...value[prop], ...next_values[prop]]
}else{
value[prop]=next_values[prop]
}
}
return value
}
function getStructure(template) {
let structure = { fields: [] }
for (const [key, value] of Object.entries(template)) {
let field: any = {}
field.name = key
field.type = typeof value
structure.fields.push(field)
}
return structure
}
const getDefaultState = () => {
return {
Accounts: {},
Account: {},
Params: {},
_Structure: {
BaseAccount: getStructure(BaseAccount.fromPartial({})),
ModuleAccount: getStructure(ModuleAccount.fromPartial({})),
Params: getStructure(Params.fromPartial({})),
},
_Registry: registry,
_Subscriptions: new Set(),
}
}
// initial state
const state = getDefaultState()
export default {
namespaced: true,
state,
mutations: {
RESET_STATE(state) {
Object.assign(state, getDefaultState())
},
QUERY(state, { query, key, value }) {
state[query][JSON.stringify(key)] = value
},
SUBSCRIBE(state, subscription) {
state._Subscriptions.add(JSON.stringify(subscription))
},
UNSUBSCRIBE(state, subscription) {
state._Subscriptions.delete(JSON.stringify(subscription))
}
},
getters: {
getAccounts: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.Accounts[JSON.stringify(params)] ?? {}
},
getAccount: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.Account[JSON.stringify(params)] ?? {}
},
getParams: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.Params[JSON.stringify(params)] ?? {}
},
getTypeStructure: (state) => (type) => {
return state._Structure[type].fields
},
getRegistry: (state) => {
return state._Registry
}
},
actions: {
init({ dispatch, rootGetters }) {
console.log('Vuex module: cosmos.auth.v1beta1 initialized!')
if (rootGetters['common/env/client']) {
rootGetters['common/env/client'].on('newblock', () => {
dispatch('StoreUpdate')
})
}
},
resetState({ commit }) {
commit('RESET_STATE')
},
unsubscribe({ commit }, subscription) {
commit('UNSUBSCRIBE', subscription)
},
async StoreUpdate({ state, dispatch }) {
state._Subscriptions.forEach(async (subscription) => {
try {
const sub=JSON.parse(subscription)
await dispatch(sub.action, sub.payload)
}catch(e) {
throw new Error('Subscriptions: ' + e.message)
}
})
},
async QueryAccounts({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryAccounts(query)).data
while (all && (<any> value).pagination && (<any> value).pagination.next_key!=null) {
let next_values=(await queryClient.queryAccounts({...query, 'pagination.key':(<any> value).pagination.next_key})).data
value = mergeResults(value, next_values);
}
commit('QUERY', { query: 'Accounts', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryAccounts', payload: { options: { all }, params: {...key},query }})
return getters['getAccounts']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryAccounts API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QueryAccount({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryAccount( key.address)).data
commit('QUERY', { query: 'Account', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryAccount', payload: { options: { all }, params: {...key},query }})
return getters['getAccount']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryAccount API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QueryParams({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryParams()).data
commit('QUERY', { query: 'Params', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryParams', payload: { options: { all }, params: {...key},query }})
return getters['getParams']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryParams API Node Unavailable. Could not perform query: ' + e.message)
}
},
}
}

View File

@ -0,0 +1,57 @@
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT MODIFY.
import { StdFee } from "@cosmjs/launchpad";
import { SigningStargateClient } from "@cosmjs/stargate";
import { Registry, OfflineSigner, EncodeObject, DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { Api } from "./rest";
const types = [
];
export const MissingWalletError = new Error("wallet is required");
export const registry = new Registry(<any>types);
const defaultFee = {
amount: [],
gas: "200000",
};
interface TxClientOptions {
addr: string
}
interface SignAndBroadcastOptions {
fee: StdFee,
memo?: string
}
const txClient = async (wallet: OfflineSigner, { addr: addr }: TxClientOptions = { addr: "http://localhost:26657" }) => {
if (!wallet) throw MissingWalletError;
let client;
if (addr) {
client = await SigningStargateClient.connectWithSigner(addr, wallet, { registry });
}else{
client = await SigningStargateClient.offline( wallet, { registry });
}
const { address } = (await wallet.getAccounts())[0];
return {
signAndBroadcast: (msgs: EncodeObject[], { fee, memo }: SignAndBroadcastOptions = {fee: defaultFee, memo: ""}) => client.signAndBroadcast(address, msgs, fee,memo),
};
};
interface QueryClientOptions {
addr: string
}
const queryClient = async ({ addr: addr }: QueryClientOptions = { addr: "http://localhost:1317" }) => {
return new Api({ baseUrl: addr });
};
export {
txClient,
queryClient,
};

View File

@ -0,0 +1,500 @@
/* eslint-disable */
/* tslint:disable */
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
URL that describes the type of the serialized message.
Protobuf library provides support to pack/unpack Any values in the form
of utility functions or additional generated methods of the Any type.
Example 1: Pack and unpack a message in C++.
Foo foo = ...;
Any any;
any.PackFrom(foo);
...
if (any.UnpackTo(&foo)) {
...
}
Example 2: Pack and unpack a message in Java.
Foo foo = ...;
Any any = Any.pack(foo);
...
if (any.is(Foo.class)) {
foo = any.unpack(Foo.class);
}
Example 3: Pack and unpack a message in Python.
foo = Foo(...)
any = Any()
any.Pack(foo)
...
if any.Is(Foo.DESCRIPTOR):
any.Unpack(foo)
...
Example 4: Pack and unpack a message in Go
foo := &pb.Foo{...}
any, err := anypb.New(foo)
if err != nil {
...
}
...
foo := &pb.Foo{}
if err := any.UnmarshalTo(foo); err != nil {
...
}
The pack methods provided by protobuf library will by default use
'type.googleapis.com/full.type.name' as the type URL and the unpack
methods only use the fully qualified type name after the last '/'
in the type URL, for example "foo.bar.com/x/y.z" will yield type
name "y.z".
JSON
====
The JSON representation of an `Any` value uses the regular
representation of the deserialized, embedded message, with an
additional field `@type` which contains the type URL. Example:
package google.profile;
message Person {
string first_name = 1;
string last_name = 2;
}
{
"@type": "type.googleapis.com/google.profile.Person",
"firstName": <string>,
"lastName": <string>
}
If the embedded message type is well-known and has a custom JSON
representation, that representation will be embedded adding a field
`value` which holds the custom JSON in addition to the `@type`
field. Example (for message [google.protobuf.Duration][]):
{
"@type": "type.googleapis.com/google.protobuf.Duration",
"value": "1.212s"
}
*/
export interface ProtobufAny {
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*/
"@type"?: string;
}
export interface RpcStatus {
/** @format int32 */
code?: number;
message?: string;
details?: ProtobufAny[];
}
/**
* message SomeRequest {
Foo some_parameter = 1;
PageRequest pagination = 2;
}
*/
export interface V1Beta1PageRequest {
/**
* key is a value returned in PageResponse.next_key to begin
* querying the next page most efficiently. Only one of offset or key
* should be set.
* @format byte
*/
key?: string;
/**
* offset is a numeric offset that can be used when key is unavailable.
* It is less efficient than using key. Only one of offset or key should
* be set.
* @format uint64
*/
offset?: string;
/**
* limit is the total number of results to be returned in the result page.
* If left empty it will default to a value to be set by each app.
* @format uint64
*/
limit?: string;
/**
* count_total is set to true to indicate that the result set should include
* a count of the total number of items available for pagination in UIs.
* count_total is only respected when offset is used. It is ignored when key
* is set.
*/
count_total?: boolean;
/**
* reverse is set to true if results are to be returned in the descending order.
*
* Since: cosmos-sdk 0.43
*/
reverse?: boolean;
}
/**
* PageResponse is to be embedded in gRPC response messages where the
corresponding request message has used PageRequest.
message SomeResponse {
repeated Bar results = 1;
PageResponse page = 2;
}
*/
export interface V1Beta1PageResponse {
/** @format byte */
next_key?: string;
/** @format uint64 */
total?: string;
}
/**
* Params defines the parameters for the auth module.
*/
export interface V1Beta1Params {
/** @format uint64 */
max_memo_characters?: string;
/** @format uint64 */
tx_sig_limit?: string;
/** @format uint64 */
tx_size_cost_per_byte?: string;
/** @format uint64 */
sig_verify_cost_ed25519?: string;
/** @format uint64 */
sig_verify_cost_secp256k1?: string;
}
/**
* QueryAccountResponse is the response type for the Query/Account RPC method.
*/
export interface V1Beta1QueryAccountResponse {
/** account defines the account of the corresponding address. */
account?: ProtobufAny;
}
/**
* QueryAccountsResponse is the response type for the Query/Accounts RPC method.
Since: cosmos-sdk 0.43
*/
export interface V1Beta1QueryAccountsResponse {
accounts?: ProtobufAny[];
/** pagination defines the pagination in the response. */
pagination?: V1Beta1PageResponse;
}
/**
* QueryParamsResponse is the response type for the Query/Params RPC method.
*/
export interface V1Beta1QueryParamsResponse {
/** params defines the parameters of the module. */
params?: V1Beta1Params;
}
export type QueryParamsType = Record<string | number, any>;
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
export interface FullRequestParams extends Omit<RequestInit, "body"> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: keyof Omit<Body, "body" | "bodyUsed">;
/** request body */
body?: unknown;
/** base url */
baseUrl?: string;
/** request cancellation token */
cancelToken?: CancelToken;
}
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
export interface ApiConfig<SecurityDataType = unknown> {
baseUrl?: string;
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
securityWorker?: (securityData: SecurityDataType) => RequestParams | void;
}
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
data: D;
error: E;
}
type CancelToken = Symbol | string | number;
export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
}
export class HttpClient<SecurityDataType = unknown> {
public baseUrl: string = "";
private securityData: SecurityDataType = null as any;
private securityWorker: null | ApiConfig<SecurityDataType>["securityWorker"] = null;
private abortControllers = new Map<CancelToken, AbortController>();
private baseApiParams: RequestParams = {
credentials: "same-origin",
headers: {},
redirect: "follow",
referrerPolicy: "no-referrer",
};
constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
Object.assign(this, apiConfig);
}
public setSecurityData = (data: SecurityDataType) => {
this.securityData = data;
};
private addQueryParam(query: QueryParamsType, key: string) {
const value = query[key];
return (
encodeURIComponent(key) +
"=" +
encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`)
);
}
protected toQueryString(rawQuery?: QueryParamsType): string {
const query = rawQuery || {};
const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
return keys
.map((key) =>
typeof query[key] === "object" && !Array.isArray(query[key])
? this.toQueryString(query[key] as QueryParamsType)
: this.addQueryParam(query, key),
)
.join("&");
}
protected addQueryParams(rawQuery?: QueryParamsType): string {
const queryString = this.toQueryString(rawQuery);
return queryString ? `?${queryString}` : "";
}
private contentFormatters: Record<ContentType, (input: any) => any> = {
[ContentType.Json]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
[ContentType.FormData]: (input: any) =>
Object.keys(input || {}).reduce((data, key) => {
data.append(key, input[key]);
return data;
}, new FormData()),
[ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
};
private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
return {
...this.baseApiParams,
...params1,
...(params2 || {}),
headers: {
...(this.baseApiParams.headers || {}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
if (this.abortControllers.has(cancelToken)) {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
return abortController.signal;
}
return void 0;
}
const abortController = new AbortController();
this.abortControllers.set(cancelToken, abortController);
return abortController.signal;
};
public abortRequest = (cancelToken: CancelToken) => {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
abortController.abort();
this.abortControllers.delete(cancelToken);
}
};
public request = <T = any, E = any>({
body,
secure,
path,
type,
query,
format = "json",
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
...requestParams,
headers: {
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
...(requestParams.headers || {}),
},
signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
}).then(async (response) => {
const r = response as HttpResponse<T, E>;
r.data = (null as unknown) as T;
r.error = (null as unknown) as E;
const data = await response[format]()
.then((data) => {
if (r.ok) {
r.data = data;
} else {
r.error = data;
}
return r;
})
.catch((e) => {
r.error = e;
return r;
});
if (cancelToken) {
this.abortControllers.delete(cancelToken);
}
if (!response.ok) throw data;
return data;
});
};
}
/**
* @title cosmos/auth/v1beta1/auth.proto
* @version version not set
*/
export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
/**
* @description Since: cosmos-sdk 0.43
*
* @tags Query
* @name QueryAccounts
* @summary Accounts returns all the existing accounts
* @request GET:/cosmos/auth/v1beta1/accounts
*/
queryAccounts = (
query?: {
"pagination.key"?: string;
"pagination.offset"?: string;
"pagination.limit"?: string;
"pagination.count_total"?: boolean;
"pagination.reverse"?: boolean;
},
params: RequestParams = {},
) =>
this.request<V1Beta1QueryAccountsResponse, RpcStatus>({
path: `/cosmos/auth/v1beta1/accounts`,
method: "GET",
query: query,
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QueryAccount
* @summary Account returns account details based on address.
* @request GET:/cosmos/auth/v1beta1/accounts/{address}
*/
queryAccount = (address: string, params: RequestParams = {}) =>
this.request<V1Beta1QueryAccountResponse, RpcStatus>({
path: `/cosmos/auth/v1beta1/accounts/${address}`,
method: "GET",
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QueryParams
* @summary Params queries all parameters.
* @request GET:/cosmos/auth/v1beta1/params
*/
queryParams = (params: RequestParams = {}) =>
this.request<V1Beta1QueryParamsResponse, RpcStatus>({
path: `/cosmos/auth/v1beta1/params`,
method: "GET",
format: "json",
...params,
});
}

View File

@ -0,0 +1,441 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
import { Any } from "../../../google/protobuf/any";
export const protobufPackage = "cosmos.auth.v1beta1";
/**
* BaseAccount defines a base account type. It contains all the necessary fields
* for basic account functionality. Any custom account type should extend this
* type for additional functionality (e.g. vesting).
*/
export interface BaseAccount {
address: string;
pub_key: Any | undefined;
account_number: number;
sequence: number;
}
/** ModuleAccount defines an account for modules that holds coins on a pool. */
export interface ModuleAccount {
base_account: BaseAccount | undefined;
name: string;
permissions: string[];
}
/** Params defines the parameters for the auth module. */
export interface Params {
max_memo_characters: number;
tx_sig_limit: number;
tx_size_cost_per_byte: number;
sig_verify_cost_ed25519: number;
sig_verify_cost_secp256k1: number;
}
const baseBaseAccount: object = { address: "", account_number: 0, sequence: 0 };
export const BaseAccount = {
encode(message: BaseAccount, writer: Writer = Writer.create()): Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
if (message.pub_key !== undefined) {
Any.encode(message.pub_key, writer.uint32(18).fork()).ldelim();
}
if (message.account_number !== 0) {
writer.uint32(24).uint64(message.account_number);
}
if (message.sequence !== 0) {
writer.uint32(32).uint64(message.sequence);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): BaseAccount {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBaseAccount } as BaseAccount;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
case 2:
message.pub_key = Any.decode(reader, reader.uint32());
break;
case 3:
message.account_number = longToNumber(reader.uint64() as Long);
break;
case 4:
message.sequence = longToNumber(reader.uint64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BaseAccount {
const message = { ...baseBaseAccount } as BaseAccount;
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
if (object.pub_key !== undefined && object.pub_key !== null) {
message.pub_key = Any.fromJSON(object.pub_key);
} else {
message.pub_key = undefined;
}
if (object.account_number !== undefined && object.account_number !== null) {
message.account_number = Number(object.account_number);
} else {
message.account_number = 0;
}
if (object.sequence !== undefined && object.sequence !== null) {
message.sequence = Number(object.sequence);
} else {
message.sequence = 0;
}
return message;
},
toJSON(message: BaseAccount): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
message.pub_key !== undefined &&
(obj.pub_key = message.pub_key ? Any.toJSON(message.pub_key) : undefined);
message.account_number !== undefined &&
(obj.account_number = message.account_number);
message.sequence !== undefined && (obj.sequence = message.sequence);
return obj;
},
fromPartial(object: DeepPartial<BaseAccount>): BaseAccount {
const message = { ...baseBaseAccount } as BaseAccount;
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
if (object.pub_key !== undefined && object.pub_key !== null) {
message.pub_key = Any.fromPartial(object.pub_key);
} else {
message.pub_key = undefined;
}
if (object.account_number !== undefined && object.account_number !== null) {
message.account_number = object.account_number;
} else {
message.account_number = 0;
}
if (object.sequence !== undefined && object.sequence !== null) {
message.sequence = object.sequence;
} else {
message.sequence = 0;
}
return message;
},
};
const baseModuleAccount: object = { name: "", permissions: "" };
export const ModuleAccount = {
encode(message: ModuleAccount, writer: Writer = Writer.create()): Writer {
if (message.base_account !== undefined) {
BaseAccount.encode(
message.base_account,
writer.uint32(10).fork()
).ldelim();
}
if (message.name !== "") {
writer.uint32(18).string(message.name);
}
for (const v of message.permissions) {
writer.uint32(26).string(v!);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): ModuleAccount {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseModuleAccount } as ModuleAccount;
message.permissions = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.base_account = BaseAccount.decode(reader, reader.uint32());
break;
case 2:
message.name = reader.string();
break;
case 3:
message.permissions.push(reader.string());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ModuleAccount {
const message = { ...baseModuleAccount } as ModuleAccount;
message.permissions = [];
if (object.base_account !== undefined && object.base_account !== null) {
message.base_account = BaseAccount.fromJSON(object.base_account);
} else {
message.base_account = undefined;
}
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = "";
}
if (object.permissions !== undefined && object.permissions !== null) {
for (const e of object.permissions) {
message.permissions.push(String(e));
}
}
return message;
},
toJSON(message: ModuleAccount): unknown {
const obj: any = {};
message.base_account !== undefined &&
(obj.base_account = message.base_account
? BaseAccount.toJSON(message.base_account)
: undefined);
message.name !== undefined && (obj.name = message.name);
if (message.permissions) {
obj.permissions = message.permissions.map((e) => e);
} else {
obj.permissions = [];
}
return obj;
},
fromPartial(object: DeepPartial<ModuleAccount>): ModuleAccount {
const message = { ...baseModuleAccount } as ModuleAccount;
message.permissions = [];
if (object.base_account !== undefined && object.base_account !== null) {
message.base_account = BaseAccount.fromPartial(object.base_account);
} else {
message.base_account = undefined;
}
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = "";
}
if (object.permissions !== undefined && object.permissions !== null) {
for (const e of object.permissions) {
message.permissions.push(e);
}
}
return message;
},
};
const baseParams: object = {
max_memo_characters: 0,
tx_sig_limit: 0,
tx_size_cost_per_byte: 0,
sig_verify_cost_ed25519: 0,
sig_verify_cost_secp256k1: 0,
};
export const Params = {
encode(message: Params, writer: Writer = Writer.create()): Writer {
if (message.max_memo_characters !== 0) {
writer.uint32(8).uint64(message.max_memo_characters);
}
if (message.tx_sig_limit !== 0) {
writer.uint32(16).uint64(message.tx_sig_limit);
}
if (message.tx_size_cost_per_byte !== 0) {
writer.uint32(24).uint64(message.tx_size_cost_per_byte);
}
if (message.sig_verify_cost_ed25519 !== 0) {
writer.uint32(32).uint64(message.sig_verify_cost_ed25519);
}
if (message.sig_verify_cost_secp256k1 !== 0) {
writer.uint32(40).uint64(message.sig_verify_cost_secp256k1);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Params {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseParams } as Params;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.max_memo_characters = longToNumber(reader.uint64() as Long);
break;
case 2:
message.tx_sig_limit = longToNumber(reader.uint64() as Long);
break;
case 3:
message.tx_size_cost_per_byte = longToNumber(reader.uint64() as Long);
break;
case 4:
message.sig_verify_cost_ed25519 = longToNumber(
reader.uint64() as Long
);
break;
case 5:
message.sig_verify_cost_secp256k1 = longToNumber(
reader.uint64() as Long
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Params {
const message = { ...baseParams } as Params;
if (
object.max_memo_characters !== undefined &&
object.max_memo_characters !== null
) {
message.max_memo_characters = Number(object.max_memo_characters);
} else {
message.max_memo_characters = 0;
}
if (object.tx_sig_limit !== undefined && object.tx_sig_limit !== null) {
message.tx_sig_limit = Number(object.tx_sig_limit);
} else {
message.tx_sig_limit = 0;
}
if (
object.tx_size_cost_per_byte !== undefined &&
object.tx_size_cost_per_byte !== null
) {
message.tx_size_cost_per_byte = Number(object.tx_size_cost_per_byte);
} else {
message.tx_size_cost_per_byte = 0;
}
if (
object.sig_verify_cost_ed25519 !== undefined &&
object.sig_verify_cost_ed25519 !== null
) {
message.sig_verify_cost_ed25519 = Number(object.sig_verify_cost_ed25519);
} else {
message.sig_verify_cost_ed25519 = 0;
}
if (
object.sig_verify_cost_secp256k1 !== undefined &&
object.sig_verify_cost_secp256k1 !== null
) {
message.sig_verify_cost_secp256k1 = Number(
object.sig_verify_cost_secp256k1
);
} else {
message.sig_verify_cost_secp256k1 = 0;
}
return message;
},
toJSON(message: Params): unknown {
const obj: any = {};
message.max_memo_characters !== undefined &&
(obj.max_memo_characters = message.max_memo_characters);
message.tx_sig_limit !== undefined &&
(obj.tx_sig_limit = message.tx_sig_limit);
message.tx_size_cost_per_byte !== undefined &&
(obj.tx_size_cost_per_byte = message.tx_size_cost_per_byte);
message.sig_verify_cost_ed25519 !== undefined &&
(obj.sig_verify_cost_ed25519 = message.sig_verify_cost_ed25519);
message.sig_verify_cost_secp256k1 !== undefined &&
(obj.sig_verify_cost_secp256k1 = message.sig_verify_cost_secp256k1);
return obj;
},
fromPartial(object: DeepPartial<Params>): Params {
const message = { ...baseParams } as Params;
if (
object.max_memo_characters !== undefined &&
object.max_memo_characters !== null
) {
message.max_memo_characters = object.max_memo_characters;
} else {
message.max_memo_characters = 0;
}
if (object.tx_sig_limit !== undefined && object.tx_sig_limit !== null) {
message.tx_sig_limit = object.tx_sig_limit;
} else {
message.tx_sig_limit = 0;
}
if (
object.tx_size_cost_per_byte !== undefined &&
object.tx_size_cost_per_byte !== null
) {
message.tx_size_cost_per_byte = object.tx_size_cost_per_byte;
} else {
message.tx_size_cost_per_byte = 0;
}
if (
object.sig_verify_cost_ed25519 !== undefined &&
object.sig_verify_cost_ed25519 !== null
) {
message.sig_verify_cost_ed25519 = object.sig_verify_cost_ed25519;
} else {
message.sig_verify_cost_ed25519 = 0;
}
if (
object.sig_verify_cost_secp256k1 !== undefined &&
object.sig_verify_cost_secp256k1 !== null
) {
message.sig_verify_cost_secp256k1 = object.sig_verify_cost_secp256k1;
} else {
message.sig_verify_cost_secp256k1 = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,107 @@
/* eslint-disable */
import { Params } from "../../../cosmos/auth/v1beta1/auth";
import { Any } from "../../../google/protobuf/any";
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.auth.v1beta1";
/** GenesisState defines the auth module's genesis state. */
export interface GenesisState {
/** params defines all the paramaters of the module. */
params: Params | undefined;
/** accounts are the accounts present at genesis. */
accounts: Any[];
}
const baseGenesisState: object = {};
export const GenesisState = {
encode(message: GenesisState, writer: Writer = Writer.create()): Writer {
if (message.params !== undefined) {
Params.encode(message.params, writer.uint32(10).fork()).ldelim();
}
for (const v of message.accounts) {
Any.encode(v!, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): GenesisState {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseGenesisState } as GenesisState;
message.accounts = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.params = Params.decode(reader, reader.uint32());
break;
case 2:
message.accounts.push(Any.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): GenesisState {
const message = { ...baseGenesisState } as GenesisState;
message.accounts = [];
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromJSON(object.params);
} else {
message.params = undefined;
}
if (object.accounts !== undefined && object.accounts !== null) {
for (const e of object.accounts) {
message.accounts.push(Any.fromJSON(e));
}
}
return message;
},
toJSON(message: GenesisState): unknown {
const obj: any = {};
message.params !== undefined &&
(obj.params = message.params ? Params.toJSON(message.params) : undefined);
if (message.accounts) {
obj.accounts = message.accounts.map((e) =>
e ? Any.toJSON(e) : undefined
);
} else {
obj.accounts = [];
}
return obj;
},
fromPartial(object: DeepPartial<GenesisState>): GenesisState {
const message = { ...baseGenesisState } as GenesisState;
message.accounts = [];
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromPartial(object.params);
} else {
message.params = undefined;
}
if (object.accounts !== undefined && object.accounts !== null) {
for (const e of object.accounts) {
message.accounts.push(Any.fromPartial(e));
}
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,493 @@
/* eslint-disable */
import { Reader, Writer } from "protobufjs/minimal";
import {
PageRequest,
PageResponse,
} from "../../../cosmos/base/query/v1beta1/pagination";
import { Any } from "../../../google/protobuf/any";
import { Params } from "../../../cosmos/auth/v1beta1/auth";
export const protobufPackage = "cosmos.auth.v1beta1";
/**
* QueryAccountsRequest is the request type for the Query/Accounts RPC method.
*
* Since: cosmos-sdk 0.43
*/
export interface QueryAccountsRequest {
/** pagination defines an optional pagination for the request. */
pagination: PageRequest | undefined;
}
/**
* QueryAccountsResponse is the response type for the Query/Accounts RPC method.
*
* Since: cosmos-sdk 0.43
*/
export interface QueryAccountsResponse {
/** accounts are the existing accounts */
accounts: Any[];
/** pagination defines the pagination in the response. */
pagination: PageResponse | undefined;
}
/** QueryAccountRequest is the request type for the Query/Account RPC method. */
export interface QueryAccountRequest {
/** address defines the address to query for. */
address: string;
}
/** QueryAccountResponse is the response type for the Query/Account RPC method. */
export interface QueryAccountResponse {
/** account defines the account of the corresponding address. */
account: Any | undefined;
}
/** QueryParamsRequest is the request type for the Query/Params RPC method. */
export interface QueryParamsRequest {}
/** QueryParamsResponse is the response type for the Query/Params RPC method. */
export interface QueryParamsResponse {
/** params defines the parameters of the module. */
params: Params | undefined;
}
const baseQueryAccountsRequest: object = {};
export const QueryAccountsRequest = {
encode(
message: QueryAccountsRequest,
writer: Writer = Writer.create()
): Writer {
if (message.pagination !== undefined) {
PageRequest.encode(message.pagination, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryAccountsRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryAccountsRequest } as QueryAccountsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.pagination = PageRequest.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): QueryAccountsRequest {
const message = { ...baseQueryAccountsRequest } as QueryAccountsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: QueryAccountsRequest): unknown {
const obj: any = {};
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageRequest.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<QueryAccountsRequest>): QueryAccountsRequest {
const message = { ...baseQueryAccountsRequest } as QueryAccountsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseQueryAccountsResponse: object = {};
export const QueryAccountsResponse = {
encode(
message: QueryAccountsResponse,
writer: Writer = Writer.create()
): Writer {
for (const v of message.accounts) {
Any.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.pagination !== undefined) {
PageResponse.encode(
message.pagination,
writer.uint32(18).fork()
).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryAccountsResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryAccountsResponse } as QueryAccountsResponse;
message.accounts = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.accounts.push(Any.decode(reader, reader.uint32()));
break;
case 2:
message.pagination = PageResponse.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): QueryAccountsResponse {
const message = { ...baseQueryAccountsResponse } as QueryAccountsResponse;
message.accounts = [];
if (object.accounts !== undefined && object.accounts !== null) {
for (const e of object.accounts) {
message.accounts.push(Any.fromJSON(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: QueryAccountsResponse): unknown {
const obj: any = {};
if (message.accounts) {
obj.accounts = message.accounts.map((e) =>
e ? Any.toJSON(e) : undefined
);
} else {
obj.accounts = [];
}
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageResponse.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(
object: DeepPartial<QueryAccountsResponse>
): QueryAccountsResponse {
const message = { ...baseQueryAccountsResponse } as QueryAccountsResponse;
message.accounts = [];
if (object.accounts !== undefined && object.accounts !== null) {
for (const e of object.accounts) {
message.accounts.push(Any.fromPartial(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseQueryAccountRequest: object = { address: "" };
export const QueryAccountRequest = {
encode(
message: QueryAccountRequest,
writer: Writer = Writer.create()
): Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryAccountRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryAccountRequest } as QueryAccountRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): QueryAccountRequest {
const message = { ...baseQueryAccountRequest } as QueryAccountRequest;
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
return message;
},
toJSON(message: QueryAccountRequest): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
return obj;
},
fromPartial(object: DeepPartial<QueryAccountRequest>): QueryAccountRequest {
const message = { ...baseQueryAccountRequest } as QueryAccountRequest;
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
return message;
},
};
const baseQueryAccountResponse: object = {};
export const QueryAccountResponse = {
encode(
message: QueryAccountResponse,
writer: Writer = Writer.create()
): Writer {
if (message.account !== undefined) {
Any.encode(message.account, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryAccountResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryAccountResponse } as QueryAccountResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.account = Any.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): QueryAccountResponse {
const message = { ...baseQueryAccountResponse } as QueryAccountResponse;
if (object.account !== undefined && object.account !== null) {
message.account = Any.fromJSON(object.account);
} else {
message.account = undefined;
}
return message;
},
toJSON(message: QueryAccountResponse): unknown {
const obj: any = {};
message.account !== undefined &&
(obj.account = message.account ? Any.toJSON(message.account) : undefined);
return obj;
},
fromPartial(object: DeepPartial<QueryAccountResponse>): QueryAccountResponse {
const message = { ...baseQueryAccountResponse } as QueryAccountResponse;
if (object.account !== undefined && object.account !== null) {
message.account = Any.fromPartial(object.account);
} else {
message.account = undefined;
}
return message;
},
};
const baseQueryParamsRequest: object = {};
export const QueryParamsRequest = {
encode(_: QueryParamsRequest, writer: Writer = Writer.create()): Writer {
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryParamsRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryParamsRequest } as QueryParamsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): QueryParamsRequest {
const message = { ...baseQueryParamsRequest } as QueryParamsRequest;
return message;
},
toJSON(_: QueryParamsRequest): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<QueryParamsRequest>): QueryParamsRequest {
const message = { ...baseQueryParamsRequest } as QueryParamsRequest;
return message;
},
};
const baseQueryParamsResponse: object = {};
export const QueryParamsResponse = {
encode(
message: QueryParamsResponse,
writer: Writer = Writer.create()
): Writer {
if (message.params !== undefined) {
Params.encode(message.params, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): QueryParamsResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseQueryParamsResponse } as QueryParamsResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.params = Params.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): QueryParamsResponse {
const message = { ...baseQueryParamsResponse } as QueryParamsResponse;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromJSON(object.params);
} else {
message.params = undefined;
}
return message;
},
toJSON(message: QueryParamsResponse): unknown {
const obj: any = {};
message.params !== undefined &&
(obj.params = message.params ? Params.toJSON(message.params) : undefined);
return obj;
},
fromPartial(object: DeepPartial<QueryParamsResponse>): QueryParamsResponse {
const message = { ...baseQueryParamsResponse } as QueryParamsResponse;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromPartial(object.params);
} else {
message.params = undefined;
}
return message;
},
};
/** Query defines the gRPC querier service. */
export interface Query {
/**
* Accounts returns all the existing accounts
*
* Since: cosmos-sdk 0.43
*/
Accounts(request: QueryAccountsRequest): Promise<QueryAccountsResponse>;
/** Account returns account details based on address. */
Account(request: QueryAccountRequest): Promise<QueryAccountResponse>;
/** Params queries all parameters. */
Params(request: QueryParamsRequest): Promise<QueryParamsResponse>;
}
export class QueryClientImpl implements Query {
private readonly rpc: Rpc;
constructor(rpc: Rpc) {
this.rpc = rpc;
}
Accounts(request: QueryAccountsRequest): Promise<QueryAccountsResponse> {
const data = QueryAccountsRequest.encode(request).finish();
const promise = this.rpc.request(
"cosmos.auth.v1beta1.Query",
"Accounts",
data
);
return promise.then((data) =>
QueryAccountsResponse.decode(new Reader(data))
);
}
Account(request: QueryAccountRequest): Promise<QueryAccountResponse> {
const data = QueryAccountRequest.encode(request).finish();
const promise = this.rpc.request(
"cosmos.auth.v1beta1.Query",
"Account",
data
);
return promise.then((data) =>
QueryAccountResponse.decode(new Reader(data))
);
}
Params(request: QueryParamsRequest): Promise<QueryParamsResponse> {
const data = QueryParamsRequest.encode(request).finish();
const promise = this.rpc.request(
"cosmos.auth.v1beta1.Query",
"Params",
data
);
return promise.then((data) => QueryParamsResponse.decode(new Reader(data)));
}
}
interface Rpc {
request(
service: string,
method: string,
data: Uint8Array
): Promise<Uint8Array>;
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,328 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.base.query.v1beta1";
/**
* PageRequest is to be embedded in gRPC request messages for efficient
* pagination. Ex:
*
* message SomeRequest {
* Foo some_parameter = 1;
* PageRequest pagination = 2;
* }
*/
export interface PageRequest {
/**
* key is a value returned in PageResponse.next_key to begin
* querying the next page most efficiently. Only one of offset or key
* should be set.
*/
key: Uint8Array;
/**
* offset is a numeric offset that can be used when key is unavailable.
* It is less efficient than using key. Only one of offset or key should
* be set.
*/
offset: number;
/**
* limit is the total number of results to be returned in the result page.
* If left empty it will default to a value to be set by each app.
*/
limit: number;
/**
* count_total is set to true to indicate that the result set should include
* a count of the total number of items available for pagination in UIs.
* count_total is only respected when offset is used. It is ignored when key
* is set.
*/
count_total: boolean;
/**
* reverse is set to true if results are to be returned in the descending order.
*
* Since: cosmos-sdk 0.43
*/
reverse: boolean;
}
/**
* PageResponse is to be embedded in gRPC response messages where the
* corresponding request message has used PageRequest.
*
* message SomeResponse {
* repeated Bar results = 1;
* PageResponse page = 2;
* }
*/
export interface PageResponse {
/**
* next_key is the key to be passed to PageRequest.key to
* query the next page most efficiently
*/
next_key: Uint8Array;
/**
* total is total number of results available if PageRequest.count_total
* was set, its value is undefined otherwise
*/
total: number;
}
const basePageRequest: object = {
offset: 0,
limit: 0,
count_total: false,
reverse: false,
};
export const PageRequest = {
encode(message: PageRequest, writer: Writer = Writer.create()): Writer {
if (message.key.length !== 0) {
writer.uint32(10).bytes(message.key);
}
if (message.offset !== 0) {
writer.uint32(16).uint64(message.offset);
}
if (message.limit !== 0) {
writer.uint32(24).uint64(message.limit);
}
if (message.count_total === true) {
writer.uint32(32).bool(message.count_total);
}
if (message.reverse === true) {
writer.uint32(40).bool(message.reverse);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageRequest } as PageRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.bytes();
break;
case 2:
message.offset = longToNumber(reader.uint64() as Long);
break;
case 3:
message.limit = longToNumber(reader.uint64() as Long);
break;
case 4:
message.count_total = reader.bool();
break;
case 5:
message.reverse = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = bytesFromBase64(object.key);
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = Number(object.offset);
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = Number(object.limit);
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = Boolean(object.count_total);
} else {
message.count_total = false;
}
if (object.reverse !== undefined && object.reverse !== null) {
message.reverse = Boolean(object.reverse);
} else {
message.reverse = false;
}
return message;
},
toJSON(message: PageRequest): unknown {
const obj: any = {};
message.key !== undefined &&
(obj.key = base64FromBytes(
message.key !== undefined ? message.key : new Uint8Array()
));
message.offset !== undefined && (obj.offset = message.offset);
message.limit !== undefined && (obj.limit = message.limit);
message.count_total !== undefined &&
(obj.count_total = message.count_total);
message.reverse !== undefined && (obj.reverse = message.reverse);
return obj;
},
fromPartial(object: DeepPartial<PageRequest>): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = new Uint8Array();
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = object.offset;
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = object.limit;
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = object.count_total;
} else {
message.count_total = false;
}
if (object.reverse !== undefined && object.reverse !== null) {
message.reverse = object.reverse;
} else {
message.reverse = false;
}
return message;
},
};
const basePageResponse: object = { total: 0 };
export const PageResponse = {
encode(message: PageResponse, writer: Writer = Writer.create()): Writer {
if (message.next_key.length !== 0) {
writer.uint32(10).bytes(message.next_key);
}
if (message.total !== 0) {
writer.uint32(16).uint64(message.total);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageResponse } as PageResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.next_key = reader.bytes();
break;
case 2:
message.total = longToNumber(reader.uint64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = bytesFromBase64(object.next_key);
}
if (object.total !== undefined && object.total !== null) {
message.total = Number(object.total);
} else {
message.total = 0;
}
return message;
},
toJSON(message: PageResponse): unknown {
const obj: any = {};
message.next_key !== undefined &&
(obj.next_key = base64FromBytes(
message.next_key !== undefined ? message.next_key : new Uint8Array()
));
message.total !== undefined && (obj.total = message.total);
return obj;
},
fromPartial(object: DeepPartial<PageResponse>): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = object.next_key;
} else {
message.next_key = new Uint8Array();
}
if (object.total !== undefined && object.total !== null) {
message.total = object.total;
} else {
message.total = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "cosmos_proto";

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "gogoproto";

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "google.api";

View File

@ -0,0 +1,706 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "google.api";
/**
* Defines the HTTP configuration for an API service. It contains a list of
* [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
* to one or more HTTP REST API methods.
*/
export interface Http {
/**
* A list of HTTP configuration rules that apply to individual API methods.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
*/
rules: HttpRule[];
/**
* When set to true, URL path parmeters will be fully URI-decoded except in
* cases of single segment matches in reserved expansion, where "%2F" will be
* left encoded.
*
* The default behavior is to not decode RFC 6570 reserved characters in multi
* segment matches.
*/
fully_decode_reserved_expansion: boolean;
}
/**
* `HttpRule` defines the mapping of an RPC method to one or more HTTP
* REST API methods. The mapping specifies how different portions of the RPC
* request message are mapped to URL path, URL query parameters, and
* HTTP request body. The mapping is typically specified as an
* `google.api.http` annotation on the RPC method,
* see "google/api/annotations.proto" for details.
*
* The mapping consists of a field specifying the path template and
* method kind. The path template can refer to fields in the request
* message, as in the example below which describes a REST GET
* operation on a resource collection of messages:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* SubMessage sub = 2; // `sub.subfield` is url-mapped
* }
* message Message {
* string text = 1; // content of the resource
* }
*
* The same http annotation can alternatively be expressed inside the
* `GRPC API Configuration` YAML file.
*
* http:
* rules:
* - selector: <proto_package_name>.Messaging.GetMessage
* get: /v1/messages/{message_id}/{sub.subfield}
*
* This definition enables an automatic, bidrectional mapping of HTTP
* JSON to RPC. Example:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))`
*
* In general, not only fields but also field paths can be referenced
* from a path pattern. Fields mapped to the path pattern cannot be
* repeated and must have a primitive (non-message) type.
*
* Any fields in the request message which are not bound by the path
* pattern automatically become (optional) HTTP query
* parameters. Assume the following definition of the request message:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* int64 revision = 2; // becomes a parameter
* SubMessage sub = 3; // `sub.subfield` becomes a parameter
* }
*
*
* This enables a HTTP JSON to RPC mapping as below:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))`
*
* Note that fields which are mapped to HTTP parameters must have a
* primitive type or a repeated primitive type. Message types are not
* allowed. In the case of a repeated type, the parameter can be
* repeated in the URL, as in `...?param=A&param=B`.
*
* For HTTP method kinds which allow a request body, the `body` field
* specifies the mapping. Consider a REST update method on the
* message resource collection:
*
*
* service Messaging {
* rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "message"
* };
* }
* }
* message UpdateMessageRequest {
* string message_id = 1; // mapped to the URL
* Message message = 2; // mapped to the body
* }
*
*
* The following HTTP JSON to RPC mapping is enabled, where the
* representation of the JSON in the request body is determined by
* protos JSON encoding:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
*
* The special name `*` can be used in the body mapping to define that
* every field not bound by the path template should be mapped to the
* request body. This enables the following alternative definition of
* the update method:
*
* service Messaging {
* rpc UpdateMessage(Message) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "*"
* };
* }
* }
* message Message {
* string message_id = 1;
* string text = 2;
* }
*
*
* The following HTTP JSON to RPC mapping is enabled:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")`
*
* Note that when using `*` in the body mapping, it is not possible to
* have HTTP parameters, as all fields not bound by the path end in
* the body. This makes this option more rarely used in practice of
* defining REST APIs. The common usage of `*` is in custom methods
* which don't use the URL at all for transferring data.
*
* It is possible to define multiple HTTP methods for one RPC by using
* the `additional_bindings` option. Example:
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http) = {
* get: "/v1/messages/{message_id}"
* additional_bindings {
* get: "/v1/users/{user_id}/messages/{message_id}"
* }
* };
* }
* }
* message GetMessageRequest {
* string message_id = 1;
* string user_id = 2;
* }
*
*
* This enables the following two alternative HTTP JSON to RPC
* mappings:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
* `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")`
*
* # Rules for HTTP mapping
*
* The rules for mapping HTTP path, query parameters, and body fields
* to the request message are as follows:
*
* 1. The `body` field specifies either `*` or a field path, or is
* omitted. If omitted, it indicates there is no HTTP request body.
* 2. Leaf fields (recursive expansion of nested messages in the
* request) can be classified into three types:
* (a) Matched in the URL template.
* (b) Covered by body (if body is `*`, everything except (a) fields;
* else everything under the body field)
* (c) All other fields.
* 3. URL query parameters found in the HTTP request are mapped to (c) fields.
* 4. Any body sent with an HTTP request can contain only (b) fields.
*
* The syntax of the path template is as follows:
*
* Template = "/" Segments [ Verb ] ;
* Segments = Segment { "/" Segment } ;
* Segment = "*" | "**" | LITERAL | Variable ;
* Variable = "{" FieldPath [ "=" Segments ] "}" ;
* FieldPath = IDENT { "." IDENT } ;
* Verb = ":" LITERAL ;
*
* The syntax `*` matches a single path segment. The syntax `**` matches zero
* or more path segments, which must be the last part of the path except the
* `Verb`. The syntax `LITERAL` matches literal text in the path.
*
* The syntax `Variable` matches part of the URL path as specified by its
* template. A variable template must not contain other variables. If a variable
* matches a single path segment, its template may be omitted, e.g. `{var}`
* is equivalent to `{var=*}`.
*
* If a variable contains exactly one path segment, such as `"{var}"` or
* `"{var=*}"`, when such a variable is expanded into a URL path, all characters
* except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the
* Discovery Document as `{var}`.
*
* If a variable contains one or more path segments, such as `"{var=foo/*}"`
* or `"{var=**}"`, when such a variable is expanded into a URL path, all
* characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables
* show up in the Discovery Document as `{+var}`.
*
* NOTE: While the single segment variable matches the semantics of
* [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2
* Simple String Expansion, the multi segment variable **does not** match
* RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion
* does not expand special characters like `?` and `#`, which would lead
* to invalid URLs.
*
* NOTE: the field paths in variables and in the `body` must not refer to
* repeated fields or map fields.
*/
export interface HttpRule {
/**
* Selects methods to which this rule applies.
*
* Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
*/
selector: string;
/** Used for listing and getting information about resources. */
get: string | undefined;
/** Used for updating a resource. */
put: string | undefined;
/** Used for creating a resource. */
post: string | undefined;
/** Used for deleting a resource. */
delete: string | undefined;
/** Used for updating a resource. */
patch: string | undefined;
/**
* The custom pattern is used for specifying an HTTP method that is not
* included in the `pattern` field, such as HEAD, or "*" to leave the
* HTTP method unspecified for this rule. The wild-card rule is useful
* for services that provide content to Web (HTML) clients.
*/
custom: CustomHttpPattern | undefined;
/**
* The name of the request field whose value is mapped to the HTTP body, or
* `*` for mapping all fields not captured by the path pattern to the HTTP
* body. NOTE: the referred field must not be a repeated field and must be
* present at the top-level of request message type.
*/
body: string;
/**
* Optional. The name of the response field whose value is mapped to the HTTP
* body of response. Other response fields are ignored. When
* not set, the response message will be used as HTTP body of response.
*/
response_body: string;
/**
* Additional HTTP bindings for the selector. Nested bindings must
* not contain an `additional_bindings` field themselves (that is,
* the nesting may only be one level deep).
*/
additional_bindings: HttpRule[];
}
/** A custom pattern is used for defining custom HTTP verb. */
export interface CustomHttpPattern {
/** The name of this custom HTTP verb. */
kind: string;
/** The path matched by this custom verb. */
path: string;
}
const baseHttp: object = { fully_decode_reserved_expansion: false };
export const Http = {
encode(message: Http, writer: Writer = Writer.create()): Writer {
for (const v of message.rules) {
HttpRule.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.fully_decode_reserved_expansion === true) {
writer.uint32(16).bool(message.fully_decode_reserved_expansion);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Http {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttp } as Http;
message.rules = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.rules.push(HttpRule.decode(reader, reader.uint32()));
break;
case 2:
message.fully_decode_reserved_expansion = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromJSON(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion = Boolean(
object.fully_decode_reserved_expansion
);
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
toJSON(message: Http): unknown {
const obj: any = {};
if (message.rules) {
obj.rules = message.rules.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.rules = [];
}
message.fully_decode_reserved_expansion !== undefined &&
(obj.fully_decode_reserved_expansion =
message.fully_decode_reserved_expansion);
return obj;
},
fromPartial(object: DeepPartial<Http>): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromPartial(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion =
object.fully_decode_reserved_expansion;
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
};
const baseHttpRule: object = { selector: "", body: "", response_body: "" };
export const HttpRule = {
encode(message: HttpRule, writer: Writer = Writer.create()): Writer {
if (message.selector !== "") {
writer.uint32(10).string(message.selector);
}
if (message.get !== undefined) {
writer.uint32(18).string(message.get);
}
if (message.put !== undefined) {
writer.uint32(26).string(message.put);
}
if (message.post !== undefined) {
writer.uint32(34).string(message.post);
}
if (message.delete !== undefined) {
writer.uint32(42).string(message.delete);
}
if (message.patch !== undefined) {
writer.uint32(50).string(message.patch);
}
if (message.custom !== undefined) {
CustomHttpPattern.encode(
message.custom,
writer.uint32(66).fork()
).ldelim();
}
if (message.body !== "") {
writer.uint32(58).string(message.body);
}
if (message.response_body !== "") {
writer.uint32(98).string(message.response_body);
}
for (const v of message.additional_bindings) {
HttpRule.encode(v!, writer.uint32(90).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): HttpRule {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.selector = reader.string();
break;
case 2:
message.get = reader.string();
break;
case 3:
message.put = reader.string();
break;
case 4:
message.post = reader.string();
break;
case 5:
message.delete = reader.string();
break;
case 6:
message.patch = reader.string();
break;
case 8:
message.custom = CustomHttpPattern.decode(reader, reader.uint32());
break;
case 7:
message.body = reader.string();
break;
case 12:
message.response_body = reader.string();
break;
case 11:
message.additional_bindings.push(
HttpRule.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = String(object.selector);
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = String(object.get);
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = String(object.put);
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = String(object.post);
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = String(object.delete);
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = String(object.patch);
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromJSON(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = String(object.body);
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = String(object.response_body);
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromJSON(e));
}
}
return message;
},
toJSON(message: HttpRule): unknown {
const obj: any = {};
message.selector !== undefined && (obj.selector = message.selector);
message.get !== undefined && (obj.get = message.get);
message.put !== undefined && (obj.put = message.put);
message.post !== undefined && (obj.post = message.post);
message.delete !== undefined && (obj.delete = message.delete);
message.patch !== undefined && (obj.patch = message.patch);
message.custom !== undefined &&
(obj.custom = message.custom
? CustomHttpPattern.toJSON(message.custom)
: undefined);
message.body !== undefined && (obj.body = message.body);
message.response_body !== undefined &&
(obj.response_body = message.response_body);
if (message.additional_bindings) {
obj.additional_bindings = message.additional_bindings.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.additional_bindings = [];
}
return obj;
},
fromPartial(object: DeepPartial<HttpRule>): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = object.selector;
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = object.get;
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = object.put;
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = object.post;
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = object.delete;
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = object.patch;
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromPartial(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = object.body;
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = object.response_body;
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromPartial(e));
}
}
return message;
},
};
const baseCustomHttpPattern: object = { kind: "", path: "" };
export const CustomHttpPattern = {
encode(message: CustomHttpPattern, writer: Writer = Writer.create()): Writer {
if (message.kind !== "") {
writer.uint32(10).string(message.kind);
}
if (message.path !== "") {
writer.uint32(18).string(message.path);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): CustomHttpPattern {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.kind = reader.string();
break;
case 2:
message.path = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = String(object.kind);
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = String(object.path);
} else {
message.path = "";
}
return message;
},
toJSON(message: CustomHttpPattern): unknown {
const obj: any = {};
message.kind !== undefined && (obj.kind = message.kind);
message.path !== undefined && (obj.path = message.path);
return obj;
},
fromPartial(object: DeepPartial<CustomHttpPattern>): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = object.kind;
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = object.path;
} else {
message.path = "";
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,240 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "google.protobuf";
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*/
export interface Any {
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*/
type_url: string;
/** Must be a valid serialized protocol buffer of the above specified type. */
value: Uint8Array;
}
const baseAny: object = { type_url: "" };
export const Any = {
encode(message: Any, writer: Writer = Writer.create()): Writer {
if (message.type_url !== "") {
writer.uint32(10).string(message.type_url);
}
if (message.value.length !== 0) {
writer.uint32(18).bytes(message.value);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Any {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseAny } as Any;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.type_url = reader.string();
break;
case 2:
message.value = reader.bytes();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Any {
const message = { ...baseAny } as Any;
if (object.type_url !== undefined && object.type_url !== null) {
message.type_url = String(object.type_url);
} else {
message.type_url = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = bytesFromBase64(object.value);
}
return message;
},
toJSON(message: Any): unknown {
const obj: any = {};
message.type_url !== undefined && (obj.type_url = message.type_url);
message.value !== undefined &&
(obj.value = base64FromBytes(
message.value !== undefined ? message.value : new Uint8Array()
));
return obj;
},
fromPartial(object: DeepPartial<Any>): Any {
const message = { ...baseAny } as Any;
if (object.type_url !== undefined && object.type_url !== null) {
message.type_url = object.type_url;
} else {
message.type_url = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = new Uint8Array();
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,18 @@
{
"name": "cosmos-auth-v1beta1-js",
"version": "0.1.0",
"description": "Autogenerated vuex store for Cosmos module cosmos.auth.v1beta1",
"author": "Starport Codegen <hello@tendermint.com>",
"homepage": "http://github.com/cosmos/cosmos-sdk/x/auth/types",
"license": "Apache-2.0",
"licenses": [
{
"type": "Apache-2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
],
"main": "index.js",
"publishConfig": {
"access": "public"
}
}

View File

@ -0,0 +1 @@
THIS FILE IS GENERATED AUTOMATICALLY. DO NOT DELETE.

View File

@ -0,0 +1,403 @@
import { txClient, queryClient, MissingWalletError , registry} from './module'
import { SendAuthorization } from "./module/types/cosmos/bank/v1beta1/authz"
import { Params } from "./module/types/cosmos/bank/v1beta1/bank"
import { SendEnabled } from "./module/types/cosmos/bank/v1beta1/bank"
import { Input } from "./module/types/cosmos/bank/v1beta1/bank"
import { Output } from "./module/types/cosmos/bank/v1beta1/bank"
import { Supply } from "./module/types/cosmos/bank/v1beta1/bank"
import { DenomUnit } from "./module/types/cosmos/bank/v1beta1/bank"
import { Metadata } from "./module/types/cosmos/bank/v1beta1/bank"
import { Balance } from "./module/types/cosmos/bank/v1beta1/genesis"
export { SendAuthorization, Params, SendEnabled, Input, Output, Supply, DenomUnit, Metadata, Balance };
async function initTxClient(vuexGetters) {
return await txClient(vuexGetters['common/wallet/signer'], {
addr: vuexGetters['common/env/apiTendermint']
})
}
async function initQueryClient(vuexGetters) {
return await queryClient({
addr: vuexGetters['common/env/apiCosmos']
})
}
function mergeResults(value, next_values) {
for (let prop of Object.keys(next_values)) {
if (Array.isArray(next_values[prop])) {
value[prop]=[...value[prop], ...next_values[prop]]
}else{
value[prop]=next_values[prop]
}
}
return value
}
function getStructure(template) {
let structure = { fields: [] }
for (const [key, value] of Object.entries(template)) {
let field: any = {}
field.name = key
field.type = typeof value
structure.fields.push(field)
}
return structure
}
const getDefaultState = () => {
return {
Balance: {},
AllBalances: {},
TotalSupply: {},
SupplyOf: {},
Params: {},
DenomMetadata: {},
DenomsMetadata: {},
_Structure: {
SendAuthorization: getStructure(SendAuthorization.fromPartial({})),
Params: getStructure(Params.fromPartial({})),
SendEnabled: getStructure(SendEnabled.fromPartial({})),
Input: getStructure(Input.fromPartial({})),
Output: getStructure(Output.fromPartial({})),
Supply: getStructure(Supply.fromPartial({})),
DenomUnit: getStructure(DenomUnit.fromPartial({})),
Metadata: getStructure(Metadata.fromPartial({})),
Balance: getStructure(Balance.fromPartial({})),
},
_Registry: registry,
_Subscriptions: new Set(),
}
}
// initial state
const state = getDefaultState()
export default {
namespaced: true,
state,
mutations: {
RESET_STATE(state) {
Object.assign(state, getDefaultState())
},
QUERY(state, { query, key, value }) {
state[query][JSON.stringify(key)] = value
},
SUBSCRIBE(state, subscription) {
state._Subscriptions.add(JSON.stringify(subscription))
},
UNSUBSCRIBE(state, subscription) {
state._Subscriptions.delete(JSON.stringify(subscription))
}
},
getters: {
getBalance: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.Balance[JSON.stringify(params)] ?? {}
},
getAllBalances: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.AllBalances[JSON.stringify(params)] ?? {}
},
getTotalSupply: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.TotalSupply[JSON.stringify(params)] ?? {}
},
getSupplyOf: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.SupplyOf[JSON.stringify(params)] ?? {}
},
getParams: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.Params[JSON.stringify(params)] ?? {}
},
getDenomMetadata: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.DenomMetadata[JSON.stringify(params)] ?? {}
},
getDenomsMetadata: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.DenomsMetadata[JSON.stringify(params)] ?? {}
},
getTypeStructure: (state) => (type) => {
return state._Structure[type].fields
},
getRegistry: (state) => {
return state._Registry
}
},
actions: {
init({ dispatch, rootGetters }) {
console.log('Vuex module: cosmos.bank.v1beta1 initialized!')
if (rootGetters['common/env/client']) {
rootGetters['common/env/client'].on('newblock', () => {
dispatch('StoreUpdate')
})
}
},
resetState({ commit }) {
commit('RESET_STATE')
},
unsubscribe({ commit }, subscription) {
commit('UNSUBSCRIBE', subscription)
},
async StoreUpdate({ state, dispatch }) {
state._Subscriptions.forEach(async (subscription) => {
try {
const sub=JSON.parse(subscription)
await dispatch(sub.action, sub.payload)
}catch(e) {
throw new Error('Subscriptions: ' + e.message)
}
})
},
async QueryBalance({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryBalance( key.address, query)).data
while (all && (<any> value).pagination && (<any> value).pagination.next_key!=null) {
let next_values=(await queryClient.queryBalance( key.address, {...query, 'pagination.key':(<any> value).pagination.next_key})).data
value = mergeResults(value, next_values);
}
commit('QUERY', { query: 'Balance', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryBalance', payload: { options: { all }, params: {...key},query }})
return getters['getBalance']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryBalance API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QueryAllBalances({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryAllBalances( key.address, query)).data
while (all && (<any> value).pagination && (<any> value).pagination.next_key!=null) {
let next_values=(await queryClient.queryAllBalances( key.address, {...query, 'pagination.key':(<any> value).pagination.next_key})).data
value = mergeResults(value, next_values);
}
commit('QUERY', { query: 'AllBalances', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryAllBalances', payload: { options: { all }, params: {...key},query }})
return getters['getAllBalances']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryAllBalances API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QueryTotalSupply({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryTotalSupply(query)).data
while (all && (<any> value).pagination && (<any> value).pagination.next_key!=null) {
let next_values=(await queryClient.queryTotalSupply({...query, 'pagination.key':(<any> value).pagination.next_key})).data
value = mergeResults(value, next_values);
}
commit('QUERY', { query: 'TotalSupply', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryTotalSupply', payload: { options: { all }, params: {...key},query }})
return getters['getTotalSupply']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryTotalSupply API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QuerySupplyOf({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.querySupplyOf( key.denom)).data
commit('QUERY', { query: 'SupplyOf', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QuerySupplyOf', payload: { options: { all }, params: {...key},query }})
return getters['getSupplyOf']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QuerySupplyOf API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QueryParams({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryParams()).data
commit('QUERY', { query: 'Params', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryParams', payload: { options: { all }, params: {...key},query }})
return getters['getParams']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryParams API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QueryDenomMetadata({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryDenomMetadata( key.denom)).data
commit('QUERY', { query: 'DenomMetadata', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryDenomMetadata', payload: { options: { all }, params: {...key},query }})
return getters['getDenomMetadata']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryDenomMetadata API Node Unavailable. Could not perform query: ' + e.message)
}
},
async QueryDenomsMetadata({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.queryDenomsMetadata(query)).data
while (all && (<any> value).pagination && (<any> value).pagination.next_key!=null) {
let next_values=(await queryClient.queryDenomsMetadata({...query, 'pagination.key':(<any> value).pagination.next_key})).data
value = mergeResults(value, next_values);
}
commit('QUERY', { query: 'DenomsMetadata', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'QueryDenomsMetadata', payload: { options: { all }, params: {...key},query }})
return getters['getDenomsMetadata']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:QueryDenomsMetadata API Node Unavailable. Could not perform query: ' + e.message)
}
},
async sendMsgMultiSend({ rootGetters }, { value, fee = [], memo = '' }) {
try {
const txClient=await initTxClient(rootGetters)
const msg = await txClient.msgMultiSend(value)
const result = await txClient.signAndBroadcast([msg], {fee: { amount: fee,
gas: "200000" }, memo})
return result
} catch (e) {
if (e == MissingWalletError) {
throw new Error('TxClient:MsgMultiSend:Init Could not initialize signing client. Wallet is required.')
}else{
throw new Error('TxClient:MsgMultiSend:Send Could not broadcast Tx: '+ e.message)
}
}
},
async sendMsgSend({ rootGetters }, { value, fee = [], memo = '' }) {
try {
const txClient=await initTxClient(rootGetters)
const msg = await txClient.msgSend(value)
const result = await txClient.signAndBroadcast([msg], {fee: { amount: fee,
gas: "200000" }, memo})
return result
} catch (e) {
if (e == MissingWalletError) {
throw new Error('TxClient:MsgSend:Init Could not initialize signing client. Wallet is required.')
}else{
throw new Error('TxClient:MsgSend:Send Could not broadcast Tx: '+ e.message)
}
}
},
async MsgMultiSend({ rootGetters }, { value }) {
try {
const txClient=await initTxClient(rootGetters)
const msg = await txClient.msgMultiSend(value)
return msg
} catch (e) {
if (e == MissingWalletError) {
throw new Error('TxClient:MsgMultiSend:Init Could not initialize signing client. Wallet is required.')
}else{
throw new Error('TxClient:MsgMultiSend:Create Could not create message: ' + e.message)
}
}
},
async MsgSend({ rootGetters }, { value }) {
try {
const txClient=await initTxClient(rootGetters)
const msg = await txClient.msgSend(value)
return msg
} catch (e) {
if (e == MissingWalletError) {
throw new Error('TxClient:MsgSend:Init Could not initialize signing client. Wallet is required.')
}else{
throw new Error('TxClient:MsgSend:Create Could not create message: ' + e.message)
}
}
},
}
}

View File

@ -0,0 +1,63 @@
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT MODIFY.
import { StdFee } from "@cosmjs/launchpad";
import { SigningStargateClient } from "@cosmjs/stargate";
import { Registry, OfflineSigner, EncodeObject, DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { Api } from "./rest";
import { MsgMultiSend } from "./types/cosmos/bank/v1beta1/tx";
import { MsgSend } from "./types/cosmos/bank/v1beta1/tx";
const types = [
["/cosmos.bank.v1beta1.MsgMultiSend", MsgMultiSend],
["/cosmos.bank.v1beta1.MsgSend", MsgSend],
];
export const MissingWalletError = new Error("wallet is required");
export const registry = new Registry(<any>types);
const defaultFee = {
amount: [],
gas: "200000",
};
interface TxClientOptions {
addr: string
}
interface SignAndBroadcastOptions {
fee: StdFee,
memo?: string
}
const txClient = async (wallet: OfflineSigner, { addr: addr }: TxClientOptions = { addr: "http://localhost:26657" }) => {
if (!wallet) throw MissingWalletError;
let client;
if (addr) {
client = await SigningStargateClient.connectWithSigner(addr, wallet, { registry });
}else{
client = await SigningStargateClient.offline( wallet, { registry });
}
const { address } = (await wallet.getAccounts())[0];
return {
signAndBroadcast: (msgs: EncodeObject[], { fee, memo }: SignAndBroadcastOptions = {fee: defaultFee, memo: ""}) => client.signAndBroadcast(address, msgs, fee,memo),
msgMultiSend: (data: MsgMultiSend): EncodeObject => ({ typeUrl: "/cosmos.bank.v1beta1.MsgMultiSend", value: MsgMultiSend.fromPartial( data ) }),
msgSend: (data: MsgSend): EncodeObject => ({ typeUrl: "/cosmos.bank.v1beta1.MsgSend", value: MsgSend.fromPartial( data ) }),
};
};
interface QueryClientOptions {
addr: string
}
const queryClient = async ({ addr: addr }: QueryClientOptions = { addr: "http://localhost:1317" }) => {
return new Api({ baseUrl: addr });
};
export {
txClient,
queryClient,
};

View File

@ -0,0 +1,596 @@
/* eslint-disable */
/* tslint:disable */
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
export interface ProtobufAny {
"@type"?: string;
}
export interface RpcStatus {
/** @format int32 */
code?: number;
message?: string;
details?: ProtobufAny[];
}
/**
* Coin defines a token with a denomination and an amount.
NOTE: The amount field is an Int which implements the custom method
signatures required by gogoproto.
*/
export interface V1Beta1Coin {
denom?: string;
amount?: string;
}
/**
* DenomUnit represents a struct that describes a given
denomination unit of the basic token.
*/
export interface V1Beta1DenomUnit {
/** denom represents the string name of the given denom unit (e.g uatom). */
denom?: string;
/**
* exponent represents power of 10 exponent that one must
* raise the base_denom to in order to equal the given DenomUnit's denom
* 1 denom = 1^exponent base_denom
* (e.g. with a base_denom of uatom, one can create a DenomUnit of 'atom' with
* exponent = 6, thus: 1 atom = 10^6 uatom).
* @format int64
*/
exponent?: number;
aliases?: string[];
}
/**
* Input models transaction input.
*/
export interface V1Beta1Input {
address?: string;
coins?: V1Beta1Coin[];
}
/**
* Metadata represents a struct that describes
a basic token.
*/
export interface V1Beta1Metadata {
description?: string;
denom_units?: V1Beta1DenomUnit[];
/** base represents the base denom (should be the DenomUnit with exponent = 0). */
base?: string;
/**
* display indicates the suggested denom that should be
* displayed in clients.
*/
display?: string;
/** Since: cosmos-sdk 0.43 */
name?: string;
/**
* symbol is the token symbol usually shown on exchanges (eg: ATOM). This can
* be the same as the display.
*
* Since: cosmos-sdk 0.43
*/
symbol?: string;
}
/**
* MsgMultiSendResponse defines the Msg/MultiSend response type.
*/
export type V1Beta1MsgMultiSendResponse = object;
/**
* MsgSendResponse defines the Msg/Send response type.
*/
export type V1Beta1MsgSendResponse = object;
/**
* Output models transaction outputs.
*/
export interface V1Beta1Output {
address?: string;
coins?: V1Beta1Coin[];
}
/**
* message SomeRequest {
Foo some_parameter = 1;
PageRequest pagination = 2;
}
*/
export interface V1Beta1PageRequest {
/**
* key is a value returned in PageResponse.next_key to begin
* querying the next page most efficiently. Only one of offset or key
* should be set.
* @format byte
*/
key?: string;
/**
* offset is a numeric offset that can be used when key is unavailable.
* It is less efficient than using key. Only one of offset or key should
* be set.
* @format uint64
*/
offset?: string;
/**
* limit is the total number of results to be returned in the result page.
* If left empty it will default to a value to be set by each app.
* @format uint64
*/
limit?: string;
/**
* count_total is set to true to indicate that the result set should include
* a count of the total number of items available for pagination in UIs.
* count_total is only respected when offset is used. It is ignored when key
* is set.
*/
count_total?: boolean;
/**
* reverse is set to true if results are to be returned in the descending order.
*
* Since: cosmos-sdk 0.43
*/
reverse?: boolean;
}
/**
* PageResponse is to be embedded in gRPC response messages where the
corresponding request message has used PageRequest.
message SomeResponse {
repeated Bar results = 1;
PageResponse page = 2;
}
*/
export interface V1Beta1PageResponse {
/** @format byte */
next_key?: string;
/** @format uint64 */
total?: string;
}
/**
* Params defines the parameters for the bank module.
*/
export interface V1Beta1Params {
send_enabled?: V1Beta1SendEnabled[];
default_send_enabled?: boolean;
}
/**
* QueryAllBalancesResponse is the response type for the Query/AllBalances RPC
method.
*/
export interface V1Beta1QueryAllBalancesResponse {
/** balances is the balances of all the coins. */
balances?: V1Beta1Coin[];
/** pagination defines the pagination in the response. */
pagination?: V1Beta1PageResponse;
}
/**
* QueryBalanceResponse is the response type for the Query/Balance RPC method.
*/
export interface V1Beta1QueryBalanceResponse {
/** balance is the balance of the coin. */
balance?: V1Beta1Coin;
}
/**
* QueryDenomMetadataResponse is the response type for the Query/DenomMetadata RPC
method.
*/
export interface V1Beta1QueryDenomMetadataResponse {
/** metadata describes and provides all the client information for the requested token. */
metadata?: V1Beta1Metadata;
}
/**
* QueryDenomsMetadataResponse is the response type for the Query/DenomsMetadata RPC
method.
*/
export interface V1Beta1QueryDenomsMetadataResponse {
/** metadata provides the client information for all the registered tokens. */
metadatas?: V1Beta1Metadata[];
/** pagination defines the pagination in the response. */
pagination?: V1Beta1PageResponse;
}
/**
* QueryParamsResponse defines the response type for querying x/bank parameters.
*/
export interface V1Beta1QueryParamsResponse {
/** Params defines the parameters for the bank module. */
params?: V1Beta1Params;
}
/**
* QuerySupplyOfResponse is the response type for the Query/SupplyOf RPC method.
*/
export interface V1Beta1QuerySupplyOfResponse {
/** amount is the supply of the coin. */
amount?: V1Beta1Coin;
}
export interface V1Beta1QueryTotalSupplyResponse {
supply?: V1Beta1Coin[];
/**
* pagination defines the pagination in the response.
*
* Since: cosmos-sdk 0.43
*/
pagination?: V1Beta1PageResponse;
}
/**
* SendEnabled maps coin denom to a send_enabled status (whether a denom is
sendable).
*/
export interface V1Beta1SendEnabled {
denom?: string;
enabled?: boolean;
}
export type QueryParamsType = Record<string | number, any>;
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
export interface FullRequestParams extends Omit<RequestInit, "body"> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: keyof Omit<Body, "body" | "bodyUsed">;
/** request body */
body?: unknown;
/** base url */
baseUrl?: string;
/** request cancellation token */
cancelToken?: CancelToken;
}
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
export interface ApiConfig<SecurityDataType = unknown> {
baseUrl?: string;
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
securityWorker?: (securityData: SecurityDataType) => RequestParams | void;
}
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
data: D;
error: E;
}
type CancelToken = Symbol | string | number;
export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
}
export class HttpClient<SecurityDataType = unknown> {
public baseUrl: string = "";
private securityData: SecurityDataType = null as any;
private securityWorker: null | ApiConfig<SecurityDataType>["securityWorker"] = null;
private abortControllers = new Map<CancelToken, AbortController>();
private baseApiParams: RequestParams = {
credentials: "same-origin",
headers: {},
redirect: "follow",
referrerPolicy: "no-referrer",
};
constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
Object.assign(this, apiConfig);
}
public setSecurityData = (data: SecurityDataType) => {
this.securityData = data;
};
private addQueryParam(query: QueryParamsType, key: string) {
const value = query[key];
return (
encodeURIComponent(key) +
"=" +
encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`)
);
}
protected toQueryString(rawQuery?: QueryParamsType): string {
const query = rawQuery || {};
const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
return keys
.map((key) =>
typeof query[key] === "object" && !Array.isArray(query[key])
? this.toQueryString(query[key] as QueryParamsType)
: this.addQueryParam(query, key),
)
.join("&");
}
protected addQueryParams(rawQuery?: QueryParamsType): string {
const queryString = this.toQueryString(rawQuery);
return queryString ? `?${queryString}` : "";
}
private contentFormatters: Record<ContentType, (input: any) => any> = {
[ContentType.Json]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
[ContentType.FormData]: (input: any) =>
Object.keys(input || {}).reduce((data, key) => {
data.append(key, input[key]);
return data;
}, new FormData()),
[ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
};
private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
return {
...this.baseApiParams,
...params1,
...(params2 || {}),
headers: {
...(this.baseApiParams.headers || {}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
if (this.abortControllers.has(cancelToken)) {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
return abortController.signal;
}
return void 0;
}
const abortController = new AbortController();
this.abortControllers.set(cancelToken, abortController);
return abortController.signal;
};
public abortRequest = (cancelToken: CancelToken) => {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
abortController.abort();
this.abortControllers.delete(cancelToken);
}
};
public request = <T = any, E = any>({
body,
secure,
path,
type,
query,
format = "json",
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
...requestParams,
headers: {
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
...(requestParams.headers || {}),
},
signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
}).then(async (response) => {
const r = response as HttpResponse<T, E>;
r.data = (null as unknown) as T;
r.error = (null as unknown) as E;
const data = await response[format]()
.then((data) => {
if (r.ok) {
r.data = data;
} else {
r.error = data;
}
return r;
})
.catch((e) => {
r.error = e;
return r;
});
if (cancelToken) {
this.abortControllers.delete(cancelToken);
}
if (!response.ok) throw data;
return data;
});
};
}
/**
* @title cosmos/bank/v1beta1/authz.proto
* @version version not set
*/
export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
/**
* No description
*
* @tags Query
* @name QueryAllBalances
* @summary AllBalances queries the balance of all coins for a single account.
* @request GET:/cosmos/bank/v1beta1/balances/{address}
*/
queryAllBalances = (
address: string,
query?: {
"pagination.key"?: string;
"pagination.offset"?: string;
"pagination.limit"?: string;
"pagination.count_total"?: boolean;
"pagination.reverse"?: boolean;
},
params: RequestParams = {},
) =>
this.request<V1Beta1QueryAllBalancesResponse, RpcStatus>({
path: `/cosmos/bank/v1beta1/balances/${address}`,
method: "GET",
query: query,
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QueryBalance
* @summary Balance queries the balance of a single coin for a single account.
* @request GET:/cosmos/bank/v1beta1/balances/{address}/by_denom
*/
queryBalance = (address: string, query?: { denom?: string }, params: RequestParams = {}) =>
this.request<V1Beta1QueryBalanceResponse, RpcStatus>({
path: `/cosmos/bank/v1beta1/balances/${address}/by_denom`,
method: "GET",
query: query,
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QueryDenomsMetadata
* @summary DenomsMetadata queries the client metadata for all registered coin denominations.
* @request GET:/cosmos/bank/v1beta1/denoms_metadata
*/
queryDenomsMetadata = (
query?: {
"pagination.key"?: string;
"pagination.offset"?: string;
"pagination.limit"?: string;
"pagination.count_total"?: boolean;
"pagination.reverse"?: boolean;
},
params: RequestParams = {},
) =>
this.request<V1Beta1QueryDenomsMetadataResponse, RpcStatus>({
path: `/cosmos/bank/v1beta1/denoms_metadata`,
method: "GET",
query: query,
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QueryDenomMetadata
* @summary DenomsMetadata queries the client metadata of a given coin denomination.
* @request GET:/cosmos/bank/v1beta1/denoms_metadata/{denom}
*/
queryDenomMetadata = (denom: string, params: RequestParams = {}) =>
this.request<V1Beta1QueryDenomMetadataResponse, RpcStatus>({
path: `/cosmos/bank/v1beta1/denoms_metadata/${denom}`,
method: "GET",
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QueryParams
* @summary Params queries the parameters of x/bank module.
* @request GET:/cosmos/bank/v1beta1/params
*/
queryParams = (params: RequestParams = {}) =>
this.request<V1Beta1QueryParamsResponse, RpcStatus>({
path: `/cosmos/bank/v1beta1/params`,
method: "GET",
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QueryTotalSupply
* @summary TotalSupply queries the total supply of all coins.
* @request GET:/cosmos/bank/v1beta1/supply
*/
queryTotalSupply = (
query?: {
"pagination.key"?: string;
"pagination.offset"?: string;
"pagination.limit"?: string;
"pagination.count_total"?: boolean;
"pagination.reverse"?: boolean;
},
params: RequestParams = {},
) =>
this.request<V1Beta1QueryTotalSupplyResponse, RpcStatus>({
path: `/cosmos/bank/v1beta1/supply`,
method: "GET",
query: query,
format: "json",
...params,
});
/**
* No description
*
* @tags Query
* @name QuerySupplyOf
* @summary SupplyOf queries the supply of a single coin.
* @request GET:/cosmos/bank/v1beta1/supply/{denom}
*/
querySupplyOf = (denom: string, params: RequestParams = {}) =>
this.request<V1Beta1QuerySupplyOfResponse, RpcStatus>({
path: `/cosmos/bank/v1beta1/supply/${denom}`,
method: "GET",
format: "json",
...params,
});
}

View File

@ -0,0 +1,90 @@
/* eslint-disable */
import { Coin } from "../../../cosmos/base/v1beta1/coin";
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.bank.v1beta1";
/**
* SendAuthorization allows the grantee to spend up to spend_limit coins from
* the granter's account.
*
* Since: cosmos-sdk 0.43
*/
export interface SendAuthorization {
spend_limit: Coin[];
}
const baseSendAuthorization: object = {};
export const SendAuthorization = {
encode(message: SendAuthorization, writer: Writer = Writer.create()): Writer {
for (const v of message.spend_limit) {
Coin.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): SendAuthorization {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSendAuthorization } as SendAuthorization;
message.spend_limit = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.spend_limit.push(Coin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SendAuthorization {
const message = { ...baseSendAuthorization } as SendAuthorization;
message.spend_limit = [];
if (object.spend_limit !== undefined && object.spend_limit !== null) {
for (const e of object.spend_limit) {
message.spend_limit.push(Coin.fromJSON(e));
}
}
return message;
},
toJSON(message: SendAuthorization): unknown {
const obj: any = {};
if (message.spend_limit) {
obj.spend_limit = message.spend_limit.map((e) =>
e ? Coin.toJSON(e) : undefined
);
} else {
obj.spend_limit = [];
}
return obj;
},
fromPartial(object: DeepPartial<SendAuthorization>): SendAuthorization {
const message = { ...baseSendAuthorization } as SendAuthorization;
message.spend_limit = [];
if (object.spend_limit !== undefined && object.spend_limit !== null) {
for (const e of object.spend_limit) {
message.spend_limit.push(Coin.fromPartial(e));
}
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,737 @@
/* eslint-disable */
import { Coin } from "../../../cosmos/base/v1beta1/coin";
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.bank.v1beta1";
/** Params defines the parameters for the bank module. */
export interface Params {
send_enabled: SendEnabled[];
default_send_enabled: boolean;
}
/**
* SendEnabled maps coin denom to a send_enabled status (whether a denom is
* sendable).
*/
export interface SendEnabled {
denom: string;
enabled: boolean;
}
/** Input models transaction input. */
export interface Input {
address: string;
coins: Coin[];
}
/** Output models transaction outputs. */
export interface Output {
address: string;
coins: Coin[];
}
/**
* Supply represents a struct that passively keeps track of the total supply
* amounts in the network.
* This message is deprecated now that supply is indexed by denom.
*
* @deprecated
*/
export interface Supply {
total: Coin[];
}
/**
* DenomUnit represents a struct that describes a given
* denomination unit of the basic token.
*/
export interface DenomUnit {
/** denom represents the string name of the given denom unit (e.g uatom). */
denom: string;
/**
* exponent represents power of 10 exponent that one must
* raise the base_denom to in order to equal the given DenomUnit's denom
* 1 denom = 1^exponent base_denom
* (e.g. with a base_denom of uatom, one can create a DenomUnit of 'atom' with
* exponent = 6, thus: 1 atom = 10^6 uatom).
*/
exponent: number;
/** aliases is a list of string aliases for the given denom */
aliases: string[];
}
/**
* Metadata represents a struct that describes
* a basic token.
*/
export interface Metadata {
description: string;
/** denom_units represents the list of DenomUnit's for a given coin */
denom_units: DenomUnit[];
/** base represents the base denom (should be the DenomUnit with exponent = 0). */
base: string;
/**
* display indicates the suggested denom that should be
* displayed in clients.
*/
display: string;
/**
* name defines the name of the token (eg: Cosmos Atom)
*
* Since: cosmos-sdk 0.43
*/
name: string;
/**
* symbol is the token symbol usually shown on exchanges (eg: ATOM). This can
* be the same as the display.
*
* Since: cosmos-sdk 0.43
*/
symbol: string;
}
const baseParams: object = { default_send_enabled: false };
export const Params = {
encode(message: Params, writer: Writer = Writer.create()): Writer {
for (const v of message.send_enabled) {
SendEnabled.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.default_send_enabled === true) {
writer.uint32(16).bool(message.default_send_enabled);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Params {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseParams } as Params;
message.send_enabled = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.send_enabled.push(
SendEnabled.decode(reader, reader.uint32())
);
break;
case 2:
message.default_send_enabled = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Params {
const message = { ...baseParams } as Params;
message.send_enabled = [];
if (object.send_enabled !== undefined && object.send_enabled !== null) {
for (const e of object.send_enabled) {
message.send_enabled.push(SendEnabled.fromJSON(e));
}
}
if (
object.default_send_enabled !== undefined &&
object.default_send_enabled !== null
) {
message.default_send_enabled = Boolean(object.default_send_enabled);
} else {
message.default_send_enabled = false;
}
return message;
},
toJSON(message: Params): unknown {
const obj: any = {};
if (message.send_enabled) {
obj.send_enabled = message.send_enabled.map((e) =>
e ? SendEnabled.toJSON(e) : undefined
);
} else {
obj.send_enabled = [];
}
message.default_send_enabled !== undefined &&
(obj.default_send_enabled = message.default_send_enabled);
return obj;
},
fromPartial(object: DeepPartial<Params>): Params {
const message = { ...baseParams } as Params;
message.send_enabled = [];
if (object.send_enabled !== undefined && object.send_enabled !== null) {
for (const e of object.send_enabled) {
message.send_enabled.push(SendEnabled.fromPartial(e));
}
}
if (
object.default_send_enabled !== undefined &&
object.default_send_enabled !== null
) {
message.default_send_enabled = object.default_send_enabled;
} else {
message.default_send_enabled = false;
}
return message;
},
};
const baseSendEnabled: object = { denom: "", enabled: false };
export const SendEnabled = {
encode(message: SendEnabled, writer: Writer = Writer.create()): Writer {
if (message.denom !== "") {
writer.uint32(10).string(message.denom);
}
if (message.enabled === true) {
writer.uint32(16).bool(message.enabled);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): SendEnabled {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSendEnabled } as SendEnabled;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.denom = reader.string();
break;
case 2:
message.enabled = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SendEnabled {
const message = { ...baseSendEnabled } as SendEnabled;
if (object.denom !== undefined && object.denom !== null) {
message.denom = String(object.denom);
} else {
message.denom = "";
}
if (object.enabled !== undefined && object.enabled !== null) {
message.enabled = Boolean(object.enabled);
} else {
message.enabled = false;
}
return message;
},
toJSON(message: SendEnabled): unknown {
const obj: any = {};
message.denom !== undefined && (obj.denom = message.denom);
message.enabled !== undefined && (obj.enabled = message.enabled);
return obj;
},
fromPartial(object: DeepPartial<SendEnabled>): SendEnabled {
const message = { ...baseSendEnabled } as SendEnabled;
if (object.denom !== undefined && object.denom !== null) {
message.denom = object.denom;
} else {
message.denom = "";
}
if (object.enabled !== undefined && object.enabled !== null) {
message.enabled = object.enabled;
} else {
message.enabled = false;
}
return message;
},
};
const baseInput: object = { address: "" };
export const Input = {
encode(message: Input, writer: Writer = Writer.create()): Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
for (const v of message.coins) {
Coin.encode(v!, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Input {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseInput } as Input;
message.coins = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
case 2:
message.coins.push(Coin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Input {
const message = { ...baseInput } as Input;
message.coins = [];
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
if (object.coins !== undefined && object.coins !== null) {
for (const e of object.coins) {
message.coins.push(Coin.fromJSON(e));
}
}
return message;
},
toJSON(message: Input): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
if (message.coins) {
obj.coins = message.coins.map((e) => (e ? Coin.toJSON(e) : undefined));
} else {
obj.coins = [];
}
return obj;
},
fromPartial(object: DeepPartial<Input>): Input {
const message = { ...baseInput } as Input;
message.coins = [];
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
if (object.coins !== undefined && object.coins !== null) {
for (const e of object.coins) {
message.coins.push(Coin.fromPartial(e));
}
}
return message;
},
};
const baseOutput: object = { address: "" };
export const Output = {
encode(message: Output, writer: Writer = Writer.create()): Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
for (const v of message.coins) {
Coin.encode(v!, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Output {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseOutput } as Output;
message.coins = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
case 2:
message.coins.push(Coin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Output {
const message = { ...baseOutput } as Output;
message.coins = [];
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
if (object.coins !== undefined && object.coins !== null) {
for (const e of object.coins) {
message.coins.push(Coin.fromJSON(e));
}
}
return message;
},
toJSON(message: Output): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
if (message.coins) {
obj.coins = message.coins.map((e) => (e ? Coin.toJSON(e) : undefined));
} else {
obj.coins = [];
}
return obj;
},
fromPartial(object: DeepPartial<Output>): Output {
const message = { ...baseOutput } as Output;
message.coins = [];
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
if (object.coins !== undefined && object.coins !== null) {
for (const e of object.coins) {
message.coins.push(Coin.fromPartial(e));
}
}
return message;
},
};
const baseSupply: object = {};
export const Supply = {
encode(message: Supply, writer: Writer = Writer.create()): Writer {
for (const v of message.total) {
Coin.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Supply {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSupply } as Supply;
message.total = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.total.push(Coin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Supply {
const message = { ...baseSupply } as Supply;
message.total = [];
if (object.total !== undefined && object.total !== null) {
for (const e of object.total) {
message.total.push(Coin.fromJSON(e));
}
}
return message;
},
toJSON(message: Supply): unknown {
const obj: any = {};
if (message.total) {
obj.total = message.total.map((e) => (e ? Coin.toJSON(e) : undefined));
} else {
obj.total = [];
}
return obj;
},
fromPartial(object: DeepPartial<Supply>): Supply {
const message = { ...baseSupply } as Supply;
message.total = [];
if (object.total !== undefined && object.total !== null) {
for (const e of object.total) {
message.total.push(Coin.fromPartial(e));
}
}
return message;
},
};
const baseDenomUnit: object = { denom: "", exponent: 0, aliases: "" };
export const DenomUnit = {
encode(message: DenomUnit, writer: Writer = Writer.create()): Writer {
if (message.denom !== "") {
writer.uint32(10).string(message.denom);
}
if (message.exponent !== 0) {
writer.uint32(16).uint32(message.exponent);
}
for (const v of message.aliases) {
writer.uint32(26).string(v!);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): DenomUnit {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDenomUnit } as DenomUnit;
message.aliases = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.denom = reader.string();
break;
case 2:
message.exponent = reader.uint32();
break;
case 3:
message.aliases.push(reader.string());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DenomUnit {
const message = { ...baseDenomUnit } as DenomUnit;
message.aliases = [];
if (object.denom !== undefined && object.denom !== null) {
message.denom = String(object.denom);
} else {
message.denom = "";
}
if (object.exponent !== undefined && object.exponent !== null) {
message.exponent = Number(object.exponent);
} else {
message.exponent = 0;
}
if (object.aliases !== undefined && object.aliases !== null) {
for (const e of object.aliases) {
message.aliases.push(String(e));
}
}
return message;
},
toJSON(message: DenomUnit): unknown {
const obj: any = {};
message.denom !== undefined && (obj.denom = message.denom);
message.exponent !== undefined && (obj.exponent = message.exponent);
if (message.aliases) {
obj.aliases = message.aliases.map((e) => e);
} else {
obj.aliases = [];
}
return obj;
},
fromPartial(object: DeepPartial<DenomUnit>): DenomUnit {
const message = { ...baseDenomUnit } as DenomUnit;
message.aliases = [];
if (object.denom !== undefined && object.denom !== null) {
message.denom = object.denom;
} else {
message.denom = "";
}
if (object.exponent !== undefined && object.exponent !== null) {
message.exponent = object.exponent;
} else {
message.exponent = 0;
}
if (object.aliases !== undefined && object.aliases !== null) {
for (const e of object.aliases) {
message.aliases.push(e);
}
}
return message;
},
};
const baseMetadata: object = {
description: "",
base: "",
display: "",
name: "",
symbol: "",
};
export const Metadata = {
encode(message: Metadata, writer: Writer = Writer.create()): Writer {
if (message.description !== "") {
writer.uint32(10).string(message.description);
}
for (const v of message.denom_units) {
DenomUnit.encode(v!, writer.uint32(18).fork()).ldelim();
}
if (message.base !== "") {
writer.uint32(26).string(message.base);
}
if (message.display !== "") {
writer.uint32(34).string(message.display);
}
if (message.name !== "") {
writer.uint32(42).string(message.name);
}
if (message.symbol !== "") {
writer.uint32(50).string(message.symbol);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Metadata {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMetadata } as Metadata;
message.denom_units = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.description = reader.string();
break;
case 2:
message.denom_units.push(DenomUnit.decode(reader, reader.uint32()));
break;
case 3:
message.base = reader.string();
break;
case 4:
message.display = reader.string();
break;
case 5:
message.name = reader.string();
break;
case 6:
message.symbol = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Metadata {
const message = { ...baseMetadata } as Metadata;
message.denom_units = [];
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.denom_units !== undefined && object.denom_units !== null) {
for (const e of object.denom_units) {
message.denom_units.push(DenomUnit.fromJSON(e));
}
}
if (object.base !== undefined && object.base !== null) {
message.base = String(object.base);
} else {
message.base = "";
}
if (object.display !== undefined && object.display !== null) {
message.display = String(object.display);
} else {
message.display = "";
}
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = "";
}
if (object.symbol !== undefined && object.symbol !== null) {
message.symbol = String(object.symbol);
} else {
message.symbol = "";
}
return message;
},
toJSON(message: Metadata): unknown {
const obj: any = {};
message.description !== undefined &&
(obj.description = message.description);
if (message.denom_units) {
obj.denom_units = message.denom_units.map((e) =>
e ? DenomUnit.toJSON(e) : undefined
);
} else {
obj.denom_units = [];
}
message.base !== undefined && (obj.base = message.base);
message.display !== undefined && (obj.display = message.display);
message.name !== undefined && (obj.name = message.name);
message.symbol !== undefined && (obj.symbol = message.symbol);
return obj;
},
fromPartial(object: DeepPartial<Metadata>): Metadata {
const message = { ...baseMetadata } as Metadata;
message.denom_units = [];
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.denom_units !== undefined && object.denom_units !== null) {
for (const e of object.denom_units) {
message.denom_units.push(DenomUnit.fromPartial(e));
}
}
if (object.base !== undefined && object.base !== null) {
message.base = object.base;
} else {
message.base = "";
}
if (object.display !== undefined && object.display !== null) {
message.display = object.display;
} else {
message.display = "";
}
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = "";
}
if (object.symbol !== undefined && object.symbol !== null) {
message.symbol = object.symbol;
} else {
message.symbol = "";
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,254 @@
/* eslint-disable */
import { Params, Metadata } from "../../../cosmos/bank/v1beta1/bank";
import { Coin } from "../../../cosmos/base/v1beta1/coin";
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.bank.v1beta1";
/** GenesisState defines the bank module's genesis state. */
export interface GenesisState {
/** params defines all the paramaters of the module. */
params: Params | undefined;
/** balances is an array containing the balances of all the accounts. */
balances: Balance[];
/**
* supply represents the total supply. If it is left empty, then supply will be calculated based on the provided
* balances. Otherwise, it will be used to validate that the sum of the balances equals this amount.
*/
supply: Coin[];
/** denom_metadata defines the metadata of the differents coins. */
denom_metadata: Metadata[];
}
/**
* Balance defines an account address and balance pair used in the bank module's
* genesis state.
*/
export interface Balance {
/** address is the address of the balance holder. */
address: string;
/** coins defines the different coins this balance holds. */
coins: Coin[];
}
const baseGenesisState: object = {};
export const GenesisState = {
encode(message: GenesisState, writer: Writer = Writer.create()): Writer {
if (message.params !== undefined) {
Params.encode(message.params, writer.uint32(10).fork()).ldelim();
}
for (const v of message.balances) {
Balance.encode(v!, writer.uint32(18).fork()).ldelim();
}
for (const v of message.supply) {
Coin.encode(v!, writer.uint32(26).fork()).ldelim();
}
for (const v of message.denom_metadata) {
Metadata.encode(v!, writer.uint32(34).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): GenesisState {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseGenesisState } as GenesisState;
message.balances = [];
message.supply = [];
message.denom_metadata = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.params = Params.decode(reader, reader.uint32());
break;
case 2:
message.balances.push(Balance.decode(reader, reader.uint32()));
break;
case 3:
message.supply.push(Coin.decode(reader, reader.uint32()));
break;
case 4:
message.denom_metadata.push(Metadata.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): GenesisState {
const message = { ...baseGenesisState } as GenesisState;
message.balances = [];
message.supply = [];
message.denom_metadata = [];
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromJSON(object.params);
} else {
message.params = undefined;
}
if (object.balances !== undefined && object.balances !== null) {
for (const e of object.balances) {
message.balances.push(Balance.fromJSON(e));
}
}
if (object.supply !== undefined && object.supply !== null) {
for (const e of object.supply) {
message.supply.push(Coin.fromJSON(e));
}
}
if (object.denom_metadata !== undefined && object.denom_metadata !== null) {
for (const e of object.denom_metadata) {
message.denom_metadata.push(Metadata.fromJSON(e));
}
}
return message;
},
toJSON(message: GenesisState): unknown {
const obj: any = {};
message.params !== undefined &&
(obj.params = message.params ? Params.toJSON(message.params) : undefined);
if (message.balances) {
obj.balances = message.balances.map((e) =>
e ? Balance.toJSON(e) : undefined
);
} else {
obj.balances = [];
}
if (message.supply) {
obj.supply = message.supply.map((e) => (e ? Coin.toJSON(e) : undefined));
} else {
obj.supply = [];
}
if (message.denom_metadata) {
obj.denom_metadata = message.denom_metadata.map((e) =>
e ? Metadata.toJSON(e) : undefined
);
} else {
obj.denom_metadata = [];
}
return obj;
},
fromPartial(object: DeepPartial<GenesisState>): GenesisState {
const message = { ...baseGenesisState } as GenesisState;
message.balances = [];
message.supply = [];
message.denom_metadata = [];
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromPartial(object.params);
} else {
message.params = undefined;
}
if (object.balances !== undefined && object.balances !== null) {
for (const e of object.balances) {
message.balances.push(Balance.fromPartial(e));
}
}
if (object.supply !== undefined && object.supply !== null) {
for (const e of object.supply) {
message.supply.push(Coin.fromPartial(e));
}
}
if (object.denom_metadata !== undefined && object.denom_metadata !== null) {
for (const e of object.denom_metadata) {
message.denom_metadata.push(Metadata.fromPartial(e));
}
}
return message;
},
};
const baseBalance: object = { address: "" };
export const Balance = {
encode(message: Balance, writer: Writer = Writer.create()): Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
for (const v of message.coins) {
Coin.encode(v!, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Balance {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBalance } as Balance;
message.coins = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
case 2:
message.coins.push(Coin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Balance {
const message = { ...baseBalance } as Balance;
message.coins = [];
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
if (object.coins !== undefined && object.coins !== null) {
for (const e of object.coins) {
message.coins.push(Coin.fromJSON(e));
}
}
return message;
},
toJSON(message: Balance): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
if (message.coins) {
obj.coins = message.coins.map((e) => (e ? Coin.toJSON(e) : undefined));
} else {
obj.coins = [];
}
return obj;
},
fromPartial(object: DeepPartial<Balance>): Balance {
const message = { ...baseBalance } as Balance;
message.coins = [];
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
if (object.coins !== undefined && object.coins !== null) {
for (const e of object.coins) {
message.coins.push(Coin.fromPartial(e));
}
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,337 @@
/* eslint-disable */
import { Reader, Writer } from "protobufjs/minimal";
import { Coin } from "../../../cosmos/base/v1beta1/coin";
import { Input, Output } from "../../../cosmos/bank/v1beta1/bank";
export const protobufPackage = "cosmos.bank.v1beta1";
/** MsgSend represents a message to send coins from one account to another. */
export interface MsgSend {
from_address: string;
to_address: string;
amount: Coin[];
}
/** MsgSendResponse defines the Msg/Send response type. */
export interface MsgSendResponse {}
/** MsgMultiSend represents an arbitrary multi-in, multi-out send message. */
export interface MsgMultiSend {
inputs: Input[];
outputs: Output[];
}
/** MsgMultiSendResponse defines the Msg/MultiSend response type. */
export interface MsgMultiSendResponse {}
const baseMsgSend: object = { from_address: "", to_address: "" };
export const MsgSend = {
encode(message: MsgSend, writer: Writer = Writer.create()): Writer {
if (message.from_address !== "") {
writer.uint32(10).string(message.from_address);
}
if (message.to_address !== "") {
writer.uint32(18).string(message.to_address);
}
for (const v of message.amount) {
Coin.encode(v!, writer.uint32(26).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): MsgSend {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgSend } as MsgSend;
message.amount = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.from_address = reader.string();
break;
case 2:
message.to_address = reader.string();
break;
case 3:
message.amount.push(Coin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): MsgSend {
const message = { ...baseMsgSend } as MsgSend;
message.amount = [];
if (object.from_address !== undefined && object.from_address !== null) {
message.from_address = String(object.from_address);
} else {
message.from_address = "";
}
if (object.to_address !== undefined && object.to_address !== null) {
message.to_address = String(object.to_address);
} else {
message.to_address = "";
}
if (object.amount !== undefined && object.amount !== null) {
for (const e of object.amount) {
message.amount.push(Coin.fromJSON(e));
}
}
return message;
},
toJSON(message: MsgSend): unknown {
const obj: any = {};
message.from_address !== undefined &&
(obj.from_address = message.from_address);
message.to_address !== undefined && (obj.to_address = message.to_address);
if (message.amount) {
obj.amount = message.amount.map((e) => (e ? Coin.toJSON(e) : undefined));
} else {
obj.amount = [];
}
return obj;
},
fromPartial(object: DeepPartial<MsgSend>): MsgSend {
const message = { ...baseMsgSend } as MsgSend;
message.amount = [];
if (object.from_address !== undefined && object.from_address !== null) {
message.from_address = object.from_address;
} else {
message.from_address = "";
}
if (object.to_address !== undefined && object.to_address !== null) {
message.to_address = object.to_address;
} else {
message.to_address = "";
}
if (object.amount !== undefined && object.amount !== null) {
for (const e of object.amount) {
message.amount.push(Coin.fromPartial(e));
}
}
return message;
},
};
const baseMsgSendResponse: object = {};
export const MsgSendResponse = {
encode(_: MsgSendResponse, writer: Writer = Writer.create()): Writer {
return writer;
},
decode(input: Reader | Uint8Array, length?: number): MsgSendResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgSendResponse } as MsgSendResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): MsgSendResponse {
const message = { ...baseMsgSendResponse } as MsgSendResponse;
return message;
},
toJSON(_: MsgSendResponse): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<MsgSendResponse>): MsgSendResponse {
const message = { ...baseMsgSendResponse } as MsgSendResponse;
return message;
},
};
const baseMsgMultiSend: object = {};
export const MsgMultiSend = {
encode(message: MsgMultiSend, writer: Writer = Writer.create()): Writer {
for (const v of message.inputs) {
Input.encode(v!, writer.uint32(10).fork()).ldelim();
}
for (const v of message.outputs) {
Output.encode(v!, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): MsgMultiSend {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgMultiSend } as MsgMultiSend;
message.inputs = [];
message.outputs = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.inputs.push(Input.decode(reader, reader.uint32()));
break;
case 2:
message.outputs.push(Output.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): MsgMultiSend {
const message = { ...baseMsgMultiSend } as MsgMultiSend;
message.inputs = [];
message.outputs = [];
if (object.inputs !== undefined && object.inputs !== null) {
for (const e of object.inputs) {
message.inputs.push(Input.fromJSON(e));
}
}
if (object.outputs !== undefined && object.outputs !== null) {
for (const e of object.outputs) {
message.outputs.push(Output.fromJSON(e));
}
}
return message;
},
toJSON(message: MsgMultiSend): unknown {
const obj: any = {};
if (message.inputs) {
obj.inputs = message.inputs.map((e) => (e ? Input.toJSON(e) : undefined));
} else {
obj.inputs = [];
}
if (message.outputs) {
obj.outputs = message.outputs.map((e) =>
e ? Output.toJSON(e) : undefined
);
} else {
obj.outputs = [];
}
return obj;
},
fromPartial(object: DeepPartial<MsgMultiSend>): MsgMultiSend {
const message = { ...baseMsgMultiSend } as MsgMultiSend;
message.inputs = [];
message.outputs = [];
if (object.inputs !== undefined && object.inputs !== null) {
for (const e of object.inputs) {
message.inputs.push(Input.fromPartial(e));
}
}
if (object.outputs !== undefined && object.outputs !== null) {
for (const e of object.outputs) {
message.outputs.push(Output.fromPartial(e));
}
}
return message;
},
};
const baseMsgMultiSendResponse: object = {};
export const MsgMultiSendResponse = {
encode(_: MsgMultiSendResponse, writer: Writer = Writer.create()): Writer {
return writer;
},
decode(input: Reader | Uint8Array, length?: number): MsgMultiSendResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseMsgMultiSendResponse } as MsgMultiSendResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): MsgMultiSendResponse {
const message = { ...baseMsgMultiSendResponse } as MsgMultiSendResponse;
return message;
},
toJSON(_: MsgMultiSendResponse): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<MsgMultiSendResponse>): MsgMultiSendResponse {
const message = { ...baseMsgMultiSendResponse } as MsgMultiSendResponse;
return message;
},
};
/** Msg defines the bank Msg service. */
export interface Msg {
/** Send defines a method for sending coins from one account to another account. */
Send(request: MsgSend): Promise<MsgSendResponse>;
/** MultiSend defines a method for sending coins from some accounts to other accounts. */
MultiSend(request: MsgMultiSend): Promise<MsgMultiSendResponse>;
}
export class MsgClientImpl implements Msg {
private readonly rpc: Rpc;
constructor(rpc: Rpc) {
this.rpc = rpc;
}
Send(request: MsgSend): Promise<MsgSendResponse> {
const data = MsgSend.encode(request).finish();
const promise = this.rpc.request("cosmos.bank.v1beta1.Msg", "Send", data);
return promise.then((data) => MsgSendResponse.decode(new Reader(data)));
}
MultiSend(request: MsgMultiSend): Promise<MsgMultiSendResponse> {
const data = MsgMultiSend.encode(request).finish();
const promise = this.rpc.request(
"cosmos.bank.v1beta1.Msg",
"MultiSend",
data
);
return promise.then((data) =>
MsgMultiSendResponse.decode(new Reader(data))
);
}
}
interface Rpc {
request(
service: string,
method: string,
data: Uint8Array
): Promise<Uint8Array>;
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,328 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.base.query.v1beta1";
/**
* PageRequest is to be embedded in gRPC request messages for efficient
* pagination. Ex:
*
* message SomeRequest {
* Foo some_parameter = 1;
* PageRequest pagination = 2;
* }
*/
export interface PageRequest {
/**
* key is a value returned in PageResponse.next_key to begin
* querying the next page most efficiently. Only one of offset or key
* should be set.
*/
key: Uint8Array;
/**
* offset is a numeric offset that can be used when key is unavailable.
* It is less efficient than using key. Only one of offset or key should
* be set.
*/
offset: number;
/**
* limit is the total number of results to be returned in the result page.
* If left empty it will default to a value to be set by each app.
*/
limit: number;
/**
* count_total is set to true to indicate that the result set should include
* a count of the total number of items available for pagination in UIs.
* count_total is only respected when offset is used. It is ignored when key
* is set.
*/
count_total: boolean;
/**
* reverse is set to true if results are to be returned in the descending order.
*
* Since: cosmos-sdk 0.43
*/
reverse: boolean;
}
/**
* PageResponse is to be embedded in gRPC response messages where the
* corresponding request message has used PageRequest.
*
* message SomeResponse {
* repeated Bar results = 1;
* PageResponse page = 2;
* }
*/
export interface PageResponse {
/**
* next_key is the key to be passed to PageRequest.key to
* query the next page most efficiently
*/
next_key: Uint8Array;
/**
* total is total number of results available if PageRequest.count_total
* was set, its value is undefined otherwise
*/
total: number;
}
const basePageRequest: object = {
offset: 0,
limit: 0,
count_total: false,
reverse: false,
};
export const PageRequest = {
encode(message: PageRequest, writer: Writer = Writer.create()): Writer {
if (message.key.length !== 0) {
writer.uint32(10).bytes(message.key);
}
if (message.offset !== 0) {
writer.uint32(16).uint64(message.offset);
}
if (message.limit !== 0) {
writer.uint32(24).uint64(message.limit);
}
if (message.count_total === true) {
writer.uint32(32).bool(message.count_total);
}
if (message.reverse === true) {
writer.uint32(40).bool(message.reverse);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageRequest } as PageRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.bytes();
break;
case 2:
message.offset = longToNumber(reader.uint64() as Long);
break;
case 3:
message.limit = longToNumber(reader.uint64() as Long);
break;
case 4:
message.count_total = reader.bool();
break;
case 5:
message.reverse = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = bytesFromBase64(object.key);
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = Number(object.offset);
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = Number(object.limit);
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = Boolean(object.count_total);
} else {
message.count_total = false;
}
if (object.reverse !== undefined && object.reverse !== null) {
message.reverse = Boolean(object.reverse);
} else {
message.reverse = false;
}
return message;
},
toJSON(message: PageRequest): unknown {
const obj: any = {};
message.key !== undefined &&
(obj.key = base64FromBytes(
message.key !== undefined ? message.key : new Uint8Array()
));
message.offset !== undefined && (obj.offset = message.offset);
message.limit !== undefined && (obj.limit = message.limit);
message.count_total !== undefined &&
(obj.count_total = message.count_total);
message.reverse !== undefined && (obj.reverse = message.reverse);
return obj;
},
fromPartial(object: DeepPartial<PageRequest>): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = new Uint8Array();
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = object.offset;
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = object.limit;
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = object.count_total;
} else {
message.count_total = false;
}
if (object.reverse !== undefined && object.reverse !== null) {
message.reverse = object.reverse;
} else {
message.reverse = false;
}
return message;
},
};
const basePageResponse: object = { total: 0 };
export const PageResponse = {
encode(message: PageResponse, writer: Writer = Writer.create()): Writer {
if (message.next_key.length !== 0) {
writer.uint32(10).bytes(message.next_key);
}
if (message.total !== 0) {
writer.uint32(16).uint64(message.total);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageResponse } as PageResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.next_key = reader.bytes();
break;
case 2:
message.total = longToNumber(reader.uint64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = bytesFromBase64(object.next_key);
}
if (object.total !== undefined && object.total !== null) {
message.total = Number(object.total);
} else {
message.total = 0;
}
return message;
},
toJSON(message: PageResponse): unknown {
const obj: any = {};
message.next_key !== undefined &&
(obj.next_key = base64FromBytes(
message.next_key !== undefined ? message.next_key : new Uint8Array()
));
message.total !== undefined && (obj.total = message.total);
return obj;
},
fromPartial(object: DeepPartial<PageResponse>): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = object.next_key;
} else {
message.next_key = new Uint8Array();
}
if (object.total !== undefined && object.total !== null) {
message.total = object.total;
} else {
message.total = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,301 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.base.v1beta1";
/**
* Coin defines a token with a denomination and an amount.
*
* NOTE: The amount field is an Int which implements the custom method
* signatures required by gogoproto.
*/
export interface Coin {
denom: string;
amount: string;
}
/**
* DecCoin defines a token with a denomination and a decimal amount.
*
* NOTE: The amount field is an Dec which implements the custom method
* signatures required by gogoproto.
*/
export interface DecCoin {
denom: string;
amount: string;
}
/** IntProto defines a Protobuf wrapper around an Int object. */
export interface IntProto {
int: string;
}
/** DecProto defines a Protobuf wrapper around a Dec object. */
export interface DecProto {
dec: string;
}
const baseCoin: object = { denom: "", amount: "" };
export const Coin = {
encode(message: Coin, writer: Writer = Writer.create()): Writer {
if (message.denom !== "") {
writer.uint32(10).string(message.denom);
}
if (message.amount !== "") {
writer.uint32(18).string(message.amount);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Coin {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseCoin } as Coin;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.denom = reader.string();
break;
case 2:
message.amount = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Coin {
const message = { ...baseCoin } as Coin;
if (object.denom !== undefined && object.denom !== null) {
message.denom = String(object.denom);
} else {
message.denom = "";
}
if (object.amount !== undefined && object.amount !== null) {
message.amount = String(object.amount);
} else {
message.amount = "";
}
return message;
},
toJSON(message: Coin): unknown {
const obj: any = {};
message.denom !== undefined && (obj.denom = message.denom);
message.amount !== undefined && (obj.amount = message.amount);
return obj;
},
fromPartial(object: DeepPartial<Coin>): Coin {
const message = { ...baseCoin } as Coin;
if (object.denom !== undefined && object.denom !== null) {
message.denom = object.denom;
} else {
message.denom = "";
}
if (object.amount !== undefined && object.amount !== null) {
message.amount = object.amount;
} else {
message.amount = "";
}
return message;
},
};
const baseDecCoin: object = { denom: "", amount: "" };
export const DecCoin = {
encode(message: DecCoin, writer: Writer = Writer.create()): Writer {
if (message.denom !== "") {
writer.uint32(10).string(message.denom);
}
if (message.amount !== "") {
writer.uint32(18).string(message.amount);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): DecCoin {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDecCoin } as DecCoin;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.denom = reader.string();
break;
case 2:
message.amount = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DecCoin {
const message = { ...baseDecCoin } as DecCoin;
if (object.denom !== undefined && object.denom !== null) {
message.denom = String(object.denom);
} else {
message.denom = "";
}
if (object.amount !== undefined && object.amount !== null) {
message.amount = String(object.amount);
} else {
message.amount = "";
}
return message;
},
toJSON(message: DecCoin): unknown {
const obj: any = {};
message.denom !== undefined && (obj.denom = message.denom);
message.amount !== undefined && (obj.amount = message.amount);
return obj;
},
fromPartial(object: DeepPartial<DecCoin>): DecCoin {
const message = { ...baseDecCoin } as DecCoin;
if (object.denom !== undefined && object.denom !== null) {
message.denom = object.denom;
} else {
message.denom = "";
}
if (object.amount !== undefined && object.amount !== null) {
message.amount = object.amount;
} else {
message.amount = "";
}
return message;
},
};
const baseIntProto: object = { int: "" };
export const IntProto = {
encode(message: IntProto, writer: Writer = Writer.create()): Writer {
if (message.int !== "") {
writer.uint32(10).string(message.int);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): IntProto {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseIntProto } as IntProto;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.int = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): IntProto {
const message = { ...baseIntProto } as IntProto;
if (object.int !== undefined && object.int !== null) {
message.int = String(object.int);
} else {
message.int = "";
}
return message;
},
toJSON(message: IntProto): unknown {
const obj: any = {};
message.int !== undefined && (obj.int = message.int);
return obj;
},
fromPartial(object: DeepPartial<IntProto>): IntProto {
const message = { ...baseIntProto } as IntProto;
if (object.int !== undefined && object.int !== null) {
message.int = object.int;
} else {
message.int = "";
}
return message;
},
};
const baseDecProto: object = { dec: "" };
export const DecProto = {
encode(message: DecProto, writer: Writer = Writer.create()): Writer {
if (message.dec !== "") {
writer.uint32(10).string(message.dec);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): DecProto {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDecProto } as DecProto;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.dec = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DecProto {
const message = { ...baseDecProto } as DecProto;
if (object.dec !== undefined && object.dec !== null) {
message.dec = String(object.dec);
} else {
message.dec = "";
}
return message;
},
toJSON(message: DecProto): unknown {
const obj: any = {};
message.dec !== undefined && (obj.dec = message.dec);
return obj;
},
fromPartial(object: DeepPartial<DecProto>): DecProto {
const message = { ...baseDecProto } as DecProto;
if (object.dec !== undefined && object.dec !== null) {
message.dec = object.dec;
} else {
message.dec = "";
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "cosmos_proto";

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "gogoproto";

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "google.api";

View File

@ -0,0 +1,706 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "google.api";
/**
* Defines the HTTP configuration for an API service. It contains a list of
* [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
* to one or more HTTP REST API methods.
*/
export interface Http {
/**
* A list of HTTP configuration rules that apply to individual API methods.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
*/
rules: HttpRule[];
/**
* When set to true, URL path parmeters will be fully URI-decoded except in
* cases of single segment matches in reserved expansion, where "%2F" will be
* left encoded.
*
* The default behavior is to not decode RFC 6570 reserved characters in multi
* segment matches.
*/
fully_decode_reserved_expansion: boolean;
}
/**
* `HttpRule` defines the mapping of an RPC method to one or more HTTP
* REST API methods. The mapping specifies how different portions of the RPC
* request message are mapped to URL path, URL query parameters, and
* HTTP request body. The mapping is typically specified as an
* `google.api.http` annotation on the RPC method,
* see "google/api/annotations.proto" for details.
*
* The mapping consists of a field specifying the path template and
* method kind. The path template can refer to fields in the request
* message, as in the example below which describes a REST GET
* operation on a resource collection of messages:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* SubMessage sub = 2; // `sub.subfield` is url-mapped
* }
* message Message {
* string text = 1; // content of the resource
* }
*
* The same http annotation can alternatively be expressed inside the
* `GRPC API Configuration` YAML file.
*
* http:
* rules:
* - selector: <proto_package_name>.Messaging.GetMessage
* get: /v1/messages/{message_id}/{sub.subfield}
*
* This definition enables an automatic, bidrectional mapping of HTTP
* JSON to RPC. Example:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))`
*
* In general, not only fields but also field paths can be referenced
* from a path pattern. Fields mapped to the path pattern cannot be
* repeated and must have a primitive (non-message) type.
*
* Any fields in the request message which are not bound by the path
* pattern automatically become (optional) HTTP query
* parameters. Assume the following definition of the request message:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* int64 revision = 2; // becomes a parameter
* SubMessage sub = 3; // `sub.subfield` becomes a parameter
* }
*
*
* This enables a HTTP JSON to RPC mapping as below:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))`
*
* Note that fields which are mapped to HTTP parameters must have a
* primitive type or a repeated primitive type. Message types are not
* allowed. In the case of a repeated type, the parameter can be
* repeated in the URL, as in `...?param=A&param=B`.
*
* For HTTP method kinds which allow a request body, the `body` field
* specifies the mapping. Consider a REST update method on the
* message resource collection:
*
*
* service Messaging {
* rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "message"
* };
* }
* }
* message UpdateMessageRequest {
* string message_id = 1; // mapped to the URL
* Message message = 2; // mapped to the body
* }
*
*
* The following HTTP JSON to RPC mapping is enabled, where the
* representation of the JSON in the request body is determined by
* protos JSON encoding:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
*
* The special name `*` can be used in the body mapping to define that
* every field not bound by the path template should be mapped to the
* request body. This enables the following alternative definition of
* the update method:
*
* service Messaging {
* rpc UpdateMessage(Message) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "*"
* };
* }
* }
* message Message {
* string message_id = 1;
* string text = 2;
* }
*
*
* The following HTTP JSON to RPC mapping is enabled:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")`
*
* Note that when using `*` in the body mapping, it is not possible to
* have HTTP parameters, as all fields not bound by the path end in
* the body. This makes this option more rarely used in practice of
* defining REST APIs. The common usage of `*` is in custom methods
* which don't use the URL at all for transferring data.
*
* It is possible to define multiple HTTP methods for one RPC by using
* the `additional_bindings` option. Example:
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http) = {
* get: "/v1/messages/{message_id}"
* additional_bindings {
* get: "/v1/users/{user_id}/messages/{message_id}"
* }
* };
* }
* }
* message GetMessageRequest {
* string message_id = 1;
* string user_id = 2;
* }
*
*
* This enables the following two alternative HTTP JSON to RPC
* mappings:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
* `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")`
*
* # Rules for HTTP mapping
*
* The rules for mapping HTTP path, query parameters, and body fields
* to the request message are as follows:
*
* 1. The `body` field specifies either `*` or a field path, or is
* omitted. If omitted, it indicates there is no HTTP request body.
* 2. Leaf fields (recursive expansion of nested messages in the
* request) can be classified into three types:
* (a) Matched in the URL template.
* (b) Covered by body (if body is `*`, everything except (a) fields;
* else everything under the body field)
* (c) All other fields.
* 3. URL query parameters found in the HTTP request are mapped to (c) fields.
* 4. Any body sent with an HTTP request can contain only (b) fields.
*
* The syntax of the path template is as follows:
*
* Template = "/" Segments [ Verb ] ;
* Segments = Segment { "/" Segment } ;
* Segment = "*" | "**" | LITERAL | Variable ;
* Variable = "{" FieldPath [ "=" Segments ] "}" ;
* FieldPath = IDENT { "." IDENT } ;
* Verb = ":" LITERAL ;
*
* The syntax `*` matches a single path segment. The syntax `**` matches zero
* or more path segments, which must be the last part of the path except the
* `Verb`. The syntax `LITERAL` matches literal text in the path.
*
* The syntax `Variable` matches part of the URL path as specified by its
* template. A variable template must not contain other variables. If a variable
* matches a single path segment, its template may be omitted, e.g. `{var}`
* is equivalent to `{var=*}`.
*
* If a variable contains exactly one path segment, such as `"{var}"` or
* `"{var=*}"`, when such a variable is expanded into a URL path, all characters
* except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the
* Discovery Document as `{var}`.
*
* If a variable contains one or more path segments, such as `"{var=foo/*}"`
* or `"{var=**}"`, when such a variable is expanded into a URL path, all
* characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables
* show up in the Discovery Document as `{+var}`.
*
* NOTE: While the single segment variable matches the semantics of
* [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2
* Simple String Expansion, the multi segment variable **does not** match
* RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion
* does not expand special characters like `?` and `#`, which would lead
* to invalid URLs.
*
* NOTE: the field paths in variables and in the `body` must not refer to
* repeated fields or map fields.
*/
export interface HttpRule {
/**
* Selects methods to which this rule applies.
*
* Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
*/
selector: string;
/** Used for listing and getting information about resources. */
get: string | undefined;
/** Used for updating a resource. */
put: string | undefined;
/** Used for creating a resource. */
post: string | undefined;
/** Used for deleting a resource. */
delete: string | undefined;
/** Used for updating a resource. */
patch: string | undefined;
/**
* The custom pattern is used for specifying an HTTP method that is not
* included in the `pattern` field, such as HEAD, or "*" to leave the
* HTTP method unspecified for this rule. The wild-card rule is useful
* for services that provide content to Web (HTML) clients.
*/
custom: CustomHttpPattern | undefined;
/**
* The name of the request field whose value is mapped to the HTTP body, or
* `*` for mapping all fields not captured by the path pattern to the HTTP
* body. NOTE: the referred field must not be a repeated field and must be
* present at the top-level of request message type.
*/
body: string;
/**
* Optional. The name of the response field whose value is mapped to the HTTP
* body of response. Other response fields are ignored. When
* not set, the response message will be used as HTTP body of response.
*/
response_body: string;
/**
* Additional HTTP bindings for the selector. Nested bindings must
* not contain an `additional_bindings` field themselves (that is,
* the nesting may only be one level deep).
*/
additional_bindings: HttpRule[];
}
/** A custom pattern is used for defining custom HTTP verb. */
export interface CustomHttpPattern {
/** The name of this custom HTTP verb. */
kind: string;
/** The path matched by this custom verb. */
path: string;
}
const baseHttp: object = { fully_decode_reserved_expansion: false };
export const Http = {
encode(message: Http, writer: Writer = Writer.create()): Writer {
for (const v of message.rules) {
HttpRule.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.fully_decode_reserved_expansion === true) {
writer.uint32(16).bool(message.fully_decode_reserved_expansion);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Http {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttp } as Http;
message.rules = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.rules.push(HttpRule.decode(reader, reader.uint32()));
break;
case 2:
message.fully_decode_reserved_expansion = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromJSON(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion = Boolean(
object.fully_decode_reserved_expansion
);
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
toJSON(message: Http): unknown {
const obj: any = {};
if (message.rules) {
obj.rules = message.rules.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.rules = [];
}
message.fully_decode_reserved_expansion !== undefined &&
(obj.fully_decode_reserved_expansion =
message.fully_decode_reserved_expansion);
return obj;
},
fromPartial(object: DeepPartial<Http>): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromPartial(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion =
object.fully_decode_reserved_expansion;
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
};
const baseHttpRule: object = { selector: "", body: "", response_body: "" };
export const HttpRule = {
encode(message: HttpRule, writer: Writer = Writer.create()): Writer {
if (message.selector !== "") {
writer.uint32(10).string(message.selector);
}
if (message.get !== undefined) {
writer.uint32(18).string(message.get);
}
if (message.put !== undefined) {
writer.uint32(26).string(message.put);
}
if (message.post !== undefined) {
writer.uint32(34).string(message.post);
}
if (message.delete !== undefined) {
writer.uint32(42).string(message.delete);
}
if (message.patch !== undefined) {
writer.uint32(50).string(message.patch);
}
if (message.custom !== undefined) {
CustomHttpPattern.encode(
message.custom,
writer.uint32(66).fork()
).ldelim();
}
if (message.body !== "") {
writer.uint32(58).string(message.body);
}
if (message.response_body !== "") {
writer.uint32(98).string(message.response_body);
}
for (const v of message.additional_bindings) {
HttpRule.encode(v!, writer.uint32(90).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): HttpRule {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.selector = reader.string();
break;
case 2:
message.get = reader.string();
break;
case 3:
message.put = reader.string();
break;
case 4:
message.post = reader.string();
break;
case 5:
message.delete = reader.string();
break;
case 6:
message.patch = reader.string();
break;
case 8:
message.custom = CustomHttpPattern.decode(reader, reader.uint32());
break;
case 7:
message.body = reader.string();
break;
case 12:
message.response_body = reader.string();
break;
case 11:
message.additional_bindings.push(
HttpRule.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = String(object.selector);
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = String(object.get);
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = String(object.put);
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = String(object.post);
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = String(object.delete);
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = String(object.patch);
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromJSON(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = String(object.body);
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = String(object.response_body);
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromJSON(e));
}
}
return message;
},
toJSON(message: HttpRule): unknown {
const obj: any = {};
message.selector !== undefined && (obj.selector = message.selector);
message.get !== undefined && (obj.get = message.get);
message.put !== undefined && (obj.put = message.put);
message.post !== undefined && (obj.post = message.post);
message.delete !== undefined && (obj.delete = message.delete);
message.patch !== undefined && (obj.patch = message.patch);
message.custom !== undefined &&
(obj.custom = message.custom
? CustomHttpPattern.toJSON(message.custom)
: undefined);
message.body !== undefined && (obj.body = message.body);
message.response_body !== undefined &&
(obj.response_body = message.response_body);
if (message.additional_bindings) {
obj.additional_bindings = message.additional_bindings.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.additional_bindings = [];
}
return obj;
},
fromPartial(object: DeepPartial<HttpRule>): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = object.selector;
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = object.get;
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = object.put;
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = object.post;
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = object.delete;
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = object.patch;
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromPartial(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = object.body;
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = object.response_body;
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromPartial(e));
}
}
return message;
},
};
const baseCustomHttpPattern: object = { kind: "", path: "" };
export const CustomHttpPattern = {
encode(message: CustomHttpPattern, writer: Writer = Writer.create()): Writer {
if (message.kind !== "") {
writer.uint32(10).string(message.kind);
}
if (message.path !== "") {
writer.uint32(18).string(message.path);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): CustomHttpPattern {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.kind = reader.string();
break;
case 2:
message.path = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = String(object.kind);
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = String(object.path);
} else {
message.path = "";
}
return message;
},
toJSON(message: CustomHttpPattern): unknown {
const obj: any = {};
message.kind !== undefined && (obj.kind = message.kind);
message.path !== undefined && (obj.path = message.path);
return obj;
},
fromPartial(object: DeepPartial<CustomHttpPattern>): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = object.kind;
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = object.path;
} else {
message.path = "";
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,18 @@
{
"name": "cosmos-bank-v1beta1-js",
"version": "0.1.0",
"description": "Autogenerated vuex store for Cosmos module cosmos.bank.v1beta1",
"author": "Starport Codegen <hello@tendermint.com>",
"homepage": "http://github.com/cosmos/cosmos-sdk/x/bank/types",
"license": "Apache-2.0",
"licenses": [
{
"type": "Apache-2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
],
"main": "index.js",
"publishConfig": {
"access": "public"
}
}

View File

@ -0,0 +1 @@
THIS FILE IS GENERATED AUTOMATICALLY. DO NOT DELETE.

View File

@ -0,0 +1,298 @@
import { txClient, queryClient, MissingWalletError , registry} from './module'
import { Validator } from "./module/types/cosmos/base/tendermint/v1beta1/query"
import { VersionInfo } from "./module/types/cosmos/base/tendermint/v1beta1/query"
import { Module } from "./module/types/cosmos/base/tendermint/v1beta1/query"
export { Validator, VersionInfo, Module };
async function initTxClient(vuexGetters) {
return await txClient(vuexGetters['common/wallet/signer'], {
addr: vuexGetters['common/env/apiTendermint']
})
}
async function initQueryClient(vuexGetters) {
return await queryClient({
addr: vuexGetters['common/env/apiCosmos']
})
}
function mergeResults(value, next_values) {
for (let prop of Object.keys(next_values)) {
if (Array.isArray(next_values[prop])) {
value[prop]=[...value[prop], ...next_values[prop]]
}else{
value[prop]=next_values[prop]
}
}
return value
}
function getStructure(template) {
let structure = { fields: [] }
for (const [key, value] of Object.entries(template)) {
let field: any = {}
field.name = key
field.type = typeof value
structure.fields.push(field)
}
return structure
}
const getDefaultState = () => {
return {
GetNodeInfo: {},
GetSyncing: {},
GetLatestBlock: {},
GetBlockByHeight: {},
GetLatestValidatorSet: {},
GetValidatorSetByHeight: {},
_Structure: {
Validator: getStructure(Validator.fromPartial({})),
VersionInfo: getStructure(VersionInfo.fromPartial({})),
Module: getStructure(Module.fromPartial({})),
},
_Registry: registry,
_Subscriptions: new Set(),
}
}
// initial state
const state = getDefaultState()
export default {
namespaced: true,
state,
mutations: {
RESET_STATE(state) {
Object.assign(state, getDefaultState())
},
QUERY(state, { query, key, value }) {
state[query][JSON.stringify(key)] = value
},
SUBSCRIBE(state, subscription) {
state._Subscriptions.add(JSON.stringify(subscription))
},
UNSUBSCRIBE(state, subscription) {
state._Subscriptions.delete(JSON.stringify(subscription))
}
},
getters: {
getGetNodeInfo: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.GetNodeInfo[JSON.stringify(params)] ?? {}
},
getGetSyncing: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.GetSyncing[JSON.stringify(params)] ?? {}
},
getGetLatestBlock: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.GetLatestBlock[JSON.stringify(params)] ?? {}
},
getGetBlockByHeight: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.GetBlockByHeight[JSON.stringify(params)] ?? {}
},
getGetLatestValidatorSet: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.GetLatestValidatorSet[JSON.stringify(params)] ?? {}
},
getGetValidatorSetByHeight: (state) => (params = { params: {}}) => {
if (!(<any> params).query) {
(<any> params).query=null
}
return state.GetValidatorSetByHeight[JSON.stringify(params)] ?? {}
},
getTypeStructure: (state) => (type) => {
return state._Structure[type].fields
},
getRegistry: (state) => {
return state._Registry
}
},
actions: {
init({ dispatch, rootGetters }) {
console.log('Vuex module: cosmos.base.tendermint.v1beta1 initialized!')
if (rootGetters['common/env/client']) {
rootGetters['common/env/client'].on('newblock', () => {
dispatch('StoreUpdate')
})
}
},
resetState({ commit }) {
commit('RESET_STATE')
},
unsubscribe({ commit }, subscription) {
commit('UNSUBSCRIBE', subscription)
},
async StoreUpdate({ state, dispatch }) {
state._Subscriptions.forEach(async (subscription) => {
try {
const sub=JSON.parse(subscription)
await dispatch(sub.action, sub.payload)
}catch(e) {
throw new Error('Subscriptions: ' + e.message)
}
})
},
async ServiceGetNodeInfo({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.serviceGetNodeInfo()).data
commit('QUERY', { query: 'GetNodeInfo', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'ServiceGetNodeInfo', payload: { options: { all }, params: {...key},query }})
return getters['getGetNodeInfo']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:ServiceGetNodeInfo API Node Unavailable. Could not perform query: ' + e.message)
}
},
async ServiceGetSyncing({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.serviceGetSyncing()).data
commit('QUERY', { query: 'GetSyncing', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'ServiceGetSyncing', payload: { options: { all }, params: {...key},query }})
return getters['getGetSyncing']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:ServiceGetSyncing API Node Unavailable. Could not perform query: ' + e.message)
}
},
async ServiceGetLatestBlock({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.serviceGetLatestBlock()).data
commit('QUERY', { query: 'GetLatestBlock', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'ServiceGetLatestBlock', payload: { options: { all }, params: {...key},query }})
return getters['getGetLatestBlock']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:ServiceGetLatestBlock API Node Unavailable. Could not perform query: ' + e.message)
}
},
async ServiceGetBlockByHeight({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.serviceGetBlockByHeight( key.height)).data
commit('QUERY', { query: 'GetBlockByHeight', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'ServiceGetBlockByHeight', payload: { options: { all }, params: {...key},query }})
return getters['getGetBlockByHeight']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:ServiceGetBlockByHeight API Node Unavailable. Could not perform query: ' + e.message)
}
},
async ServiceGetLatestValidatorSet({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.serviceGetLatestValidatorSet(query)).data
while (all && (<any> value).pagination && (<any> value).pagination.next_key!=null) {
let next_values=(await queryClient.serviceGetLatestValidatorSet({...query, 'pagination.key':(<any> value).pagination.next_key})).data
value = mergeResults(value, next_values);
}
commit('QUERY', { query: 'GetLatestValidatorSet', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'ServiceGetLatestValidatorSet', payload: { options: { all }, params: {...key},query }})
return getters['getGetLatestValidatorSet']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:ServiceGetLatestValidatorSet API Node Unavailable. Could not perform query: ' + e.message)
}
},
async ServiceGetValidatorSetByHeight({ commit, rootGetters, getters }, { options: { subscribe, all} = { subscribe:false, all:false}, params, query=null }) {
try {
const key = params ?? {};
const queryClient=await initQueryClient(rootGetters)
let value= (await queryClient.serviceGetValidatorSetByHeight( key.height, query)).data
while (all && (<any> value).pagination && (<any> value).pagination.next_key!=null) {
let next_values=(await queryClient.serviceGetValidatorSetByHeight( key.height, {...query, 'pagination.key':(<any> value).pagination.next_key})).data
value = mergeResults(value, next_values);
}
commit('QUERY', { query: 'GetValidatorSetByHeight', key: { params: {...key}, query}, value })
if (subscribe) commit('SUBSCRIBE', { action: 'ServiceGetValidatorSetByHeight', payload: { options: { all }, params: {...key},query }})
return getters['getGetValidatorSetByHeight']( { params: {...key}, query}) ?? {}
} catch (e) {
throw new Error('QueryClient:ServiceGetValidatorSetByHeight API Node Unavailable. Could not perform query: ' + e.message)
}
},
}
}

View File

@ -0,0 +1,57 @@
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT MODIFY.
import { StdFee } from "@cosmjs/launchpad";
import { SigningStargateClient } from "@cosmjs/stargate";
import { Registry, OfflineSigner, EncodeObject, DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { Api } from "./rest";
const types = [
];
export const MissingWalletError = new Error("wallet is required");
export const registry = new Registry(<any>types);
const defaultFee = {
amount: [],
gas: "200000",
};
interface TxClientOptions {
addr: string
}
interface SignAndBroadcastOptions {
fee: StdFee,
memo?: string
}
const txClient = async (wallet: OfflineSigner, { addr: addr }: TxClientOptions = { addr: "http://localhost:26657" }) => {
if (!wallet) throw MissingWalletError;
let client;
if (addr) {
client = await SigningStargateClient.connectWithSigner(addr, wallet, { registry });
}else{
client = await SigningStargateClient.offline( wallet, { registry });
}
const { address } = (await wallet.getAccounts())[0];
return {
signAndBroadcast: (msgs: EncodeObject[], { fee, memo }: SignAndBroadcastOptions = {fee: defaultFee, memo: ""}) => client.signAndBroadcast(address, msgs, fee,memo),
};
};
interface QueryClientOptions {
addr: string
}
const queryClient = async ({ addr: addr }: QueryClientOptions = { addr: "http://localhost:1317" }) => {
return new Api({ baseUrl: addr });
};
export {
txClient,
queryClient,
};

View File

@ -0,0 +1,987 @@
/* eslint-disable */
/* tslint:disable */
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
export interface CryptoPublicKey {
/** @format byte */
ed25519?: string;
/** @format byte */
secp256k1?: string;
}
export interface P2PDefaultNodeInfo {
protocol_version?: P2PProtocolVersion;
default_node_id?: string;
listen_addr?: string;
network?: string;
version?: string;
/** @format byte */
channels?: string;
moniker?: string;
other?: P2PDefaultNodeInfoOther;
}
export interface P2PDefaultNodeInfoOther {
tx_index?: string;
rpc_address?: string;
}
export interface P2PProtocolVersion {
/** @format uint64 */
p2p?: string;
/** @format uint64 */
block?: string;
/** @format uint64 */
app?: string;
}
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
URL that describes the type of the serialized message.
Protobuf library provides support to pack/unpack Any values in the form
of utility functions or additional generated methods of the Any type.
Example 1: Pack and unpack a message in C++.
Foo foo = ...;
Any any;
any.PackFrom(foo);
...
if (any.UnpackTo(&foo)) {
...
}
Example 2: Pack and unpack a message in Java.
Foo foo = ...;
Any any = Any.pack(foo);
...
if (any.is(Foo.class)) {
foo = any.unpack(Foo.class);
}
Example 3: Pack and unpack a message in Python.
foo = Foo(...)
any = Any()
any.Pack(foo)
...
if any.Is(Foo.DESCRIPTOR):
any.Unpack(foo)
...
Example 4: Pack and unpack a message in Go
foo := &pb.Foo{...}
any, err := anypb.New(foo)
if err != nil {
...
}
...
foo := &pb.Foo{}
if err := any.UnmarshalTo(foo); err != nil {
...
}
The pack methods provided by protobuf library will by default use
'type.googleapis.com/full.type.name' as the type URL and the unpack
methods only use the fully qualified type name after the last '/'
in the type URL, for example "foo.bar.com/x/y.z" will yield type
name "y.z".
JSON
====
The JSON representation of an `Any` value uses the regular
representation of the deserialized, embedded message, with an
additional field `@type` which contains the type URL. Example:
package google.profile;
message Person {
string first_name = 1;
string last_name = 2;
}
{
"@type": "type.googleapis.com/google.profile.Person",
"firstName": <string>,
"lastName": <string>
}
If the embedded message type is well-known and has a custom JSON
representation, that representation will be embedded adding a field
`value` which holds the custom JSON in addition to the `@type`
field. Example (for message [google.protobuf.Duration][]):
{
"@type": "type.googleapis.com/google.protobuf.Duration",
"value": "1.212s"
}
*/
export interface ProtobufAny {
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*/
"@type"?: string;
}
export interface RpcStatus {
/** @format int32 */
code?: number;
message?: string;
details?: ProtobufAny[];
}
export interface TenderminttypesValidator {
/** @format byte */
address?: string;
pub_key?: CryptoPublicKey;
/** @format int64 */
voting_power?: string;
/** @format int64 */
proposer_priority?: string;
}
/**
* Validator is the type for the validator-set.
*/
export interface Tendermintv1Beta1Validator {
address?: string;
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*/
pub_key?: ProtobufAny;
/** @format int64 */
voting_power?: string;
/** @format int64 */
proposer_priority?: string;
}
export interface TypesBlock {
/** Header defines the structure of a Tendermint block header. */
header?: TypesHeader;
data?: TypesData;
evidence?: TypesEvidenceList;
/** Commit contains the evidence that a block was committed by a set of validators. */
last_commit?: TypesCommit;
}
export interface TypesBlockID {
/** @format byte */
hash?: string;
part_set_header?: TypesPartSetHeader;
}
export enum TypesBlockIDFlag {
BLOCK_ID_FLAG_UNKNOWN = "BLOCK_ID_FLAG_UNKNOWN",
BLOCK_ID_FLAG_ABSENT = "BLOCK_ID_FLAG_ABSENT",
BLOCK_ID_FLAG_COMMIT = "BLOCK_ID_FLAG_COMMIT",
BLOCK_ID_FLAG_NIL = "BLOCK_ID_FLAG_NIL",
}
/**
* Commit contains the evidence that a block was committed by a set of validators.
*/
export interface TypesCommit {
/** @format int64 */
height?: string;
/** @format int32 */
round?: number;
block_id?: TypesBlockID;
signatures?: TypesCommitSig[];
}
/**
* CommitSig is a part of the Vote included in a Commit.
*/
export interface TypesCommitSig {
block_id_flag?: TypesBlockIDFlag;
/** @format byte */
validator_address?: string;
/** @format date-time */
timestamp?: string;
/** @format byte */
signature?: string;
}
export interface TypesData {
/**
* Txs that will be applied by state @ block.Height+1.
* NOTE: not all txs here are valid. We're just agreeing on the order first.
* This means that block.AppHash does not include these txs.
*/
txs?: string[];
}
/**
* DuplicateVoteEvidence contains evidence of a validator signed two conflicting votes.
*/
export interface TypesDuplicateVoteEvidence {
/**
* Vote represents a prevote, precommit, or commit vote from validators for
* consensus.
*/
vote_a?: TypesVote;
/**
* Vote represents a prevote, precommit, or commit vote from validators for
* consensus.
*/
vote_b?: TypesVote;
/** @format int64 */
total_voting_power?: string;
/** @format int64 */
validator_power?: string;
/** @format date-time */
timestamp?: string;
}
export interface TypesEvidence {
/** DuplicateVoteEvidence contains evidence of a validator signed two conflicting votes. */
duplicate_vote_evidence?: TypesDuplicateVoteEvidence;
/** LightClientAttackEvidence contains evidence of a set of validators attempting to mislead a light client. */
light_client_attack_evidence?: TypesLightClientAttackEvidence;
}
export interface TypesEvidenceList {
evidence?: TypesEvidence[];
}
/**
* Header defines the structure of a Tendermint block header.
*/
export interface TypesHeader {
/**
* Consensus captures the consensus rules for processing a block in the blockchain,
* including all blockchain data structures and the rules of the application's
* state transition machine.
*/
version?: VersionConsensus;
chain_id?: string;
/** @format int64 */
height?: string;
/** @format date-time */
time?: string;
last_block_id?: TypesBlockID;
/** @format byte */
last_commit_hash?: string;
/** @format byte */
data_hash?: string;
/** @format byte */
validators_hash?: string;
/** @format byte */
next_validators_hash?: string;
/** @format byte */
consensus_hash?: string;
/** @format byte */
app_hash?: string;
/** @format byte */
last_results_hash?: string;
/** @format byte */
evidence_hash?: string;
/** @format byte */
proposer_address?: string;
}
export interface TypesLightBlock {
signed_header?: TypesSignedHeader;
validator_set?: TypesValidatorSet;
}
/**
* LightClientAttackEvidence contains evidence of a set of validators attempting to mislead a light client.
*/
export interface TypesLightClientAttackEvidence {
conflicting_block?: TypesLightBlock;
/** @format int64 */
common_height?: string;
byzantine_validators?: TenderminttypesValidator[];
/** @format int64 */
total_voting_power?: string;
/** @format date-time */
timestamp?: string;
}
export interface TypesPartSetHeader {
/** @format int64 */
total?: number;
/** @format byte */
hash?: string;
}
export interface TypesSignedHeader {
/** Header defines the structure of a Tendermint block header. */
header?: TypesHeader;
/** Commit contains the evidence that a block was committed by a set of validators. */
commit?: TypesCommit;
}
/**
* SignedMsgType is a type of signed message in the consensus.
- SIGNED_MSG_TYPE_PREVOTE: Votes
- SIGNED_MSG_TYPE_PROPOSAL: Proposals
*/
export enum TypesSignedMsgType {
SIGNED_MSG_TYPE_UNKNOWN = "SIGNED_MSG_TYPE_UNKNOWN",
SIGNED_MSG_TYPE_PREVOTE = "SIGNED_MSG_TYPE_PREVOTE",
SIGNED_MSG_TYPE_PRECOMMIT = "SIGNED_MSG_TYPE_PRECOMMIT",
SIGNED_MSG_TYPE_PROPOSAL = "SIGNED_MSG_TYPE_PROPOSAL",
}
export interface TypesValidatorSet {
validators?: TenderminttypesValidator[];
proposer?: TenderminttypesValidator;
/** @format int64 */
total_voting_power?: string;
}
/**
* Vote represents a prevote, precommit, or commit vote from validators for
consensus.
*/
export interface TypesVote {
/**
* SignedMsgType is a type of signed message in the consensus.
*
* - SIGNED_MSG_TYPE_PREVOTE: Votes
* - SIGNED_MSG_TYPE_PROPOSAL: Proposals
*/
type?: TypesSignedMsgType;
/** @format int64 */
height?: string;
/** @format int32 */
round?: number;
block_id?: TypesBlockID;
/** @format date-time */
timestamp?: string;
/** @format byte */
validator_address?: string;
/** @format int32 */
validator_index?: number;
/** @format byte */
signature?: string;
}
/**
* GetBlockByHeightResponse is the response type for the Query/GetBlockByHeight RPC method.
*/
export interface V1Beta1GetBlockByHeightResponse {
block_id?: TypesBlockID;
block?: TypesBlock;
}
/**
* GetLatestBlockResponse is the response type for the Query/GetLatestBlock RPC method.
*/
export interface V1Beta1GetLatestBlockResponse {
block_id?: TypesBlockID;
block?: TypesBlock;
}
/**
* GetLatestValidatorSetResponse is the response type for the Query/GetValidatorSetByHeight RPC method.
*/
export interface V1Beta1GetLatestValidatorSetResponse {
/** @format int64 */
block_height?: string;
validators?: Tendermintv1Beta1Validator[];
/** pagination defines an pagination for the response. */
pagination?: V1Beta1PageResponse;
}
/**
* GetNodeInfoResponse is the request type for the Query/GetNodeInfo RPC method.
*/
export interface V1Beta1GetNodeInfoResponse {
default_node_info?: P2PDefaultNodeInfo;
/** VersionInfo is the type for the GetNodeInfoResponse message. */
application_version?: V1Beta1VersionInfo;
}
/**
* GetSyncingResponse is the response type for the Query/GetSyncing RPC method.
*/
export interface V1Beta1GetSyncingResponse {
syncing?: boolean;
}
/**
* GetValidatorSetByHeightResponse is the response type for the Query/GetValidatorSetByHeight RPC method.
*/
export interface V1Beta1GetValidatorSetByHeightResponse {
/** @format int64 */
block_height?: string;
validators?: Tendermintv1Beta1Validator[];
/** pagination defines an pagination for the response. */
pagination?: V1Beta1PageResponse;
}
export interface V1Beta1Module {
path?: string;
version?: string;
sum?: string;
}
/**
* message SomeRequest {
Foo some_parameter = 1;
PageRequest pagination = 2;
}
*/
export interface V1Beta1PageRequest {
/**
* key is a value returned in PageResponse.next_key to begin
* querying the next page most efficiently. Only one of offset or key
* should be set.
* @format byte
*/
key?: string;
/**
* offset is a numeric offset that can be used when key is unavailable.
* It is less efficient than using key. Only one of offset or key should
* be set.
* @format uint64
*/
offset?: string;
/**
* limit is the total number of results to be returned in the result page.
* If left empty it will default to a value to be set by each app.
* @format uint64
*/
limit?: string;
/**
* count_total is set to true to indicate that the result set should include
* a count of the total number of items available for pagination in UIs.
* count_total is only respected when offset is used. It is ignored when key
* is set.
*/
count_total?: boolean;
/**
* reverse is set to true if results are to be returned in the descending order.
*
* Since: cosmos-sdk 0.43
*/
reverse?: boolean;
}
/**
* PageResponse is to be embedded in gRPC response messages where the
corresponding request message has used PageRequest.
message SomeResponse {
repeated Bar results = 1;
PageResponse page = 2;
}
*/
export interface V1Beta1PageResponse {
/** @format byte */
next_key?: string;
/** @format uint64 */
total?: string;
}
/**
* VersionInfo is the type for the GetNodeInfoResponse message.
*/
export interface V1Beta1VersionInfo {
name?: string;
app_name?: string;
version?: string;
git_commit?: string;
build_tags?: string;
go_version?: string;
build_deps?: V1Beta1Module[];
cosmos_sdk_version?: string;
}
/**
* Consensus captures the consensus rules for processing a block in the blockchain,
including all blockchain data structures and the rules of the application's
state transition machine.
*/
export interface VersionConsensus {
/** @format uint64 */
block?: string;
/** @format uint64 */
app?: string;
}
export type QueryParamsType = Record<string | number, any>;
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
export interface FullRequestParams extends Omit<RequestInit, "body"> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: keyof Omit<Body, "body" | "bodyUsed">;
/** request body */
body?: unknown;
/** base url */
baseUrl?: string;
/** request cancellation token */
cancelToken?: CancelToken;
}
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
export interface ApiConfig<SecurityDataType = unknown> {
baseUrl?: string;
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
securityWorker?: (securityData: SecurityDataType) => RequestParams | void;
}
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
data: D;
error: E;
}
type CancelToken = Symbol | string | number;
export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
}
export class HttpClient<SecurityDataType = unknown> {
public baseUrl: string = "";
private securityData: SecurityDataType = null as any;
private securityWorker: null | ApiConfig<SecurityDataType>["securityWorker"] = null;
private abortControllers = new Map<CancelToken, AbortController>();
private baseApiParams: RequestParams = {
credentials: "same-origin",
headers: {},
redirect: "follow",
referrerPolicy: "no-referrer",
};
constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
Object.assign(this, apiConfig);
}
public setSecurityData = (data: SecurityDataType) => {
this.securityData = data;
};
private addQueryParam(query: QueryParamsType, key: string) {
const value = query[key];
return (
encodeURIComponent(key) +
"=" +
encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`)
);
}
protected toQueryString(rawQuery?: QueryParamsType): string {
const query = rawQuery || {};
const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
return keys
.map((key) =>
typeof query[key] === "object" && !Array.isArray(query[key])
? this.toQueryString(query[key] as QueryParamsType)
: this.addQueryParam(query, key),
)
.join("&");
}
protected addQueryParams(rawQuery?: QueryParamsType): string {
const queryString = this.toQueryString(rawQuery);
return queryString ? `?${queryString}` : "";
}
private contentFormatters: Record<ContentType, (input: any) => any> = {
[ContentType.Json]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
[ContentType.FormData]: (input: any) =>
Object.keys(input || {}).reduce((data, key) => {
data.append(key, input[key]);
return data;
}, new FormData()),
[ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
};
private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
return {
...this.baseApiParams,
...params1,
...(params2 || {}),
headers: {
...(this.baseApiParams.headers || {}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
if (this.abortControllers.has(cancelToken)) {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
return abortController.signal;
}
return void 0;
}
const abortController = new AbortController();
this.abortControllers.set(cancelToken, abortController);
return abortController.signal;
};
public abortRequest = (cancelToken: CancelToken) => {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
abortController.abort();
this.abortControllers.delete(cancelToken);
}
};
public request = <T = any, E = any>({
body,
secure,
path,
type,
query,
format = "json",
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
...requestParams,
headers: {
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
...(requestParams.headers || {}),
},
signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
}).then(async (response) => {
const r = response as HttpResponse<T, E>;
r.data = (null as unknown) as T;
r.error = (null as unknown) as E;
const data = await response[format]()
.then((data) => {
if (r.ok) {
r.data = data;
} else {
r.error = data;
}
return r;
})
.catch((e) => {
r.error = e;
return r;
});
if (cancelToken) {
this.abortControllers.delete(cancelToken);
}
if (!response.ok) throw data;
return data;
});
};
}
/**
* @title cosmos/base/tendermint/v1beta1/query.proto
* @version version not set
*/
export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
/**
* No description
*
* @tags Service
* @name ServiceGetLatestBlock
* @summary GetLatestBlock returns the latest block.
* @request GET:/cosmos/base/tendermint/v1beta1/blocks/latest
*/
serviceGetLatestBlock = (params: RequestParams = {}) =>
this.request<V1Beta1GetLatestBlockResponse, RpcStatus>({
path: `/cosmos/base/tendermint/v1beta1/blocks/latest`,
method: "GET",
format: "json",
...params,
});
/**
* No description
*
* @tags Service
* @name ServiceGetBlockByHeight
* @summary GetBlockByHeight queries block for given height.
* @request GET:/cosmos/base/tendermint/v1beta1/blocks/{height}
*/
serviceGetBlockByHeight = (height: string, params: RequestParams = {}) =>
this.request<V1Beta1GetBlockByHeightResponse, RpcStatus>({
path: `/cosmos/base/tendermint/v1beta1/blocks/${height}`,
method: "GET",
format: "json",
...params,
});
/**
* No description
*
* @tags Service
* @name ServiceGetNodeInfo
* @summary GetNodeInfo queries the current node info.
* @request GET:/cosmos/base/tendermint/v1beta1/node_info
*/
serviceGetNodeInfo = (params: RequestParams = {}) =>
this.request<V1Beta1GetNodeInfoResponse, RpcStatus>({
path: `/cosmos/base/tendermint/v1beta1/node_info`,
method: "GET",
format: "json",
...params,
});
/**
* No description
*
* @tags Service
* @name ServiceGetSyncing
* @summary GetSyncing queries node syncing.
* @request GET:/cosmos/base/tendermint/v1beta1/syncing
*/
serviceGetSyncing = (params: RequestParams = {}) =>
this.request<V1Beta1GetSyncingResponse, RpcStatus>({
path: `/cosmos/base/tendermint/v1beta1/syncing`,
method: "GET",
format: "json",
...params,
});
/**
* No description
*
* @tags Service
* @name ServiceGetLatestValidatorSet
* @summary GetLatestValidatorSet queries latest validator-set.
* @request GET:/cosmos/base/tendermint/v1beta1/validatorsets/latest
*/
serviceGetLatestValidatorSet = (
query?: {
"pagination.key"?: string;
"pagination.offset"?: string;
"pagination.limit"?: string;
"pagination.count_total"?: boolean;
"pagination.reverse"?: boolean;
},
params: RequestParams = {},
) =>
this.request<V1Beta1GetLatestValidatorSetResponse, RpcStatus>({
path: `/cosmos/base/tendermint/v1beta1/validatorsets/latest`,
method: "GET",
query: query,
format: "json",
...params,
});
/**
* No description
*
* @tags Service
* @name ServiceGetValidatorSetByHeight
* @summary GetValidatorSetByHeight queries validator-set at a given height.
* @request GET:/cosmos/base/tendermint/v1beta1/validatorsets/{height}
*/
serviceGetValidatorSetByHeight = (
height: string,
query?: {
"pagination.key"?: string;
"pagination.offset"?: string;
"pagination.limit"?: string;
"pagination.count_total"?: boolean;
"pagination.reverse"?: boolean;
},
params: RequestParams = {},
) =>
this.request<V1Beta1GetValidatorSetByHeightResponse, RpcStatus>({
path: `/cosmos/base/tendermint/v1beta1/validatorsets/${height}`,
method: "GET",
query: query,
format: "json",
...params,
});
}

View File

@ -0,0 +1,328 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "cosmos.base.query.v1beta1";
/**
* PageRequest is to be embedded in gRPC request messages for efficient
* pagination. Ex:
*
* message SomeRequest {
* Foo some_parameter = 1;
* PageRequest pagination = 2;
* }
*/
export interface PageRequest {
/**
* key is a value returned in PageResponse.next_key to begin
* querying the next page most efficiently. Only one of offset or key
* should be set.
*/
key: Uint8Array;
/**
* offset is a numeric offset that can be used when key is unavailable.
* It is less efficient than using key. Only one of offset or key should
* be set.
*/
offset: number;
/**
* limit is the total number of results to be returned in the result page.
* If left empty it will default to a value to be set by each app.
*/
limit: number;
/**
* count_total is set to true to indicate that the result set should include
* a count of the total number of items available for pagination in UIs.
* count_total is only respected when offset is used. It is ignored when key
* is set.
*/
count_total: boolean;
/**
* reverse is set to true if results are to be returned in the descending order.
*
* Since: cosmos-sdk 0.43
*/
reverse: boolean;
}
/**
* PageResponse is to be embedded in gRPC response messages where the
* corresponding request message has used PageRequest.
*
* message SomeResponse {
* repeated Bar results = 1;
* PageResponse page = 2;
* }
*/
export interface PageResponse {
/**
* next_key is the key to be passed to PageRequest.key to
* query the next page most efficiently
*/
next_key: Uint8Array;
/**
* total is total number of results available if PageRequest.count_total
* was set, its value is undefined otherwise
*/
total: number;
}
const basePageRequest: object = {
offset: 0,
limit: 0,
count_total: false,
reverse: false,
};
export const PageRequest = {
encode(message: PageRequest, writer: Writer = Writer.create()): Writer {
if (message.key.length !== 0) {
writer.uint32(10).bytes(message.key);
}
if (message.offset !== 0) {
writer.uint32(16).uint64(message.offset);
}
if (message.limit !== 0) {
writer.uint32(24).uint64(message.limit);
}
if (message.count_total === true) {
writer.uint32(32).bool(message.count_total);
}
if (message.reverse === true) {
writer.uint32(40).bool(message.reverse);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageRequest {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageRequest } as PageRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.bytes();
break;
case 2:
message.offset = longToNumber(reader.uint64() as Long);
break;
case 3:
message.limit = longToNumber(reader.uint64() as Long);
break;
case 4:
message.count_total = reader.bool();
break;
case 5:
message.reverse = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = bytesFromBase64(object.key);
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = Number(object.offset);
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = Number(object.limit);
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = Boolean(object.count_total);
} else {
message.count_total = false;
}
if (object.reverse !== undefined && object.reverse !== null) {
message.reverse = Boolean(object.reverse);
} else {
message.reverse = false;
}
return message;
},
toJSON(message: PageRequest): unknown {
const obj: any = {};
message.key !== undefined &&
(obj.key = base64FromBytes(
message.key !== undefined ? message.key : new Uint8Array()
));
message.offset !== undefined && (obj.offset = message.offset);
message.limit !== undefined && (obj.limit = message.limit);
message.count_total !== undefined &&
(obj.count_total = message.count_total);
message.reverse !== undefined && (obj.reverse = message.reverse);
return obj;
},
fromPartial(object: DeepPartial<PageRequest>): PageRequest {
const message = { ...basePageRequest } as PageRequest;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = new Uint8Array();
}
if (object.offset !== undefined && object.offset !== null) {
message.offset = object.offset;
} else {
message.offset = 0;
}
if (object.limit !== undefined && object.limit !== null) {
message.limit = object.limit;
} else {
message.limit = 0;
}
if (object.count_total !== undefined && object.count_total !== null) {
message.count_total = object.count_total;
} else {
message.count_total = false;
}
if (object.reverse !== undefined && object.reverse !== null) {
message.reverse = object.reverse;
} else {
message.reverse = false;
}
return message;
},
};
const basePageResponse: object = { total: 0 };
export const PageResponse = {
encode(message: PageResponse, writer: Writer = Writer.create()): Writer {
if (message.next_key.length !== 0) {
writer.uint32(10).bytes(message.next_key);
}
if (message.total !== 0) {
writer.uint32(16).uint64(message.total);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PageResponse {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePageResponse } as PageResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.next_key = reader.bytes();
break;
case 2:
message.total = longToNumber(reader.uint64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = bytesFromBase64(object.next_key);
}
if (object.total !== undefined && object.total !== null) {
message.total = Number(object.total);
} else {
message.total = 0;
}
return message;
},
toJSON(message: PageResponse): unknown {
const obj: any = {};
message.next_key !== undefined &&
(obj.next_key = base64FromBytes(
message.next_key !== undefined ? message.next_key : new Uint8Array()
));
message.total !== undefined && (obj.total = message.total);
return obj;
},
fromPartial(object: DeepPartial<PageResponse>): PageResponse {
const message = { ...basePageResponse } as PageResponse;
if (object.next_key !== undefined && object.next_key !== null) {
message.next_key = object.next_key;
} else {
message.next_key = new Uint8Array();
}
if (object.total !== undefined && object.total !== null) {
message.total = object.total;
} else {
message.total = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "gogoproto";

View File

@ -0,0 +1,2 @@
/* eslint-disable */
export const protobufPackage = "google.api";

View File

@ -0,0 +1,706 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "google.api";
/**
* Defines the HTTP configuration for an API service. It contains a list of
* [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
* to one or more HTTP REST API methods.
*/
export interface Http {
/**
* A list of HTTP configuration rules that apply to individual API methods.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
*/
rules: HttpRule[];
/**
* When set to true, URL path parmeters will be fully URI-decoded except in
* cases of single segment matches in reserved expansion, where "%2F" will be
* left encoded.
*
* The default behavior is to not decode RFC 6570 reserved characters in multi
* segment matches.
*/
fully_decode_reserved_expansion: boolean;
}
/**
* `HttpRule` defines the mapping of an RPC method to one or more HTTP
* REST API methods. The mapping specifies how different portions of the RPC
* request message are mapped to URL path, URL query parameters, and
* HTTP request body. The mapping is typically specified as an
* `google.api.http` annotation on the RPC method,
* see "google/api/annotations.proto" for details.
*
* The mapping consists of a field specifying the path template and
* method kind. The path template can refer to fields in the request
* message, as in the example below which describes a REST GET
* operation on a resource collection of messages:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* SubMessage sub = 2; // `sub.subfield` is url-mapped
* }
* message Message {
* string text = 1; // content of the resource
* }
*
* The same http annotation can alternatively be expressed inside the
* `GRPC API Configuration` YAML file.
*
* http:
* rules:
* - selector: <proto_package_name>.Messaging.GetMessage
* get: /v1/messages/{message_id}/{sub.subfield}
*
* This definition enables an automatic, bidrectional mapping of HTTP
* JSON to RPC. Example:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))`
*
* In general, not only fields but also field paths can be referenced
* from a path pattern. Fields mapped to the path pattern cannot be
* repeated and must have a primitive (non-message) type.
*
* Any fields in the request message which are not bound by the path
* pattern automatically become (optional) HTTP query
* parameters. Assume the following definition of the request message:
*
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http).get = "/v1/messages/{message_id}";
* }
* }
* message GetMessageRequest {
* message SubMessage {
* string subfield = 1;
* }
* string message_id = 1; // mapped to the URL
* int64 revision = 2; // becomes a parameter
* SubMessage sub = 3; // `sub.subfield` becomes a parameter
* }
*
*
* This enables a HTTP JSON to RPC mapping as below:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))`
*
* Note that fields which are mapped to HTTP parameters must have a
* primitive type or a repeated primitive type. Message types are not
* allowed. In the case of a repeated type, the parameter can be
* repeated in the URL, as in `...?param=A&param=B`.
*
* For HTTP method kinds which allow a request body, the `body` field
* specifies the mapping. Consider a REST update method on the
* message resource collection:
*
*
* service Messaging {
* rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "message"
* };
* }
* }
* message UpdateMessageRequest {
* string message_id = 1; // mapped to the URL
* Message message = 2; // mapped to the body
* }
*
*
* The following HTTP JSON to RPC mapping is enabled, where the
* representation of the JSON in the request body is determined by
* protos JSON encoding:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
*
* The special name `*` can be used in the body mapping to define that
* every field not bound by the path template should be mapped to the
* request body. This enables the following alternative definition of
* the update method:
*
* service Messaging {
* rpc UpdateMessage(Message) returns (Message) {
* option (google.api.http) = {
* put: "/v1/messages/{message_id}"
* body: "*"
* };
* }
* }
* message Message {
* string message_id = 1;
* string text = 2;
* }
*
*
* The following HTTP JSON to RPC mapping is enabled:
*
* HTTP | RPC
* -----|-----
* `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")`
*
* Note that when using `*` in the body mapping, it is not possible to
* have HTTP parameters, as all fields not bound by the path end in
* the body. This makes this option more rarely used in practice of
* defining REST APIs. The common usage of `*` is in custom methods
* which don't use the URL at all for transferring data.
*
* It is possible to define multiple HTTP methods for one RPC by using
* the `additional_bindings` option. Example:
*
* service Messaging {
* rpc GetMessage(GetMessageRequest) returns (Message) {
* option (google.api.http) = {
* get: "/v1/messages/{message_id}"
* additional_bindings {
* get: "/v1/users/{user_id}/messages/{message_id}"
* }
* };
* }
* }
* message GetMessageRequest {
* string message_id = 1;
* string user_id = 2;
* }
*
*
* This enables the following two alternative HTTP JSON to RPC
* mappings:
*
* HTTP | RPC
* -----|-----
* `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
* `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")`
*
* # Rules for HTTP mapping
*
* The rules for mapping HTTP path, query parameters, and body fields
* to the request message are as follows:
*
* 1. The `body` field specifies either `*` or a field path, or is
* omitted. If omitted, it indicates there is no HTTP request body.
* 2. Leaf fields (recursive expansion of nested messages in the
* request) can be classified into three types:
* (a) Matched in the URL template.
* (b) Covered by body (if body is `*`, everything except (a) fields;
* else everything under the body field)
* (c) All other fields.
* 3. URL query parameters found in the HTTP request are mapped to (c) fields.
* 4. Any body sent with an HTTP request can contain only (b) fields.
*
* The syntax of the path template is as follows:
*
* Template = "/" Segments [ Verb ] ;
* Segments = Segment { "/" Segment } ;
* Segment = "*" | "**" | LITERAL | Variable ;
* Variable = "{" FieldPath [ "=" Segments ] "}" ;
* FieldPath = IDENT { "." IDENT } ;
* Verb = ":" LITERAL ;
*
* The syntax `*` matches a single path segment. The syntax `**` matches zero
* or more path segments, which must be the last part of the path except the
* `Verb`. The syntax `LITERAL` matches literal text in the path.
*
* The syntax `Variable` matches part of the URL path as specified by its
* template. A variable template must not contain other variables. If a variable
* matches a single path segment, its template may be omitted, e.g. `{var}`
* is equivalent to `{var=*}`.
*
* If a variable contains exactly one path segment, such as `"{var}"` or
* `"{var=*}"`, when such a variable is expanded into a URL path, all characters
* except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the
* Discovery Document as `{var}`.
*
* If a variable contains one or more path segments, such as `"{var=foo/*}"`
* or `"{var=**}"`, when such a variable is expanded into a URL path, all
* characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables
* show up in the Discovery Document as `{+var}`.
*
* NOTE: While the single segment variable matches the semantics of
* [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2
* Simple String Expansion, the multi segment variable **does not** match
* RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion
* does not expand special characters like `?` and `#`, which would lead
* to invalid URLs.
*
* NOTE: the field paths in variables and in the `body` must not refer to
* repeated fields or map fields.
*/
export interface HttpRule {
/**
* Selects methods to which this rule applies.
*
* Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
*/
selector: string;
/** Used for listing and getting information about resources. */
get: string | undefined;
/** Used for updating a resource. */
put: string | undefined;
/** Used for creating a resource. */
post: string | undefined;
/** Used for deleting a resource. */
delete: string | undefined;
/** Used for updating a resource. */
patch: string | undefined;
/**
* The custom pattern is used for specifying an HTTP method that is not
* included in the `pattern` field, such as HEAD, or "*" to leave the
* HTTP method unspecified for this rule. The wild-card rule is useful
* for services that provide content to Web (HTML) clients.
*/
custom: CustomHttpPattern | undefined;
/**
* The name of the request field whose value is mapped to the HTTP body, or
* `*` for mapping all fields not captured by the path pattern to the HTTP
* body. NOTE: the referred field must not be a repeated field and must be
* present at the top-level of request message type.
*/
body: string;
/**
* Optional. The name of the response field whose value is mapped to the HTTP
* body of response. Other response fields are ignored. When
* not set, the response message will be used as HTTP body of response.
*/
response_body: string;
/**
* Additional HTTP bindings for the selector. Nested bindings must
* not contain an `additional_bindings` field themselves (that is,
* the nesting may only be one level deep).
*/
additional_bindings: HttpRule[];
}
/** A custom pattern is used for defining custom HTTP verb. */
export interface CustomHttpPattern {
/** The name of this custom HTTP verb. */
kind: string;
/** The path matched by this custom verb. */
path: string;
}
const baseHttp: object = { fully_decode_reserved_expansion: false };
export const Http = {
encode(message: Http, writer: Writer = Writer.create()): Writer {
for (const v of message.rules) {
HttpRule.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.fully_decode_reserved_expansion === true) {
writer.uint32(16).bool(message.fully_decode_reserved_expansion);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Http {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttp } as Http;
message.rules = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.rules.push(HttpRule.decode(reader, reader.uint32()));
break;
case 2:
message.fully_decode_reserved_expansion = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromJSON(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion = Boolean(
object.fully_decode_reserved_expansion
);
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
toJSON(message: Http): unknown {
const obj: any = {};
if (message.rules) {
obj.rules = message.rules.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.rules = [];
}
message.fully_decode_reserved_expansion !== undefined &&
(obj.fully_decode_reserved_expansion =
message.fully_decode_reserved_expansion);
return obj;
},
fromPartial(object: DeepPartial<Http>): Http {
const message = { ...baseHttp } as Http;
message.rules = [];
if (object.rules !== undefined && object.rules !== null) {
for (const e of object.rules) {
message.rules.push(HttpRule.fromPartial(e));
}
}
if (
object.fully_decode_reserved_expansion !== undefined &&
object.fully_decode_reserved_expansion !== null
) {
message.fully_decode_reserved_expansion =
object.fully_decode_reserved_expansion;
} else {
message.fully_decode_reserved_expansion = false;
}
return message;
},
};
const baseHttpRule: object = { selector: "", body: "", response_body: "" };
export const HttpRule = {
encode(message: HttpRule, writer: Writer = Writer.create()): Writer {
if (message.selector !== "") {
writer.uint32(10).string(message.selector);
}
if (message.get !== undefined) {
writer.uint32(18).string(message.get);
}
if (message.put !== undefined) {
writer.uint32(26).string(message.put);
}
if (message.post !== undefined) {
writer.uint32(34).string(message.post);
}
if (message.delete !== undefined) {
writer.uint32(42).string(message.delete);
}
if (message.patch !== undefined) {
writer.uint32(50).string(message.patch);
}
if (message.custom !== undefined) {
CustomHttpPattern.encode(
message.custom,
writer.uint32(66).fork()
).ldelim();
}
if (message.body !== "") {
writer.uint32(58).string(message.body);
}
if (message.response_body !== "") {
writer.uint32(98).string(message.response_body);
}
for (const v of message.additional_bindings) {
HttpRule.encode(v!, writer.uint32(90).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): HttpRule {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.selector = reader.string();
break;
case 2:
message.get = reader.string();
break;
case 3:
message.put = reader.string();
break;
case 4:
message.post = reader.string();
break;
case 5:
message.delete = reader.string();
break;
case 6:
message.patch = reader.string();
break;
case 8:
message.custom = CustomHttpPattern.decode(reader, reader.uint32());
break;
case 7:
message.body = reader.string();
break;
case 12:
message.response_body = reader.string();
break;
case 11:
message.additional_bindings.push(
HttpRule.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = String(object.selector);
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = String(object.get);
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = String(object.put);
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = String(object.post);
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = String(object.delete);
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = String(object.patch);
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromJSON(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = String(object.body);
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = String(object.response_body);
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromJSON(e));
}
}
return message;
},
toJSON(message: HttpRule): unknown {
const obj: any = {};
message.selector !== undefined && (obj.selector = message.selector);
message.get !== undefined && (obj.get = message.get);
message.put !== undefined && (obj.put = message.put);
message.post !== undefined && (obj.post = message.post);
message.delete !== undefined && (obj.delete = message.delete);
message.patch !== undefined && (obj.patch = message.patch);
message.custom !== undefined &&
(obj.custom = message.custom
? CustomHttpPattern.toJSON(message.custom)
: undefined);
message.body !== undefined && (obj.body = message.body);
message.response_body !== undefined &&
(obj.response_body = message.response_body);
if (message.additional_bindings) {
obj.additional_bindings = message.additional_bindings.map((e) =>
e ? HttpRule.toJSON(e) : undefined
);
} else {
obj.additional_bindings = [];
}
return obj;
},
fromPartial(object: DeepPartial<HttpRule>): HttpRule {
const message = { ...baseHttpRule } as HttpRule;
message.additional_bindings = [];
if (object.selector !== undefined && object.selector !== null) {
message.selector = object.selector;
} else {
message.selector = "";
}
if (object.get !== undefined && object.get !== null) {
message.get = object.get;
} else {
message.get = undefined;
}
if (object.put !== undefined && object.put !== null) {
message.put = object.put;
} else {
message.put = undefined;
}
if (object.post !== undefined && object.post !== null) {
message.post = object.post;
} else {
message.post = undefined;
}
if (object.delete !== undefined && object.delete !== null) {
message.delete = object.delete;
} else {
message.delete = undefined;
}
if (object.patch !== undefined && object.patch !== null) {
message.patch = object.patch;
} else {
message.patch = undefined;
}
if (object.custom !== undefined && object.custom !== null) {
message.custom = CustomHttpPattern.fromPartial(object.custom);
} else {
message.custom = undefined;
}
if (object.body !== undefined && object.body !== null) {
message.body = object.body;
} else {
message.body = "";
}
if (object.response_body !== undefined && object.response_body !== null) {
message.response_body = object.response_body;
} else {
message.response_body = "";
}
if (
object.additional_bindings !== undefined &&
object.additional_bindings !== null
) {
for (const e of object.additional_bindings) {
message.additional_bindings.push(HttpRule.fromPartial(e));
}
}
return message;
},
};
const baseCustomHttpPattern: object = { kind: "", path: "" };
export const CustomHttpPattern = {
encode(message: CustomHttpPattern, writer: Writer = Writer.create()): Writer {
if (message.kind !== "") {
writer.uint32(10).string(message.kind);
}
if (message.path !== "") {
writer.uint32(18).string(message.path);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): CustomHttpPattern {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.kind = reader.string();
break;
case 2:
message.path = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = String(object.kind);
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = String(object.path);
} else {
message.path = "";
}
return message;
},
toJSON(message: CustomHttpPattern): unknown {
const obj: any = {};
message.kind !== undefined && (obj.kind = message.kind);
message.path !== undefined && (obj.path = message.path);
return obj;
},
fromPartial(object: DeepPartial<CustomHttpPattern>): CustomHttpPattern {
const message = { ...baseCustomHttpPattern } as CustomHttpPattern;
if (object.kind !== undefined && object.kind !== null) {
message.kind = object.kind;
} else {
message.kind = "";
}
if (object.path !== undefined && object.path !== null) {
message.path = object.path;
} else {
message.path = "";
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,240 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "google.protobuf";
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := anypb.New(foo)
* if err != nil {
* ...
* }
* ...
* foo := &pb.Foo{}
* if err := any.UnmarshalTo(foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
*
* JSON
* ====
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message [google.protobuf.Duration][]):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*/
export interface Any {
/**
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a [google.protobuf.Type][]
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*/
type_url: string;
/** Must be a valid serialized protocol buffer of the above specified type. */
value: Uint8Array;
}
const baseAny: object = { type_url: "" };
export const Any = {
encode(message: Any, writer: Writer = Writer.create()): Writer {
if (message.type_url !== "") {
writer.uint32(10).string(message.type_url);
}
if (message.value.length !== 0) {
writer.uint32(18).bytes(message.value);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Any {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseAny } as Any;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.type_url = reader.string();
break;
case 2:
message.value = reader.bytes();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Any {
const message = { ...baseAny } as Any;
if (object.type_url !== undefined && object.type_url !== null) {
message.type_url = String(object.type_url);
} else {
message.type_url = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = bytesFromBase64(object.value);
}
return message;
},
toJSON(message: Any): unknown {
const obj: any = {};
message.type_url !== undefined && (obj.type_url = message.type_url);
message.value !== undefined &&
(obj.value = base64FromBytes(
message.value !== undefined ? message.value : new Uint8Array()
));
return obj;
},
fromPartial(object: DeepPartial<Any>): Any {
const message = { ...baseAny } as Any;
if (object.type_url !== undefined && object.type_url !== null) {
message.type_url = object.type_url;
} else {
message.type_url = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = new Uint8Array();
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,219 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "google.protobuf";
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
*
* Example 5: Compute Timestamp from Java `Instant.now()`.
*
* Instant now = Instant.now();
*
* Timestamp timestamp =
* Timestamp.newBuilder().setSeconds(now.getEpochSecond())
* .setNanos(now.getNano()).build();
*
*
* Example 6: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](
* http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
* ) to obtain a formatter capable of generating timestamps in this format.
*/
export interface Timestamp {
/**
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*/
seconds: number;
/**
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*/
nanos: number;
}
const baseTimestamp: object = { seconds: 0, nanos: 0 };
export const Timestamp = {
encode(message: Timestamp, writer: Writer = Writer.create()): Writer {
if (message.seconds !== 0) {
writer.uint32(8).int64(message.seconds);
}
if (message.nanos !== 0) {
writer.uint32(16).int32(message.nanos);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Timestamp {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseTimestamp } as Timestamp;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.seconds = longToNumber(reader.int64() as Long);
break;
case 2:
message.nanos = reader.int32();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Timestamp {
const message = { ...baseTimestamp } as Timestamp;
if (object.seconds !== undefined && object.seconds !== null) {
message.seconds = Number(object.seconds);
} else {
message.seconds = 0;
}
if (object.nanos !== undefined && object.nanos !== null) {
message.nanos = Number(object.nanos);
} else {
message.nanos = 0;
}
return message;
},
toJSON(message: Timestamp): unknown {
const obj: any = {};
message.seconds !== undefined && (obj.seconds = message.seconds);
message.nanos !== undefined && (obj.nanos = message.nanos);
return obj;
},
fromPartial(object: DeepPartial<Timestamp>): Timestamp {
const message = { ...baseTimestamp } as Timestamp;
if (object.seconds !== undefined && object.seconds !== null) {
message.seconds = object.seconds;
} else {
message.seconds = 0;
}
if (object.nanos !== undefined && object.nanos !== null) {
message.nanos = object.nanos;
} else {
message.nanos = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,130 @@
/* eslint-disable */
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "tendermint.crypto";
/** PublicKey defines the keys available for use with Tendermint Validators */
export interface PublicKey {
ed25519: Uint8Array | undefined;
secp256k1: Uint8Array | undefined;
}
const basePublicKey: object = {};
export const PublicKey = {
encode(message: PublicKey, writer: Writer = Writer.create()): Writer {
if (message.ed25519 !== undefined) {
writer.uint32(10).bytes(message.ed25519);
}
if (message.secp256k1 !== undefined) {
writer.uint32(18).bytes(message.secp256k1);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): PublicKey {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...basePublicKey } as PublicKey;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.ed25519 = reader.bytes();
break;
case 2:
message.secp256k1 = reader.bytes();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): PublicKey {
const message = { ...basePublicKey } as PublicKey;
if (object.ed25519 !== undefined && object.ed25519 !== null) {
message.ed25519 = bytesFromBase64(object.ed25519);
}
if (object.secp256k1 !== undefined && object.secp256k1 !== null) {
message.secp256k1 = bytesFromBase64(object.secp256k1);
}
return message;
},
toJSON(message: PublicKey): unknown {
const obj: any = {};
message.ed25519 !== undefined &&
(obj.ed25519 =
message.ed25519 !== undefined
? base64FromBytes(message.ed25519)
: undefined);
message.secp256k1 !== undefined &&
(obj.secp256k1 =
message.secp256k1 !== undefined
? base64FromBytes(message.secp256k1)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<PublicKey>): PublicKey {
const message = { ...basePublicKey } as PublicKey;
if (object.ed25519 !== undefined && object.ed25519 !== null) {
message.ed25519 = object.ed25519;
} else {
message.ed25519 = undefined;
}
if (object.secp256k1 !== undefined && object.secp256k1 !== null) {
message.secp256k1 = object.secp256k1;
} else {
message.secp256k1 = undefined;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,529 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "tendermint.crypto";
export interface Proof {
total: number;
index: number;
leaf_hash: Uint8Array;
aunts: Uint8Array[];
}
export interface ValueOp {
/** Encoded in ProofOp.Key. */
key: Uint8Array;
/** To encode in ProofOp.Data */
proof: Proof | undefined;
}
export interface DominoOp {
key: string;
input: string;
output: string;
}
/**
* ProofOp defines an operation used for calculating Merkle root
* The data could be arbitrary format, providing nessecary data
* for example neighbouring node hash
*/
export interface ProofOp {
type: string;
key: Uint8Array;
data: Uint8Array;
}
/** ProofOps is Merkle proof defined by the list of ProofOps */
export interface ProofOps {
ops: ProofOp[];
}
const baseProof: object = { total: 0, index: 0 };
export const Proof = {
encode(message: Proof, writer: Writer = Writer.create()): Writer {
if (message.total !== 0) {
writer.uint32(8).int64(message.total);
}
if (message.index !== 0) {
writer.uint32(16).int64(message.index);
}
if (message.leaf_hash.length !== 0) {
writer.uint32(26).bytes(message.leaf_hash);
}
for (const v of message.aunts) {
writer.uint32(34).bytes(v!);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Proof {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseProof } as Proof;
message.aunts = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.total = longToNumber(reader.int64() as Long);
break;
case 2:
message.index = longToNumber(reader.int64() as Long);
break;
case 3:
message.leaf_hash = reader.bytes();
break;
case 4:
message.aunts.push(reader.bytes());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Proof {
const message = { ...baseProof } as Proof;
message.aunts = [];
if (object.total !== undefined && object.total !== null) {
message.total = Number(object.total);
} else {
message.total = 0;
}
if (object.index !== undefined && object.index !== null) {
message.index = Number(object.index);
} else {
message.index = 0;
}
if (object.leaf_hash !== undefined && object.leaf_hash !== null) {
message.leaf_hash = bytesFromBase64(object.leaf_hash);
}
if (object.aunts !== undefined && object.aunts !== null) {
for (const e of object.aunts) {
message.aunts.push(bytesFromBase64(e));
}
}
return message;
},
toJSON(message: Proof): unknown {
const obj: any = {};
message.total !== undefined && (obj.total = message.total);
message.index !== undefined && (obj.index = message.index);
message.leaf_hash !== undefined &&
(obj.leaf_hash = base64FromBytes(
message.leaf_hash !== undefined ? message.leaf_hash : new Uint8Array()
));
if (message.aunts) {
obj.aunts = message.aunts.map((e) =>
base64FromBytes(e !== undefined ? e : new Uint8Array())
);
} else {
obj.aunts = [];
}
return obj;
},
fromPartial(object: DeepPartial<Proof>): Proof {
const message = { ...baseProof } as Proof;
message.aunts = [];
if (object.total !== undefined && object.total !== null) {
message.total = object.total;
} else {
message.total = 0;
}
if (object.index !== undefined && object.index !== null) {
message.index = object.index;
} else {
message.index = 0;
}
if (object.leaf_hash !== undefined && object.leaf_hash !== null) {
message.leaf_hash = object.leaf_hash;
} else {
message.leaf_hash = new Uint8Array();
}
if (object.aunts !== undefined && object.aunts !== null) {
for (const e of object.aunts) {
message.aunts.push(e);
}
}
return message;
},
};
const baseValueOp: object = {};
export const ValueOp = {
encode(message: ValueOp, writer: Writer = Writer.create()): Writer {
if (message.key.length !== 0) {
writer.uint32(10).bytes(message.key);
}
if (message.proof !== undefined) {
Proof.encode(message.proof, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): ValueOp {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseValueOp } as ValueOp;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.bytes();
break;
case 2:
message.proof = Proof.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ValueOp {
const message = { ...baseValueOp } as ValueOp;
if (object.key !== undefined && object.key !== null) {
message.key = bytesFromBase64(object.key);
}
if (object.proof !== undefined && object.proof !== null) {
message.proof = Proof.fromJSON(object.proof);
} else {
message.proof = undefined;
}
return message;
},
toJSON(message: ValueOp): unknown {
const obj: any = {};
message.key !== undefined &&
(obj.key = base64FromBytes(
message.key !== undefined ? message.key : new Uint8Array()
));
message.proof !== undefined &&
(obj.proof = message.proof ? Proof.toJSON(message.proof) : undefined);
return obj;
},
fromPartial(object: DeepPartial<ValueOp>): ValueOp {
const message = { ...baseValueOp } as ValueOp;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = new Uint8Array();
}
if (object.proof !== undefined && object.proof !== null) {
message.proof = Proof.fromPartial(object.proof);
} else {
message.proof = undefined;
}
return message;
},
};
const baseDominoOp: object = { key: "", input: "", output: "" };
export const DominoOp = {
encode(message: DominoOp, writer: Writer = Writer.create()): Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.input !== "") {
writer.uint32(18).string(message.input);
}
if (message.output !== "") {
writer.uint32(26).string(message.output);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): DominoOp {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDominoOp } as DominoOp;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.input = reader.string();
break;
case 3:
message.output = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DominoOp {
const message = { ...baseDominoOp } as DominoOp;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.input !== undefined && object.input !== null) {
message.input = String(object.input);
} else {
message.input = "";
}
if (object.output !== undefined && object.output !== null) {
message.output = String(object.output);
} else {
message.output = "";
}
return message;
},
toJSON(message: DominoOp): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.input !== undefined && (obj.input = message.input);
message.output !== undefined && (obj.output = message.output);
return obj;
},
fromPartial(object: DeepPartial<DominoOp>): DominoOp {
const message = { ...baseDominoOp } as DominoOp;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.input !== undefined && object.input !== null) {
message.input = object.input;
} else {
message.input = "";
}
if (object.output !== undefined && object.output !== null) {
message.output = object.output;
} else {
message.output = "";
}
return message;
},
};
const baseProofOp: object = { type: "" };
export const ProofOp = {
encode(message: ProofOp, writer: Writer = Writer.create()): Writer {
if (message.type !== "") {
writer.uint32(10).string(message.type);
}
if (message.key.length !== 0) {
writer.uint32(18).bytes(message.key);
}
if (message.data.length !== 0) {
writer.uint32(26).bytes(message.data);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): ProofOp {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseProofOp } as ProofOp;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.type = reader.string();
break;
case 2:
message.key = reader.bytes();
break;
case 3:
message.data = reader.bytes();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ProofOp {
const message = { ...baseProofOp } as ProofOp;
if (object.type !== undefined && object.type !== null) {
message.type = String(object.type);
} else {
message.type = "";
}
if (object.key !== undefined && object.key !== null) {
message.key = bytesFromBase64(object.key);
}
if (object.data !== undefined && object.data !== null) {
message.data = bytesFromBase64(object.data);
}
return message;
},
toJSON(message: ProofOp): unknown {
const obj: any = {};
message.type !== undefined && (obj.type = message.type);
message.key !== undefined &&
(obj.key = base64FromBytes(
message.key !== undefined ? message.key : new Uint8Array()
));
message.data !== undefined &&
(obj.data = base64FromBytes(
message.data !== undefined ? message.data : new Uint8Array()
));
return obj;
},
fromPartial(object: DeepPartial<ProofOp>): ProofOp {
const message = { ...baseProofOp } as ProofOp;
if (object.type !== undefined && object.type !== null) {
message.type = object.type;
} else {
message.type = "";
}
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = new Uint8Array();
}
if (object.data !== undefined && object.data !== null) {
message.data = object.data;
} else {
message.data = new Uint8Array();
}
return message;
},
};
const baseProofOps: object = {};
export const ProofOps = {
encode(message: ProofOps, writer: Writer = Writer.create()): Writer {
for (const v of message.ops) {
ProofOp.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): ProofOps {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseProofOps } as ProofOps;
message.ops = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.ops.push(ProofOp.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ProofOps {
const message = { ...baseProofOps } as ProofOps;
message.ops = [];
if (object.ops !== undefined && object.ops !== null) {
for (const e of object.ops) {
message.ops.push(ProofOp.fromJSON(e));
}
}
return message;
},
toJSON(message: ProofOps): unknown {
const obj: any = {};
if (message.ops) {
obj.ops = message.ops.map((e) => (e ? ProofOp.toJSON(e) : undefined));
} else {
obj.ops = [];
}
return obj;
},
fromPartial(object: DeepPartial<ProofOps>): ProofOps {
const message = { ...baseProofOps } as ProofOps;
message.ops = [];
if (object.ops !== undefined && object.ops !== null) {
for (const e of object.ops) {
message.ops.push(ProofOp.fromPartial(e));
}
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,557 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "tendermint.p2p";
export interface NetAddress {
id: string;
ip: string;
port: number;
}
export interface ProtocolVersion {
p2p: number;
block: number;
app: number;
}
export interface DefaultNodeInfo {
protocol_version: ProtocolVersion | undefined;
default_node_id: string;
listen_addr: string;
network: string;
version: string;
channels: Uint8Array;
moniker: string;
other: DefaultNodeInfoOther | undefined;
}
export interface DefaultNodeInfoOther {
tx_index: string;
rpc_address: string;
}
const baseNetAddress: object = { id: "", ip: "", port: 0 };
export const NetAddress = {
encode(message: NetAddress, writer: Writer = Writer.create()): Writer {
if (message.id !== "") {
writer.uint32(10).string(message.id);
}
if (message.ip !== "") {
writer.uint32(18).string(message.ip);
}
if (message.port !== 0) {
writer.uint32(24).uint32(message.port);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): NetAddress {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseNetAddress } as NetAddress;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.id = reader.string();
break;
case 2:
message.ip = reader.string();
break;
case 3:
message.port = reader.uint32();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): NetAddress {
const message = { ...baseNetAddress } as NetAddress;
if (object.id !== undefined && object.id !== null) {
message.id = String(object.id);
} else {
message.id = "";
}
if (object.ip !== undefined && object.ip !== null) {
message.ip = String(object.ip);
} else {
message.ip = "";
}
if (object.port !== undefined && object.port !== null) {
message.port = Number(object.port);
} else {
message.port = 0;
}
return message;
},
toJSON(message: NetAddress): unknown {
const obj: any = {};
message.id !== undefined && (obj.id = message.id);
message.ip !== undefined && (obj.ip = message.ip);
message.port !== undefined && (obj.port = message.port);
return obj;
},
fromPartial(object: DeepPartial<NetAddress>): NetAddress {
const message = { ...baseNetAddress } as NetAddress;
if (object.id !== undefined && object.id !== null) {
message.id = object.id;
} else {
message.id = "";
}
if (object.ip !== undefined && object.ip !== null) {
message.ip = object.ip;
} else {
message.ip = "";
}
if (object.port !== undefined && object.port !== null) {
message.port = object.port;
} else {
message.port = 0;
}
return message;
},
};
const baseProtocolVersion: object = { p2p: 0, block: 0, app: 0 };
export const ProtocolVersion = {
encode(message: ProtocolVersion, writer: Writer = Writer.create()): Writer {
if (message.p2p !== 0) {
writer.uint32(8).uint64(message.p2p);
}
if (message.block !== 0) {
writer.uint32(16).uint64(message.block);
}
if (message.app !== 0) {
writer.uint32(24).uint64(message.app);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): ProtocolVersion {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseProtocolVersion } as ProtocolVersion;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.p2p = longToNumber(reader.uint64() as Long);
break;
case 2:
message.block = longToNumber(reader.uint64() as Long);
break;
case 3:
message.app = longToNumber(reader.uint64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ProtocolVersion {
const message = { ...baseProtocolVersion } as ProtocolVersion;
if (object.p2p !== undefined && object.p2p !== null) {
message.p2p = Number(object.p2p);
} else {
message.p2p = 0;
}
if (object.block !== undefined && object.block !== null) {
message.block = Number(object.block);
} else {
message.block = 0;
}
if (object.app !== undefined && object.app !== null) {
message.app = Number(object.app);
} else {
message.app = 0;
}
return message;
},
toJSON(message: ProtocolVersion): unknown {
const obj: any = {};
message.p2p !== undefined && (obj.p2p = message.p2p);
message.block !== undefined && (obj.block = message.block);
message.app !== undefined && (obj.app = message.app);
return obj;
},
fromPartial(object: DeepPartial<ProtocolVersion>): ProtocolVersion {
const message = { ...baseProtocolVersion } as ProtocolVersion;
if (object.p2p !== undefined && object.p2p !== null) {
message.p2p = object.p2p;
} else {
message.p2p = 0;
}
if (object.block !== undefined && object.block !== null) {
message.block = object.block;
} else {
message.block = 0;
}
if (object.app !== undefined && object.app !== null) {
message.app = object.app;
} else {
message.app = 0;
}
return message;
},
};
const baseDefaultNodeInfo: object = {
default_node_id: "",
listen_addr: "",
network: "",
version: "",
moniker: "",
};
export const DefaultNodeInfo = {
encode(message: DefaultNodeInfo, writer: Writer = Writer.create()): Writer {
if (message.protocol_version !== undefined) {
ProtocolVersion.encode(
message.protocol_version,
writer.uint32(10).fork()
).ldelim();
}
if (message.default_node_id !== "") {
writer.uint32(18).string(message.default_node_id);
}
if (message.listen_addr !== "") {
writer.uint32(26).string(message.listen_addr);
}
if (message.network !== "") {
writer.uint32(34).string(message.network);
}
if (message.version !== "") {
writer.uint32(42).string(message.version);
}
if (message.channels.length !== 0) {
writer.uint32(50).bytes(message.channels);
}
if (message.moniker !== "") {
writer.uint32(58).string(message.moniker);
}
if (message.other !== undefined) {
DefaultNodeInfoOther.encode(
message.other,
writer.uint32(66).fork()
).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): DefaultNodeInfo {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDefaultNodeInfo } as DefaultNodeInfo;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.protocol_version = ProtocolVersion.decode(
reader,
reader.uint32()
);
break;
case 2:
message.default_node_id = reader.string();
break;
case 3:
message.listen_addr = reader.string();
break;
case 4:
message.network = reader.string();
break;
case 5:
message.version = reader.string();
break;
case 6:
message.channels = reader.bytes();
break;
case 7:
message.moniker = reader.string();
break;
case 8:
message.other = DefaultNodeInfoOther.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DefaultNodeInfo {
const message = { ...baseDefaultNodeInfo } as DefaultNodeInfo;
if (
object.protocol_version !== undefined &&
object.protocol_version !== null
) {
message.protocol_version = ProtocolVersion.fromJSON(
object.protocol_version
);
} else {
message.protocol_version = undefined;
}
if (
object.default_node_id !== undefined &&
object.default_node_id !== null
) {
message.default_node_id = String(object.default_node_id);
} else {
message.default_node_id = "";
}
if (object.listen_addr !== undefined && object.listen_addr !== null) {
message.listen_addr = String(object.listen_addr);
} else {
message.listen_addr = "";
}
if (object.network !== undefined && object.network !== null) {
message.network = String(object.network);
} else {
message.network = "";
}
if (object.version !== undefined && object.version !== null) {
message.version = String(object.version);
} else {
message.version = "";
}
if (object.channels !== undefined && object.channels !== null) {
message.channels = bytesFromBase64(object.channels);
}
if (object.moniker !== undefined && object.moniker !== null) {
message.moniker = String(object.moniker);
} else {
message.moniker = "";
}
if (object.other !== undefined && object.other !== null) {
message.other = DefaultNodeInfoOther.fromJSON(object.other);
} else {
message.other = undefined;
}
return message;
},
toJSON(message: DefaultNodeInfo): unknown {
const obj: any = {};
message.protocol_version !== undefined &&
(obj.protocol_version = message.protocol_version
? ProtocolVersion.toJSON(message.protocol_version)
: undefined);
message.default_node_id !== undefined &&
(obj.default_node_id = message.default_node_id);
message.listen_addr !== undefined &&
(obj.listen_addr = message.listen_addr);
message.network !== undefined && (obj.network = message.network);
message.version !== undefined && (obj.version = message.version);
message.channels !== undefined &&
(obj.channels = base64FromBytes(
message.channels !== undefined ? message.channels : new Uint8Array()
));
message.moniker !== undefined && (obj.moniker = message.moniker);
message.other !== undefined &&
(obj.other = message.other
? DefaultNodeInfoOther.toJSON(message.other)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<DefaultNodeInfo>): DefaultNodeInfo {
const message = { ...baseDefaultNodeInfo } as DefaultNodeInfo;
if (
object.protocol_version !== undefined &&
object.protocol_version !== null
) {
message.protocol_version = ProtocolVersion.fromPartial(
object.protocol_version
);
} else {
message.protocol_version = undefined;
}
if (
object.default_node_id !== undefined &&
object.default_node_id !== null
) {
message.default_node_id = object.default_node_id;
} else {
message.default_node_id = "";
}
if (object.listen_addr !== undefined && object.listen_addr !== null) {
message.listen_addr = object.listen_addr;
} else {
message.listen_addr = "";
}
if (object.network !== undefined && object.network !== null) {
message.network = object.network;
} else {
message.network = "";
}
if (object.version !== undefined && object.version !== null) {
message.version = object.version;
} else {
message.version = "";
}
if (object.channels !== undefined && object.channels !== null) {
message.channels = object.channels;
} else {
message.channels = new Uint8Array();
}
if (object.moniker !== undefined && object.moniker !== null) {
message.moniker = object.moniker;
} else {
message.moniker = "";
}
if (object.other !== undefined && object.other !== null) {
message.other = DefaultNodeInfoOther.fromPartial(object.other);
} else {
message.other = undefined;
}
return message;
},
};
const baseDefaultNodeInfoOther: object = { tx_index: "", rpc_address: "" };
export const DefaultNodeInfoOther = {
encode(
message: DefaultNodeInfoOther,
writer: Writer = Writer.create()
): Writer {
if (message.tx_index !== "") {
writer.uint32(10).string(message.tx_index);
}
if (message.rpc_address !== "") {
writer.uint32(18).string(message.rpc_address);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): DefaultNodeInfoOther {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDefaultNodeInfoOther } as DefaultNodeInfoOther;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.tx_index = reader.string();
break;
case 2:
message.rpc_address = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DefaultNodeInfoOther {
const message = { ...baseDefaultNodeInfoOther } as DefaultNodeInfoOther;
if (object.tx_index !== undefined && object.tx_index !== null) {
message.tx_index = String(object.tx_index);
} else {
message.tx_index = "";
}
if (object.rpc_address !== undefined && object.rpc_address !== null) {
message.rpc_address = String(object.rpc_address);
} else {
message.rpc_address = "";
}
return message;
},
toJSON(message: DefaultNodeInfoOther): unknown {
const obj: any = {};
message.tx_index !== undefined && (obj.tx_index = message.tx_index);
message.rpc_address !== undefined &&
(obj.rpc_address = message.rpc_address);
return obj;
},
fromPartial(object: DeepPartial<DefaultNodeInfoOther>): DefaultNodeInfoOther {
const message = { ...baseDefaultNodeInfoOther } as DefaultNodeInfoOther;
if (object.tx_index !== undefined && object.tx_index !== null) {
message.tx_index = object.tx_index;
} else {
message.tx_index = "";
}
if (object.rpc_address !== undefined && object.rpc_address !== null) {
message.rpc_address = object.rpc_address;
} else {
message.rpc_address = "";
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,138 @@
/* eslint-disable */
import { Header, Data, Commit } from "../../tendermint/types/types";
import { EvidenceList } from "../../tendermint/types/evidence";
import { Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "tendermint.types";
export interface Block {
header: Header | undefined;
data: Data | undefined;
evidence: EvidenceList | undefined;
last_commit: Commit | undefined;
}
const baseBlock: object = {};
export const Block = {
encode(message: Block, writer: Writer = Writer.create()): Writer {
if (message.header !== undefined) {
Header.encode(message.header, writer.uint32(10).fork()).ldelim();
}
if (message.data !== undefined) {
Data.encode(message.data, writer.uint32(18).fork()).ldelim();
}
if (message.evidence !== undefined) {
EvidenceList.encode(message.evidence, writer.uint32(26).fork()).ldelim();
}
if (message.last_commit !== undefined) {
Commit.encode(message.last_commit, writer.uint32(34).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Block {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBlock } as Block;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.header = Header.decode(reader, reader.uint32());
break;
case 2:
message.data = Data.decode(reader, reader.uint32());
break;
case 3:
message.evidence = EvidenceList.decode(reader, reader.uint32());
break;
case 4:
message.last_commit = Commit.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Block {
const message = { ...baseBlock } as Block;
if (object.header !== undefined && object.header !== null) {
message.header = Header.fromJSON(object.header);
} else {
message.header = undefined;
}
if (object.data !== undefined && object.data !== null) {
message.data = Data.fromJSON(object.data);
} else {
message.data = undefined;
}
if (object.evidence !== undefined && object.evidence !== null) {
message.evidence = EvidenceList.fromJSON(object.evidence);
} else {
message.evidence = undefined;
}
if (object.last_commit !== undefined && object.last_commit !== null) {
message.last_commit = Commit.fromJSON(object.last_commit);
} else {
message.last_commit = undefined;
}
return message;
},
toJSON(message: Block): unknown {
const obj: any = {};
message.header !== undefined &&
(obj.header = message.header ? Header.toJSON(message.header) : undefined);
message.data !== undefined &&
(obj.data = message.data ? Data.toJSON(message.data) : undefined);
message.evidence !== undefined &&
(obj.evidence = message.evidence
? EvidenceList.toJSON(message.evidence)
: undefined);
message.last_commit !== undefined &&
(obj.last_commit = message.last_commit
? Commit.toJSON(message.last_commit)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<Block>): Block {
const message = { ...baseBlock } as Block;
if (object.header !== undefined && object.header !== null) {
message.header = Header.fromPartial(object.header);
} else {
message.header = undefined;
}
if (object.data !== undefined && object.data !== null) {
message.data = Data.fromPartial(object.data);
} else {
message.data = undefined;
}
if (object.evidence !== undefined && object.evidence !== null) {
message.evidence = EvidenceList.fromPartial(object.evidence);
} else {
message.evidence = undefined;
}
if (object.last_commit !== undefined && object.last_commit !== null) {
message.last_commit = Commit.fromPartial(object.last_commit);
} else {
message.last_commit = undefined;
}
return message;
},
};
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;

View File

@ -0,0 +1,611 @@
/* eslint-disable */
import { Timestamp } from "../../google/protobuf/timestamp";
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
import { Vote, LightBlock } from "../../tendermint/types/types";
import { Validator } from "../../tendermint/types/validator";
export const protobufPackage = "tendermint.types";
export interface Evidence {
duplicate_vote_evidence: DuplicateVoteEvidence | undefined;
light_client_attack_evidence: LightClientAttackEvidence | undefined;
}
/** DuplicateVoteEvidence contains evidence of a validator signed two conflicting votes. */
export interface DuplicateVoteEvidence {
vote_a: Vote | undefined;
vote_b: Vote | undefined;
total_voting_power: number;
validator_power: number;
timestamp: Date | undefined;
}
/** LightClientAttackEvidence contains evidence of a set of validators attempting to mislead a light client. */
export interface LightClientAttackEvidence {
conflicting_block: LightBlock | undefined;
common_height: number;
byzantine_validators: Validator[];
total_voting_power: number;
timestamp: Date | undefined;
}
export interface EvidenceList {
evidence: Evidence[];
}
const baseEvidence: object = {};
export const Evidence = {
encode(message: Evidence, writer: Writer = Writer.create()): Writer {
if (message.duplicate_vote_evidence !== undefined) {
DuplicateVoteEvidence.encode(
message.duplicate_vote_evidence,
writer.uint32(10).fork()
).ldelim();
}
if (message.light_client_attack_evidence !== undefined) {
LightClientAttackEvidence.encode(
message.light_client_attack_evidence,
writer.uint32(18).fork()
).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Evidence {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseEvidence } as Evidence;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.duplicate_vote_evidence = DuplicateVoteEvidence.decode(
reader,
reader.uint32()
);
break;
case 2:
message.light_client_attack_evidence = LightClientAttackEvidence.decode(
reader,
reader.uint32()
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Evidence {
const message = { ...baseEvidence } as Evidence;
if (
object.duplicate_vote_evidence !== undefined &&
object.duplicate_vote_evidence !== null
) {
message.duplicate_vote_evidence = DuplicateVoteEvidence.fromJSON(
object.duplicate_vote_evidence
);
} else {
message.duplicate_vote_evidence = undefined;
}
if (
object.light_client_attack_evidence !== undefined &&
object.light_client_attack_evidence !== null
) {
message.light_client_attack_evidence = LightClientAttackEvidence.fromJSON(
object.light_client_attack_evidence
);
} else {
message.light_client_attack_evidence = undefined;
}
return message;
},
toJSON(message: Evidence): unknown {
const obj: any = {};
message.duplicate_vote_evidence !== undefined &&
(obj.duplicate_vote_evidence = message.duplicate_vote_evidence
? DuplicateVoteEvidence.toJSON(message.duplicate_vote_evidence)
: undefined);
message.light_client_attack_evidence !== undefined &&
(obj.light_client_attack_evidence = message.light_client_attack_evidence
? LightClientAttackEvidence.toJSON(message.light_client_attack_evidence)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<Evidence>): Evidence {
const message = { ...baseEvidence } as Evidence;
if (
object.duplicate_vote_evidence !== undefined &&
object.duplicate_vote_evidence !== null
) {
message.duplicate_vote_evidence = DuplicateVoteEvidence.fromPartial(
object.duplicate_vote_evidence
);
} else {
message.duplicate_vote_evidence = undefined;
}
if (
object.light_client_attack_evidence !== undefined &&
object.light_client_attack_evidence !== null
) {
message.light_client_attack_evidence = LightClientAttackEvidence.fromPartial(
object.light_client_attack_evidence
);
} else {
message.light_client_attack_evidence = undefined;
}
return message;
},
};
const baseDuplicateVoteEvidence: object = {
total_voting_power: 0,
validator_power: 0,
};
export const DuplicateVoteEvidence = {
encode(
message: DuplicateVoteEvidence,
writer: Writer = Writer.create()
): Writer {
if (message.vote_a !== undefined) {
Vote.encode(message.vote_a, writer.uint32(10).fork()).ldelim();
}
if (message.vote_b !== undefined) {
Vote.encode(message.vote_b, writer.uint32(18).fork()).ldelim();
}
if (message.total_voting_power !== 0) {
writer.uint32(24).int64(message.total_voting_power);
}
if (message.validator_power !== 0) {
writer.uint32(32).int64(message.validator_power);
}
if (message.timestamp !== undefined) {
Timestamp.encode(
toTimestamp(message.timestamp),
writer.uint32(42).fork()
).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): DuplicateVoteEvidence {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDuplicateVoteEvidence } as DuplicateVoteEvidence;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.vote_a = Vote.decode(reader, reader.uint32());
break;
case 2:
message.vote_b = Vote.decode(reader, reader.uint32());
break;
case 3:
message.total_voting_power = longToNumber(reader.int64() as Long);
break;
case 4:
message.validator_power = longToNumber(reader.int64() as Long);
break;
case 5:
message.timestamp = fromTimestamp(
Timestamp.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DuplicateVoteEvidence {
const message = { ...baseDuplicateVoteEvidence } as DuplicateVoteEvidence;
if (object.vote_a !== undefined && object.vote_a !== null) {
message.vote_a = Vote.fromJSON(object.vote_a);
} else {
message.vote_a = undefined;
}
if (object.vote_b !== undefined && object.vote_b !== null) {
message.vote_b = Vote.fromJSON(object.vote_b);
} else {
message.vote_b = undefined;
}
if (
object.total_voting_power !== undefined &&
object.total_voting_power !== null
) {
message.total_voting_power = Number(object.total_voting_power);
} else {
message.total_voting_power = 0;
}
if (
object.validator_power !== undefined &&
object.validator_power !== null
) {
message.validator_power = Number(object.validator_power);
} else {
message.validator_power = 0;
}
if (object.timestamp !== undefined && object.timestamp !== null) {
message.timestamp = fromJsonTimestamp(object.timestamp);
} else {
message.timestamp = undefined;
}
return message;
},
toJSON(message: DuplicateVoteEvidence): unknown {
const obj: any = {};
message.vote_a !== undefined &&
(obj.vote_a = message.vote_a ? Vote.toJSON(message.vote_a) : undefined);
message.vote_b !== undefined &&
(obj.vote_b = message.vote_b ? Vote.toJSON(message.vote_b) : undefined);
message.total_voting_power !== undefined &&
(obj.total_voting_power = message.total_voting_power);
message.validator_power !== undefined &&
(obj.validator_power = message.validator_power);
message.timestamp !== undefined &&
(obj.timestamp =
message.timestamp !== undefined
? message.timestamp.toISOString()
: null);
return obj;
},
fromPartial(
object: DeepPartial<DuplicateVoteEvidence>
): DuplicateVoteEvidence {
const message = { ...baseDuplicateVoteEvidence } as DuplicateVoteEvidence;
if (object.vote_a !== undefined && object.vote_a !== null) {
message.vote_a = Vote.fromPartial(object.vote_a);
} else {
message.vote_a = undefined;
}
if (object.vote_b !== undefined && object.vote_b !== null) {
message.vote_b = Vote.fromPartial(object.vote_b);
} else {
message.vote_b = undefined;
}
if (
object.total_voting_power !== undefined &&
object.total_voting_power !== null
) {
message.total_voting_power = object.total_voting_power;
} else {
message.total_voting_power = 0;
}
if (
object.validator_power !== undefined &&
object.validator_power !== null
) {
message.validator_power = object.validator_power;
} else {
message.validator_power = 0;
}
if (object.timestamp !== undefined && object.timestamp !== null) {
message.timestamp = object.timestamp;
} else {
message.timestamp = undefined;
}
return message;
},
};
const baseLightClientAttackEvidence: object = {
common_height: 0,
total_voting_power: 0,
};
export const LightClientAttackEvidence = {
encode(
message: LightClientAttackEvidence,
writer: Writer = Writer.create()
): Writer {
if (message.conflicting_block !== undefined) {
LightBlock.encode(
message.conflicting_block,
writer.uint32(10).fork()
).ldelim();
}
if (message.common_height !== 0) {
writer.uint32(16).int64(message.common_height);
}
for (const v of message.byzantine_validators) {
Validator.encode(v!, writer.uint32(26).fork()).ldelim();
}
if (message.total_voting_power !== 0) {
writer.uint32(32).int64(message.total_voting_power);
}
if (message.timestamp !== undefined) {
Timestamp.encode(
toTimestamp(message.timestamp),
writer.uint32(42).fork()
).ldelim();
}
return writer;
},
decode(
input: Reader | Uint8Array,
length?: number
): LightClientAttackEvidence {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseLightClientAttackEvidence,
} as LightClientAttackEvidence;
message.byzantine_validators = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.conflicting_block = LightBlock.decode(
reader,
reader.uint32()
);
break;
case 2:
message.common_height = longToNumber(reader.int64() as Long);
break;
case 3:
message.byzantine_validators.push(
Validator.decode(reader, reader.uint32())
);
break;
case 4:
message.total_voting_power = longToNumber(reader.int64() as Long);
break;
case 5:
message.timestamp = fromTimestamp(
Timestamp.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): LightClientAttackEvidence {
const message = {
...baseLightClientAttackEvidence,
} as LightClientAttackEvidence;
message.byzantine_validators = [];
if (
object.conflicting_block !== undefined &&
object.conflicting_block !== null
) {
message.conflicting_block = LightBlock.fromJSON(object.conflicting_block);
} else {
message.conflicting_block = undefined;
}
if (object.common_height !== undefined && object.common_height !== null) {
message.common_height = Number(object.common_height);
} else {
message.common_height = 0;
}
if (
object.byzantine_validators !== undefined &&
object.byzantine_validators !== null
) {
for (const e of object.byzantine_validators) {
message.byzantine_validators.push(Validator.fromJSON(e));
}
}
if (
object.total_voting_power !== undefined &&
object.total_voting_power !== null
) {
message.total_voting_power = Number(object.total_voting_power);
} else {
message.total_voting_power = 0;
}
if (object.timestamp !== undefined && object.timestamp !== null) {
message.timestamp = fromJsonTimestamp(object.timestamp);
} else {
message.timestamp = undefined;
}
return message;
},
toJSON(message: LightClientAttackEvidence): unknown {
const obj: any = {};
message.conflicting_block !== undefined &&
(obj.conflicting_block = message.conflicting_block
? LightBlock.toJSON(message.conflicting_block)
: undefined);
message.common_height !== undefined &&
(obj.common_height = message.common_height);
if (message.byzantine_validators) {
obj.byzantine_validators = message.byzantine_validators.map((e) =>
e ? Validator.toJSON(e) : undefined
);
} else {
obj.byzantine_validators = [];
}
message.total_voting_power !== undefined &&
(obj.total_voting_power = message.total_voting_power);
message.timestamp !== undefined &&
(obj.timestamp =
message.timestamp !== undefined
? message.timestamp.toISOString()
: null);
return obj;
},
fromPartial(
object: DeepPartial<LightClientAttackEvidence>
): LightClientAttackEvidence {
const message = {
...baseLightClientAttackEvidence,
} as LightClientAttackEvidence;
message.byzantine_validators = [];
if (
object.conflicting_block !== undefined &&
object.conflicting_block !== null
) {
message.conflicting_block = LightBlock.fromPartial(
object.conflicting_block
);
} else {
message.conflicting_block = undefined;
}
if (object.common_height !== undefined && object.common_height !== null) {
message.common_height = object.common_height;
} else {
message.common_height = 0;
}
if (
object.byzantine_validators !== undefined &&
object.byzantine_validators !== null
) {
for (const e of object.byzantine_validators) {
message.byzantine_validators.push(Validator.fromPartial(e));
}
}
if (
object.total_voting_power !== undefined &&
object.total_voting_power !== null
) {
message.total_voting_power = object.total_voting_power;
} else {
message.total_voting_power = 0;
}
if (object.timestamp !== undefined && object.timestamp !== null) {
message.timestamp = object.timestamp;
} else {
message.timestamp = undefined;
}
return message;
},
};
const baseEvidenceList: object = {};
export const EvidenceList = {
encode(message: EvidenceList, writer: Writer = Writer.create()): Writer {
for (const v of message.evidence) {
Evidence.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): EvidenceList {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseEvidenceList } as EvidenceList;
message.evidence = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.evidence.push(Evidence.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): EvidenceList {
const message = { ...baseEvidenceList } as EvidenceList;
message.evidence = [];
if (object.evidence !== undefined && object.evidence !== null) {
for (const e of object.evidence) {
message.evidence.push(Evidence.fromJSON(e));
}
}
return message;
},
toJSON(message: EvidenceList): unknown {
const obj: any = {};
if (message.evidence) {
obj.evidence = message.evidence.map((e) =>
e ? Evidence.toJSON(e) : undefined
);
} else {
obj.evidence = [];
}
return obj;
},
fromPartial(object: DeepPartial<EvidenceList>): EvidenceList {
const message = { ...baseEvidenceList } as EvidenceList;
message.evidence = [];
if (object.evidence !== undefined && object.evidence !== null) {
for (const e of object.evidence) {
message.evidence.push(Evidence.fromPartial(e));
}
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function toTimestamp(date: Date): Timestamp {
const seconds = date.getTime() / 1_000;
const nanos = (date.getTime() % 1_000) * 1_000_000;
return { seconds, nanos };
}
function fromTimestamp(t: Timestamp): Date {
let millis = t.seconds * 1_000;
millis += t.nanos / 1_000_000;
return new Date(millis);
}
function fromJsonTimestamp(o: any): Date {
if (o instanceof Date) {
return o;
} else if (typeof o === "string") {
return new Date(o);
} else {
return fromTimestamp(Timestamp.fromJSON(o));
}
}
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,382 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
import { PublicKey } from "../../tendermint/crypto/keys";
export const protobufPackage = "tendermint.types";
export interface ValidatorSet {
validators: Validator[];
proposer: Validator | undefined;
total_voting_power: number;
}
export interface Validator {
address: Uint8Array;
pub_key: PublicKey | undefined;
voting_power: number;
proposer_priority: number;
}
export interface SimpleValidator {
pub_key: PublicKey | undefined;
voting_power: number;
}
const baseValidatorSet: object = { total_voting_power: 0 };
export const ValidatorSet = {
encode(message: ValidatorSet, writer: Writer = Writer.create()): Writer {
for (const v of message.validators) {
Validator.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.proposer !== undefined) {
Validator.encode(message.proposer, writer.uint32(18).fork()).ldelim();
}
if (message.total_voting_power !== 0) {
writer.uint32(24).int64(message.total_voting_power);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): ValidatorSet {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseValidatorSet } as ValidatorSet;
message.validators = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.validators.push(Validator.decode(reader, reader.uint32()));
break;
case 2:
message.proposer = Validator.decode(reader, reader.uint32());
break;
case 3:
message.total_voting_power = longToNumber(reader.int64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ValidatorSet {
const message = { ...baseValidatorSet } as ValidatorSet;
message.validators = [];
if (object.validators !== undefined && object.validators !== null) {
for (const e of object.validators) {
message.validators.push(Validator.fromJSON(e));
}
}
if (object.proposer !== undefined && object.proposer !== null) {
message.proposer = Validator.fromJSON(object.proposer);
} else {
message.proposer = undefined;
}
if (
object.total_voting_power !== undefined &&
object.total_voting_power !== null
) {
message.total_voting_power = Number(object.total_voting_power);
} else {
message.total_voting_power = 0;
}
return message;
},
toJSON(message: ValidatorSet): unknown {
const obj: any = {};
if (message.validators) {
obj.validators = message.validators.map((e) =>
e ? Validator.toJSON(e) : undefined
);
} else {
obj.validators = [];
}
message.proposer !== undefined &&
(obj.proposer = message.proposer
? Validator.toJSON(message.proposer)
: undefined);
message.total_voting_power !== undefined &&
(obj.total_voting_power = message.total_voting_power);
return obj;
},
fromPartial(object: DeepPartial<ValidatorSet>): ValidatorSet {
const message = { ...baseValidatorSet } as ValidatorSet;
message.validators = [];
if (object.validators !== undefined && object.validators !== null) {
for (const e of object.validators) {
message.validators.push(Validator.fromPartial(e));
}
}
if (object.proposer !== undefined && object.proposer !== null) {
message.proposer = Validator.fromPartial(object.proposer);
} else {
message.proposer = undefined;
}
if (
object.total_voting_power !== undefined &&
object.total_voting_power !== null
) {
message.total_voting_power = object.total_voting_power;
} else {
message.total_voting_power = 0;
}
return message;
},
};
const baseValidator: object = { voting_power: 0, proposer_priority: 0 };
export const Validator = {
encode(message: Validator, writer: Writer = Writer.create()): Writer {
if (message.address.length !== 0) {
writer.uint32(10).bytes(message.address);
}
if (message.pub_key !== undefined) {
PublicKey.encode(message.pub_key, writer.uint32(18).fork()).ldelim();
}
if (message.voting_power !== 0) {
writer.uint32(24).int64(message.voting_power);
}
if (message.proposer_priority !== 0) {
writer.uint32(32).int64(message.proposer_priority);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Validator {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseValidator } as Validator;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.bytes();
break;
case 2:
message.pub_key = PublicKey.decode(reader, reader.uint32());
break;
case 3:
message.voting_power = longToNumber(reader.int64() as Long);
break;
case 4:
message.proposer_priority = longToNumber(reader.int64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Validator {
const message = { ...baseValidator } as Validator;
if (object.address !== undefined && object.address !== null) {
message.address = bytesFromBase64(object.address);
}
if (object.pub_key !== undefined && object.pub_key !== null) {
message.pub_key = PublicKey.fromJSON(object.pub_key);
} else {
message.pub_key = undefined;
}
if (object.voting_power !== undefined && object.voting_power !== null) {
message.voting_power = Number(object.voting_power);
} else {
message.voting_power = 0;
}
if (
object.proposer_priority !== undefined &&
object.proposer_priority !== null
) {
message.proposer_priority = Number(object.proposer_priority);
} else {
message.proposer_priority = 0;
}
return message;
},
toJSON(message: Validator): unknown {
const obj: any = {};
message.address !== undefined &&
(obj.address = base64FromBytes(
message.address !== undefined ? message.address : new Uint8Array()
));
message.pub_key !== undefined &&
(obj.pub_key = message.pub_key
? PublicKey.toJSON(message.pub_key)
: undefined);
message.voting_power !== undefined &&
(obj.voting_power = message.voting_power);
message.proposer_priority !== undefined &&
(obj.proposer_priority = message.proposer_priority);
return obj;
},
fromPartial(object: DeepPartial<Validator>): Validator {
const message = { ...baseValidator } as Validator;
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = new Uint8Array();
}
if (object.pub_key !== undefined && object.pub_key !== null) {
message.pub_key = PublicKey.fromPartial(object.pub_key);
} else {
message.pub_key = undefined;
}
if (object.voting_power !== undefined && object.voting_power !== null) {
message.voting_power = object.voting_power;
} else {
message.voting_power = 0;
}
if (
object.proposer_priority !== undefined &&
object.proposer_priority !== null
) {
message.proposer_priority = object.proposer_priority;
} else {
message.proposer_priority = 0;
}
return message;
},
};
const baseSimpleValidator: object = { voting_power: 0 };
export const SimpleValidator = {
encode(message: SimpleValidator, writer: Writer = Writer.create()): Writer {
if (message.pub_key !== undefined) {
PublicKey.encode(message.pub_key, writer.uint32(10).fork()).ldelim();
}
if (message.voting_power !== 0) {
writer.uint32(16).int64(message.voting_power);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): SimpleValidator {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSimpleValidator } as SimpleValidator;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.pub_key = PublicKey.decode(reader, reader.uint32());
break;
case 2:
message.voting_power = longToNumber(reader.int64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SimpleValidator {
const message = { ...baseSimpleValidator } as SimpleValidator;
if (object.pub_key !== undefined && object.pub_key !== null) {
message.pub_key = PublicKey.fromJSON(object.pub_key);
} else {
message.pub_key = undefined;
}
if (object.voting_power !== undefined && object.voting_power !== null) {
message.voting_power = Number(object.voting_power);
} else {
message.voting_power = 0;
}
return message;
},
toJSON(message: SimpleValidator): unknown {
const obj: any = {};
message.pub_key !== undefined &&
(obj.pub_key = message.pub_key
? PublicKey.toJSON(message.pub_key)
: undefined);
message.voting_power !== undefined &&
(obj.voting_power = message.voting_power);
return obj;
},
fromPartial(object: DeepPartial<SimpleValidator>): SimpleValidator {
const message = { ...baseSimpleValidator } as SimpleValidator;
if (object.pub_key !== undefined && object.pub_key !== null) {
message.pub_key = PublicKey.fromPartial(object.pub_key);
} else {
message.pub_key = undefined;
}
if (object.voting_power !== undefined && object.voting_power !== null) {
message.voting_power = object.voting_power;
} else {
message.voting_power = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,202 @@
/* eslint-disable */
import * as Long from "long";
import { util, configure, Writer, Reader } from "protobufjs/minimal";
export const protobufPackage = "tendermint.version";
/**
* App includes the protocol and software version for the application.
* This information is included in ResponseInfo. The App.Protocol can be
* updated in ResponseEndBlock.
*/
export interface App {
protocol: number;
software: string;
}
/**
* Consensus captures the consensus rules for processing a block in the blockchain,
* including all blockchain data structures and the rules of the application's
* state transition machine.
*/
export interface Consensus {
block: number;
app: number;
}
const baseApp: object = { protocol: 0, software: "" };
export const App = {
encode(message: App, writer: Writer = Writer.create()): Writer {
if (message.protocol !== 0) {
writer.uint32(8).uint64(message.protocol);
}
if (message.software !== "") {
writer.uint32(18).string(message.software);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): App {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseApp } as App;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.protocol = longToNumber(reader.uint64() as Long);
break;
case 2:
message.software = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): App {
const message = { ...baseApp } as App;
if (object.protocol !== undefined && object.protocol !== null) {
message.protocol = Number(object.protocol);
} else {
message.protocol = 0;
}
if (object.software !== undefined && object.software !== null) {
message.software = String(object.software);
} else {
message.software = "";
}
return message;
},
toJSON(message: App): unknown {
const obj: any = {};
message.protocol !== undefined && (obj.protocol = message.protocol);
message.software !== undefined && (obj.software = message.software);
return obj;
},
fromPartial(object: DeepPartial<App>): App {
const message = { ...baseApp } as App;
if (object.protocol !== undefined && object.protocol !== null) {
message.protocol = object.protocol;
} else {
message.protocol = 0;
}
if (object.software !== undefined && object.software !== null) {
message.software = object.software;
} else {
message.software = "";
}
return message;
},
};
const baseConsensus: object = { block: 0, app: 0 };
export const Consensus = {
encode(message: Consensus, writer: Writer = Writer.create()): Writer {
if (message.block !== 0) {
writer.uint32(8).uint64(message.block);
}
if (message.app !== 0) {
writer.uint32(16).uint64(message.app);
}
return writer;
},
decode(input: Reader | Uint8Array, length?: number): Consensus {
const reader = input instanceof Uint8Array ? new Reader(input) : input;
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseConsensus } as Consensus;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.block = longToNumber(reader.uint64() as Long);
break;
case 2:
message.app = longToNumber(reader.uint64() as Long);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Consensus {
const message = { ...baseConsensus } as Consensus;
if (object.block !== undefined && object.block !== null) {
message.block = Number(object.block);
} else {
message.block = 0;
}
if (object.app !== undefined && object.app !== null) {
message.app = Number(object.app);
} else {
message.app = 0;
}
return message;
},
toJSON(message: Consensus): unknown {
const obj: any = {};
message.block !== undefined && (obj.block = message.block);
message.app !== undefined && (obj.app = message.app);
return obj;
},
fromPartial(object: DeepPartial<Consensus>): Consensus {
const message = { ...baseConsensus } as Consensus;
if (object.block !== undefined && object.block !== null) {
message.block = object.block;
} else {
message.block = 0;
}
if (object.app !== undefined && object.app !== null) {
message.app = object.app;
} else {
message.app = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
type Builtin = Date | Function | Uint8Array | string | number | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (util.Long !== Long) {
util.Long = Long as any;
configure();
}

View File

@ -0,0 +1,18 @@
{
"name": "cosmos-base-tendermint-v1beta1-js",
"version": "0.1.0",
"description": "Autogenerated vuex store for Cosmos module cosmos.base.tendermint.v1beta1",
"author": "Starport Codegen <hello@tendermint.com>",
"homepage": "http://github.com/cosmos/cosmos-sdk/client/grpc/tmservice",
"license": "Apache-2.0",
"licenses": [
{
"type": "Apache-2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
],
"main": "index.js",
"publishConfig": {
"access": "public"
}
}

View File

@ -0,0 +1 @@
THIS FILE IS GENERATED AUTOMATICALLY. DO NOT DELETE.

View File

@ -0,0 +1,138 @@
import { txClient, queryClient, MissingWalletError , registry} from './module'
export { };
async function initTxClient(vuexGetters) {
return await txClient(vuexGetters['common/wallet/signer'], {
addr: vuexGetters['common/env/apiTendermint']
})
}
async function initQueryClient(vuexGetters) {
return await queryClient({
addr: vuexGetters['common/env/apiCosmos']
})
}
function mergeResults(value, next_values) {
for (let prop of Object.keys(next_values)) {
if (Array.isArray(next_values[prop])) {
value[prop]=[...value[prop], ...next_values[prop]]
}else{
value[prop]=next_values[prop]
}
}
return value
}
function getStructure(template) {
let structure = { fields: [] }
for (const [key, value] of Object.entries(template)) {
let field: any = {}
field.name = key
field.type = typeof value
structure.fields.push(field)
}
return structure
}
const getDefaultState = () => {
return {
_Structure: {
},
_Registry: registry,
_Subscriptions: new Set(),
}
}
// initial state
const state = getDefaultState()
export default {
namespaced: true,
state,
mutations: {
RESET_STATE(state) {
Object.assign(state, getDefaultState())
},
QUERY(state, { query, key, value }) {
state[query][JSON.stringify(key)] = value
},
SUBSCRIBE(state, subscription) {
state._Subscriptions.add(JSON.stringify(subscription))
},
UNSUBSCRIBE(state, subscription) {
state._Subscriptions.delete(JSON.stringify(subscription))
}
},
getters: {
getTypeStructure: (state) => (type) => {
return state._Structure[type].fields
},
getRegistry: (state) => {
return state._Registry
}
},
actions: {
init({ dispatch, rootGetters }) {
console.log('Vuex module: cosmos.crisis.v1beta1 initialized!')
if (rootGetters['common/env/client']) {
rootGetters['common/env/client'].on('newblock', () => {
dispatch('StoreUpdate')
})
}
},
resetState({ commit }) {
commit('RESET_STATE')
},
unsubscribe({ commit }, subscription) {
commit('UNSUBSCRIBE', subscription)
},
async StoreUpdate({ state, dispatch }) {
state._Subscriptions.forEach(async (subscription) => {
try {
const sub=JSON.parse(subscription)
await dispatch(sub.action, sub.payload)
}catch(e) {
throw new Error('Subscriptions: ' + e.message)
}
})
},
async sendMsgVerifyInvariant({ rootGetters }, { value, fee = [], memo = '' }) {
try {
const txClient=await initTxClient(rootGetters)
const msg = await txClient.msgVerifyInvariant(value)
const result = await txClient.signAndBroadcast([msg], {fee: { amount: fee,
gas: "200000" }, memo})
return result
} catch (e) {
if (e == MissingWalletError) {
throw new Error('TxClient:MsgVerifyInvariant:Init Could not initialize signing client. Wallet is required.')
}else{
throw new Error('TxClient:MsgVerifyInvariant:Send Could not broadcast Tx: '+ e.message)
}
}
},
async MsgVerifyInvariant({ rootGetters }, { value }) {
try {
const txClient=await initTxClient(rootGetters)
const msg = await txClient.msgVerifyInvariant(value)
return msg
} catch (e) {
if (e == MissingWalletError) {
throw new Error('TxClient:MsgVerifyInvariant:Init Could not initialize signing client. Wallet is required.')
}else{
throw new Error('TxClient:MsgVerifyInvariant:Create Could not create message: ' + e.message)
}
}
},
}
}

View File

@ -0,0 +1,60 @@
// THIS FILE IS GENERATED AUTOMATICALLY. DO NOT MODIFY.
import { StdFee } from "@cosmjs/launchpad";
import { SigningStargateClient } from "@cosmjs/stargate";
import { Registry, OfflineSigner, EncodeObject, DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { Api } from "./rest";
import { MsgVerifyInvariant } from "./types/cosmos/crisis/v1beta1/tx";
const types = [
["/cosmos.crisis.v1beta1.MsgVerifyInvariant", MsgVerifyInvariant],
];
export const MissingWalletError = new Error("wallet is required");
export const registry = new Registry(<any>types);
const defaultFee = {
amount: [],
gas: "200000",
};
interface TxClientOptions {
addr: string
}
interface SignAndBroadcastOptions {
fee: StdFee,
memo?: string
}
const txClient = async (wallet: OfflineSigner, { addr: addr }: TxClientOptions = { addr: "http://localhost:26657" }) => {
if (!wallet) throw MissingWalletError;
let client;
if (addr) {
client = await SigningStargateClient.connectWithSigner(addr, wallet, { registry });
}else{
client = await SigningStargateClient.offline( wallet, { registry });
}
const { address } = (await wallet.getAccounts())[0];
return {
signAndBroadcast: (msgs: EncodeObject[], { fee, memo }: SignAndBroadcastOptions = {fee: defaultFee, memo: ""}) => client.signAndBroadcast(address, msgs, fee,memo),
msgVerifyInvariant: (data: MsgVerifyInvariant): EncodeObject => ({ typeUrl: "/cosmos.crisis.v1beta1.MsgVerifyInvariant", value: MsgVerifyInvariant.fromPartial( data ) }),
};
};
interface QueryClientOptions {
addr: string
}
const queryClient = async ({ addr: addr }: QueryClientOptions = { addr: "http://localhost:1317" }) => {
return new Api({ baseUrl: addr });
};
export {
txClient,
queryClient,
};

View File

@ -0,0 +1,223 @@
/* eslint-disable */
/* tslint:disable */
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
export interface ProtobufAny {
"@type"?: string;
}
export interface RpcStatus {
/** @format int32 */
code?: number;
message?: string;
details?: ProtobufAny[];
}
/**
* MsgVerifyInvariantResponse defines the Msg/VerifyInvariant response type.
*/
export type V1Beta1MsgVerifyInvariantResponse = object;
export type QueryParamsType = Record<string | number, any>;
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
export interface FullRequestParams extends Omit<RequestInit, "body"> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: keyof Omit<Body, "body" | "bodyUsed">;
/** request body */
body?: unknown;
/** base url */
baseUrl?: string;
/** request cancellation token */
cancelToken?: CancelToken;
}
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
export interface ApiConfig<SecurityDataType = unknown> {
baseUrl?: string;
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
securityWorker?: (securityData: SecurityDataType) => RequestParams | void;
}
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
data: D;
error: E;
}
type CancelToken = Symbol | string | number;
export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
}
export class HttpClient<SecurityDataType = unknown> {
public baseUrl: string = "";
private securityData: SecurityDataType = null as any;
private securityWorker: null | ApiConfig<SecurityDataType>["securityWorker"] = null;
private abortControllers = new Map<CancelToken, AbortController>();
private baseApiParams: RequestParams = {
credentials: "same-origin",
headers: {},
redirect: "follow",
referrerPolicy: "no-referrer",
};
constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
Object.assign(this, apiConfig);
}
public setSecurityData = (data: SecurityDataType) => {
this.securityData = data;
};
private addQueryParam(query: QueryParamsType, key: string) {
const value = query[key];
return (
encodeURIComponent(key) +
"=" +
encodeURIComponent(Array.isArray(value) ? value.join(",") : typeof value === "number" ? value : `${value}`)
);
}
protected toQueryString(rawQuery?: QueryParamsType): string {
const query = rawQuery || {};
const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
return keys
.map((key) =>
typeof query[key] === "object" && !Array.isArray(query[key])
? this.toQueryString(query[key] as QueryParamsType)
: this.addQueryParam(query, key),
)
.join("&");
}
protected addQueryParams(rawQuery?: QueryParamsType): string {
const queryString = this.toQueryString(rawQuery);
return queryString ? `?${queryString}` : "";
}
private contentFormatters: Record<ContentType, (input: any) => any> = {
[ContentType.Json]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
[ContentType.FormData]: (input: any) =>
Object.keys(input || {}).reduce((data, key) => {
data.append(key, input[key]);
return data;
}, new FormData()),
[ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
};
private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
return {
...this.baseApiParams,
...params1,
...(params2 || {}),
headers: {
...(this.baseApiParams.headers || {}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
if (this.abortControllers.has(cancelToken)) {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
return abortController.signal;
}
return void 0;
}
const abortController = new AbortController();
this.abortControllers.set(cancelToken, abortController);
return abortController.signal;
};
public abortRequest = (cancelToken: CancelToken) => {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
abortController.abort();
this.abortControllers.delete(cancelToken);
}
};
public request = <T = any, E = any>({
body,
secure,
path,
type,
query,
format = "json",
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams = (secure && this.securityWorker && this.securityWorker(this.securityData)) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
return fetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
...requestParams,
headers: {
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
...(requestParams.headers || {}),
},
signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
}).then(async (response) => {
const r = response as HttpResponse<T, E>;
r.data = (null as unknown) as T;
r.error = (null as unknown) as E;
const data = await response[format]()
.then((data) => {
if (r.ok) {
r.data = data;
} else {
r.error = data;
}
return r;
})
.catch((e) => {
r.error = e;
return r;
});
if (cancelToken) {
this.abortControllers.delete(cancelToken);
}
if (!response.ok) throw data;
return data;
});
};
}
/**
* @title cosmos/crisis/v1beta1/genesis.proto
* @version version not set
*/
export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {}

Some files were not shown because too many files have changed in this diff Show More