Skip to content

feat(cosmogen): implement 3rd party generation root template (backport #4737) #4740

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
### Fixes

- [#4686](https://github.com/ignite/cli/pull/4686) Filter discovered protos to only messages.
- [#4691](https://github.com/ignite/cli/pull/4691), [#4706](https://github.com/ignite/cli/pull/4706), [#4725](https://github.com/ignite/cli/pull/4725) Fix ts-client query template and solely Go template for `ts-client` generation.
- [#4691](https://github.com/ignite/cli/pull/4691), [#4706](https://github.com/ignite/cli/pull/4706), [#4725](https://github.com/ignite/cli/pull/4725), [#4737](https://github.com/ignite/cli/pull/4737) Fix ts-client query template and solely Go template for `ts-client` generation.

## [`v28.10.0`](https://github.com/ignite/cli/releases/tag/v28.10.0)

Expand Down
18 changes: 16 additions & 2 deletions ignite/pkg/cosmosbuf/buf.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"path/filepath"
"strings"

"github.com/gobwas/glob"
"golang.org/x/sync/errgroup"
Expand Down Expand Up @@ -67,6 +68,7 @@ type (
fileByFile bool
includeImports bool
includeWKT bool
moduleName string
}

// GenOption configures code generation.
Expand All @@ -80,6 +82,7 @@ func newGenOptions() genOptions {
fileByFile: false,
includeWKT: false,
includeImports: false,
moduleName: "",
}
}

Expand Down Expand Up @@ -115,6 +118,13 @@ func IncludeWKT() GenOption {
}
}

// WithModuleName sets the module name to filter protos for.
func WithModuleName(value string) GenOption {
return func(o *genOptions) {
o.moduleName = value
}
}

// FileByFile runs the generate command for each proto file.
func FileByFile() GenOption {
return func(o *genOptions) {
Expand Down Expand Up @@ -197,9 +207,13 @@ func (b Buf) Generate(
for _, apply := range options {
apply(&opts)
}

modulePath := protoPath
if opts.moduleName != "" {
path := append([]string{protoPath}, strings.Split(opts.moduleName, ".")...)
modulePath = filepath.Join(path...)
}
// find all proto files into the path.
foundFiles, err := xos.FindFilesExtension(protoPath, xos.ProtoFile)
foundFiles, err := xos.FindFilesExtension(modulePath, xos.ProtoFile)
if err != nil || len(foundFiles) == 0 {
return err
}
Expand Down
8 changes: 7 additions & 1 deletion ignite/pkg/cosmosgen/generate_typescript.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ func (g *generator) generateTS(ctx context.Context) error {
return err
}

// add third party modules to for the root template.
for _, modules := range g.thirdModules {
data.Modules = append(data.Modules, modules...)
}

return tsg.generateRootTemplates(data)
}

Expand Down Expand Up @@ -132,6 +137,7 @@ func (g *tsGenerator) generateModuleTemplate(
// All "cosmossdk.io" module packages must use SDK's
// proto path which is where the proto files are stored.
protoPath := filepath.Join(appPath, g.g.protoDir) // use module app path

if module.IsCosmosSDKPackage(appPath) {
protoPath = filepath.Join(g.g.sdkDir, "proto")
}
Expand All @@ -144,7 +150,7 @@ func (g *tsGenerator) generateModuleTemplate(
g.g.tsTemplate(),
cosmosbuf.ExcludeFiles("module.proto"),
cosmosbuf.IncludeWKT(),
// TODO: we should exclude folders that are irrelevant for the module.
cosmosbuf.WithModuleName(m.Pkg.Name),
); err != nil {
return err
}
Expand Down
13 changes: 11 additions & 2 deletions ignite/pkg/cosmosgen/generate_typescript_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package cosmosgen

import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"

"github.com/ettle/strcase"
Expand Down Expand Up @@ -39,16 +41,23 @@ func TestGenerateTypeScript(t *testing.T) {
buf: buf,
appModules: m,
opts: &generateOptions{
useCache: false,
tsClientRootPath: tsClientDir,
useCache: false,
jsOut: func(m module.Module) string {
return filepath.Join(tsClientDir, strcase.ToKebab(m.Name))
return filepath.Join(tsClientDir, fmt.Sprintf("%s.%s.%s", "ignite", "planet", strcase.ToKebab(m.Name)))
},
},
})

err = g.generateModuleTemplate(context.Background(), appDir, m[0])
require.NoError(err, "failed to generate TypeScript files")

err = g.generateRootTemplates(generatePayload{
Modules: m,
PackageNS: strings.ReplaceAll(appDir, "/", "-"),
})
require.NoError(err)

// compare all generated files to golden files
goldenDir := filepath.Join(testdataDir, "expected_files", "ts-client")
_ = filepath.Walk(goldenDir, func(path string, info os.FileInfo, err error) error {
Expand Down
164 changes: 164 additions & 0 deletions ignite/pkg/cosmosgen/testdata/expected_files/ts-client/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/// <reference path="./types.d.ts" />
import {
GeneratedType,
OfflineSigner,
EncodeObject,
Registry,
} from "@cosmjs/proto-signing";
import { SigningStargateClient, StdFee } from "@cosmjs/stargate";
import { Env } from "./env";
import { UnionToIntersection, Return, Constructor } from "./helpers";
import { IgntModule } from "./modules";
import { EventEmitter } from "events";
import { ChainInfo } from "@keplr-wallet/types";

const defaultFee = {
amount: [],
gas: "200000",
};

export class IgniteClient extends EventEmitter {
static plugins: IgntModule[] = [];
env: Env;
signer?: OfflineSigner;
registry: Array<[string, GeneratedType]> = [];
static plugin<T extends IgntModule | IgntModule[]>(plugin: T) {
const currentPlugins = this.plugins;

class AugmentedClient extends this {
static plugins = currentPlugins.concat(plugin);
}

if (Array.isArray(plugin)) {
type Extension = UnionToIntersection<Return<T>['module']>
return AugmentedClient as typeof IgniteClient & Constructor<Extension>;
}

type Extension = Return<T>['module']
return AugmentedClient as typeof IgniteClient & Constructor<Extension>;
}

async signAndBroadcast(msgs: EncodeObject[], fee: StdFee, memo: string) {
if (this.signer) {
const { address } = (await this.signer.getAccounts())[0];
const signingClient = await SigningStargateClient.connectWithSigner(this.env.rpcURL, this.signer, { registry: new Registry(this.registry) });
return await signingClient.signAndBroadcast(address, msgs, fee ? fee : defaultFee, memo)
} else {
throw new Error(" Signer is not present.");
}
}

constructor(env: Env, signer?: OfflineSigner) {
super();
this.env = env;
this.setMaxListeners(0);
this.signer = signer;
const classConstructor = this.constructor as typeof IgniteClient;
classConstructor.plugins.forEach(plugin => {
const pluginInstance = plugin(this);
Object.assign(this, pluginInstance.module)
if (this.registry) {
this.registry = this.registry.concat(pluginInstance.registry)
}
});
}
useSigner(signer: OfflineSigner) {
this.signer = signer;
this.emit("signer-changed", this.signer);
}
removeSigner() {
this.signer = undefined;
this.emit("signer-changed", this.signer);
}
async useKeplr(keplrChainInfo: Partial<ChainInfo> = {}) {
// Using queryClients directly because BaseClient has no knowledge of the modules at this stage
try {
const queryClient = (
await import("./cosmos.base.tendermint.v1beta1/module")
).queryClient;
const bankQueryClient = (await import("./cosmos.bank.v1beta1/module"))
.queryClient;
const stakingQueryClient = (await import("./cosmos.staking.v1beta1/module")).queryClient;
const stakingqc = stakingQueryClient({ addr: this.env.apiURL });
const staking = await (await stakingqc.queryParams()).data;
const qc = queryClient({ addr: this.env.apiURL });
const node_info = await (await qc.serviceGetNodeInfo()).data;
const chainId = node_info.default_node_info?.network ?? "";
const chainName = chainId?.toUpperCase() + " Network";
const bankqc = bankQueryClient({ addr: this.env.apiURL });
const tokens = await (await bankqc.queryTotalSupply()).data;
const addrPrefix = this.env.prefix ?? "cosmos";
const rpc = this.env.rpcURL;
const rest = this.env.apiURL;

let bip44 = {
coinType: 118,
};

let bech32Config = {
bech32PrefixAccAddr: addrPrefix,
bech32PrefixAccPub: addrPrefix + "pub",
bech32PrefixValAddr: addrPrefix + "valoper",
bech32PrefixValPub: addrPrefix + "valoperpub",
bech32PrefixConsAddr: addrPrefix + "valcons",
bech32PrefixConsPub: addrPrefix + "valconspub",
};

let currencies =
tokens.supply?.map((x) => {
const y = {
coinDenom: x.denom?.toUpperCase() ?? "",
coinMinimalDenom: x.denom ?? "",
coinDecimals: 0,
};
return y;
}) ?? [];

let stakeCurrency = {
coinDenom: staking.params?.bond_denom?.toUpperCase() ?? "",
coinMinimalDenom: staking.params?.bond_denom ?? "",
coinDecimals: 0,
};

let feeCurrencies =
tokens.supply?.map((x) => {
const y = {
coinDenom: x.denom?.toUpperCase() ?? "",
coinMinimalDenom: x.denom ?? "",
coinDecimals: 0,
};
return y;
}) ?? [];

if (chainId) {
const suggestOptions: ChainInfo = {
chainId,
chainName,
rpc,
rest,
stakeCurrency,
bip44,
bech32Config,
currencies,
feeCurrencies,
...keplrChainInfo,
};
await window.keplr.experimentalSuggestChain(suggestOptions);

window.keplr.defaultOptions = {
sign: {
preferNoSetFee: true,
preferNoSetMemo: true,
},
};
}
await window.keplr.enable(chainId);
this.signer = window.keplr.getOfflineSigner(chainId);
this.emit("signer-changed", this.signer);
} catch (e) {
throw new Error(
"Could not load tendermint, staking and bank modules. Please ensure your client loads them to use useKeplr()"
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { OfflineSigner } from "@cosmjs/proto-signing";

export interface Env {
apiURL: string
rpcURL: string
prefix?: string
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export type Constructor<T> = new (...args: any[]) => T;

export type AnyFunction = (...args: any) => any;

export type UnionToIntersection<Union> =
(Union extends any
? (argument: Union) => void
: never
) extends (argument: infer Intersection) => void
? Intersection
: never;

export type Return<T> =
T extends AnyFunction
? ReturnType<T>
: T extends AnyFunction[]
? UnionToIntersection<ReturnType<T[number]>>
: never


export const MissingWalletError = new Error("wallet is required");

export function getStructure(template) {
let structure = { fields: [] as Array<unknown>}
for (const [key, value] of Object.entries(template)) {
let field: any = {}
field.name = key
field.type = typeof value
structure.fields.push(field)
}
return structure
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { msgTypes } from './registry';
import { IgniteClient } from "../client"
import { MissingWalletError } from "../helpers"
import { Api } from "./rest";
import { MsgMyMessageRequest } from "./types/planet/mars/mars";
import { MsgBarRequest } from "./types/planet/mars/mars";
import { MsgMyMessageRequest } from "./types/ignite/planet/mars/mars";
import { MsgBarRequest } from "./types/ignite/planet/mars/mars";

import { AnotherType as typeAnotherType} from "./types"

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { GeneratedType } from "@cosmjs/proto-signing";
import { MsgMyMessageRequest } from "./types/planet/mars/mars";
import { MsgBarRequest } from "./types/planet/mars/mars";
import { MsgMyMessageRequest } from "./types/ignite/planet/mars/mars";
import { MsgBarRequest } from "./types/ignite/planet/mars/mars";

const msgTypes: Array<[string, GeneratedType]> = [
["/ignite.planet.mars.MsgMyMessageRequest", MsgMyMessageRequest],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, ResponseType } from "axios";
import { QuerySimpleResponse } from "./types/planet/mars/mars";
import { QuerySimpleParamsResponse } from "./types/planet/mars/mars";
import { QueryWithPaginationResponse } from "./types/planet/mars/mars";
import { QueryWithQueryParamsResponse } from "./types/planet/mars/mars";
import { QueryWithQueryParamsWithPaginationResponse } from "./types/planet/mars/mars";
import { QuerySimpleResponse } from "./types/ignite/planet/mars/mars";
import { QuerySimpleParamsResponse } from "./types/ignite/planet/mars/mars";
import { QueryWithPaginationResponse } from "./types/ignite/planet/mars/mars";
import { QueryWithQueryParamsResponse } from "./types/ignite/planet/mars/mars";
import { QueryWithQueryParamsWithPaginationResponse } from "./types/ignite/planet/mars/mars";

import { QuerySimpleRequest } from "./types/planet/mars/mars";
import { QuerySimpleParamsRequest } from "./types/planet/mars/mars";
import { QueryWithPaginationRequest } from "./types/planet/mars/mars";
import { QueryWithQueryParamsRequest } from "./types/planet/mars/mars";
import { QueryWithQueryParamsWithPaginationRequest } from "./types/planet/mars/mars";
import { QuerySimpleRequest } from "./types/ignite/planet/mars/mars";
import { QuerySimpleParamsRequest } from "./types/ignite/planet/mars/mars";
import { QueryWithPaginationRequest } from "./types/ignite/planet/mars/mars";
import { QueryWithQueryParamsRequest } from "./types/ignite/planet/mars/mars";
import { QueryWithQueryParamsWithPaginationRequest } from "./types/ignite/planet/mars/mars";


import type {SnakeCasedPropertiesDeep} from 'type-fest';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { AnotherType } from "./types/ignite/planet/mars/mars"


export {
AnotherType,

}
Loading
Loading