@cosmwasm/ts-codegen converts your CosmWasm smart contracts into dev-friendly TypeScript classes so you can focus on shipping code.
npm install @cosmwasm/ts-codegenGenerate TypeScript SDKs for your CosmWasm smart contracts
```
npm install @cosmwasm/ts-codegen
The quickest and easiest way to interact with CosmWasm Contracts. @cosmwasm/ts-codegen converts your CosmWasm smart contracts into dev-friendly TypeScript classes so you can focus on shipping code.
🎥 Checkout our video playlist to learn how to use ts-codegen!
- @cosmwasm/ts-codegen
- Table of contents
- Usage
- Programmatic Usage
- Types
- TS Clients
- React Query
- Recoil
- Message Composer
- Message Builder
- Use Contracts Hook
- Bundles
- CLI Usage and Examples
- Advanced Usage
- JSON Schema
- JSON Schema Generation
- Exporting Schemas
- Developing
- Related
For production usage, we recommend setting up a build script that uses the main entry point:
`ts
import codegen from "@cosmwasm/ts-codegen";
codegen({
contracts: [
{
name: "SG721",
dir: "./path/to/sg721/schema",
},
{
name: "Minter",
dir: "./path/to/Minter/schema",
},
],
outPath: "./path/to/code/src/",
// options are completely optional ;)
options: {
bundle: {
bundleFile: "index.ts",
scope: "contracts",
},
types: {
enabled: true,
},
client: {
enabled: true,
},
reactQuery: {
enabled: true,
optionalClient: true,
version: "v4",
mutations: true,
queryKeys: true,
queryFactory: true,
},
recoil: {
enabled: false,
},
messageComposer: {
enabled: false,
},
messageBuilder: {
enabled: false,
},
useContractsHook: {
enabled: false,
},
},
}).then(() => {
console.log("✨ all done!");
});
`
#### Types
Typescript types and interfaces are generated in separate files so they can be imported into various generated plugins.
#### Types Options
| option | description |
| ------------------------ | --------------------------------------------------------------------- |
| types.enabled | enable type generation |types.aliasExecuteMsg
| | generate a type alias based on the contract name |types.aliasEntryPoints
| | generate type aliases for the entry points based on the contract name |
will be generated as dependency for most files. It includes the base client for interchainjs.#### Gas Configuration
The generated client provides flexible gas fee configuration options to handle different blockchain networks and fee settings.
##### Default Gas Settings
By default, the client uses a gas limit of
200000 for all transactions. You can customize this behavior through the setDefaultGasAmount.##### ChainConfig Options
The
ChainConfig interface supports two approaches for gas configuration:1. Chain Registry Integration (Recommended)
When you provide chain information, the client automatically fetches gas prices from the chain registry:
`typescript
import { useChain } from '@interchain-kit/react';const { chain } = useChain('osmosistestnet');
const chainConfig: ChainConfig = { chain: chain };
`2. Manual Gas Price Configuration
You can explicitly set gas prices for more control:
`typescript
const chainConfig: ChainConfig = {
gasPrice: {
denom: 'uosmo',
amount: '0.025'
}
};
`$3
The
client plugin will generate TS client classes for your contracts. This option generates a QueryClient for queries as well as a Client for queries and mutations.#### Client Options
| option | description |
| --------------------------- | ---------------------------------------------------- |
|
client.enabled | generate TS client classes for your contracts |
| client.execExtendsQuery | execute should extend query message clients |
| client.noImplicitOverride | should match your tsconfig noImplicitOverride option |
| client.useDeclareKeyword | use declare keyword for inherited class fields |$3
Generate react-query v3 or react-query v4 bindings for your contracts with the
react-query command.#### React Query Options
| option | description |
| --------------------------- | ---------------------------------------------------------------------------- |
|
reactQuery.enabled | enable the react-query plugin |
| reactQuery.optionalClient | allows contract client to be undefined as the component renders |
| reactQuery.queryKeys | generates a const queryKeys object for use with invalidations and set values |
| reactQuery.queryFactory | generates a const queryFactory object for useQueries and prefetchQueries use |
| reactQuery.version | v4 uses @tanstack/react-query and v3 uses react-query |
| reactQuery.mutations | also generate mutations |
| reactQuery.camelize | use camelCase style for property names |$3
Generate recoil bindings for your contracts with the
recoil command.#### Recoil Options
| option | description |
| ---------------- | ------------------------ |
|
recoil.enabled | enable the recoil plugin |$3
Generate pure message objects with the proper
utf8 encoding and typeUrl configured that you can broadcast yourself via interchainjs with the message-composer command.#### Message Composer Options
| option | description |
| ------------------------- | --------------------------------- |
|
messageComposer.enabled | enable the messageComposer plugin |$3
Generate raw message jsons for use in your application with the
message-builder command.#### Message Builder Options
| option | description |
| ------------------------ | -------------------------------- |
|
messageBuilder.enabled | enable the messageBuilder plugin |$3
Generates
useContracts hook to easily access contracts, already equipped with a signing client| option | description |
| -------------------------- | -------------------------------- |
|
useContractsHook.enabled | enable the useContracts plugin |#### Example Output
- Provider
- Contract Providers
- Contract Context
- Context Base
#### Use Contracts Provider Usage
`tsx
import { useChain } from "@cosmos-kit/react";
import { ContractsProvider } from "../path/to/codegen/contracts-context";export default function YourComponent() {
const { address, getCosmWasmClient, getSigningCosmWasmClient } =
useChain(chainName);
return (
contractsConfig={{
address,
getCosmWasmClient,
getSigningCosmWasmClient,
}}
>
);
}
`#### Use Contracts Provider Babel/TSC config
If you're using Babel, please make sure include
'@babel/preset-react' in devDeps and presets in .babelrc.js:`js
presets: ["@babel/typescript", "@babel/env", "@babel/preset-react"];
`For
tsc, you should set the jsx option to 'react' in your tsconfig.json.#### Use Contracts Hooks Usage
Once enabled, you can get contracts very simply:
`ts
const { marketplace } = useContracts();
``ts
const marketplaceClient = marketplace.signingClient(marketplaceContract);
await marketplaceClient.updateAskPrice({
collection: token.collectionAddr,
price: {
amount,
denom,
},
tokenId,
});
`$3
The bundler will make a nice package of all your contracts. For example:
`ts
const { MinterQueryClient, useMinterConfigQuery } = contracts.Minter;const { CwAdminFactoryClient } = contracts.CwAdminFactory;
`#### Bundler Options
| option | description |
| ------------------- | -------------------------------------------------------------------------------- |
|
bundle.enabled | enable the bundler plugin |
| bundle.scope | name of the scope, defaults to contracts (you can use . to make more scopes) |
| bundle.bundleFile | name of the bundle file |#### Coding Style
| option | description | default |
| ------------------ | ----------------------------------- | ------- |
|
useShorthandCtor | Enable using shorthand constructor. | true |Using shorthand constructor (Might not be transpiled correctly with babel):
`ts
constructor(
protected address: string | undefined,
protected cosmWasmClient: CosmWasmClient | undefined,
protected signingCosmWasmClient: SigningCosmWasmClient | undefined,
private TSign?: new (
client: SigningCosmWasmClient,
sender: string,
contractAddress: string
) => TSign,
private TQuery?: new (
client: CosmWasmClient,
contractAddress: string
) => TQuery,
private TMsgComposer?: new (
sender: string,
contractAddress: string
) => TMsgComposer
) {}
`Without using shorthand constructor:
`ts
address: string | undefined;
...
TMsgComposer?: new (
sender: string,
contractAddress: string
) => TMsgComposer; constructor(
address: string | undefined,
...
TMsgComposer?: new (
sender: string,
contractAddress: string
) => TMsgComposer
) {
this.address = address;
...
this.TMsgComposer = TMsgComposer;
}
`$3
You can get started quickly using our
cli by globally installing via npm:`
npm install @cosmwasm/ts-codegen
`Clone your project and
cd into your contracts folder`sh
git clone https://github.com/hyperweb-io/launchpad.git
cd launchpad/contracts/whitelists/whitelist
`Run
ts-codegen or cosmwasm-ts-codegen to generate your code.`sh
ts-codegen generate \
--plugin client \
--schema ./schema \
--out ./ts \
--name Whitelist \
--no-bundle
`The output will be in the folder specified by
--out, enjoy!#### Interactive prompt
The CLI is interactive, and if you don't specify an option, it will interactively prompt you.
`sh
cosmwasm-ts-codegen generate
? [plugin] which plugins? (Press to select, to toggle all, to invert selection)
❯◯ client
◯ recoil
◯ react-query
◯ message-composer
`In this example, you can press space bar to select a number of plugins you wish you enable.
#### Specifying Plugins
Additionally, it will also show you the name of the field (in this case
plugin) so you can specify the parameter (for example when using CI/CD) on the comand line. Here is an exampl with --plugin set to client via CLI:`sh
ts-codegen generate \
--plugin client
--schema ./schema \
--out ./ts \
--name MyContractName
`You can specify multiple
--plugin options using the generate command:`sh
ts-codegen generate \
--plugin client \
--plugin recoil \
--schema ./schema \
--out ./ts \
--name SG721
`#### Bypassing the Prompt
All options can be provided so you can bypass the prompt.
For confirm options, you can pass
--no- to set the value to false. Here is an example without optional client, using v3 for react-query, without mutations:`sh
ts-codegen generate \
--plugin client \
--plugin react-query \
--schema ./schema \
--out ./ts \
--name MyContractName \
--version v3 \
--no-optionalClient \
--no-mutations
`Example with optional client, using v4, with mutations:
`sh
ts-codegen generate \
--plugin react-query \
--schema ./schema \
--out ./ts \
--name MyContractName \
--optionalClient \
--version v4 \
--mutations
`#### Types Only Option
If needed, you can generate only the types with the
typesOnly option;`sh
ts-codegen generate \
--typesOnly \
--schema ./schema \
--out ./ts \
--name SG721
`#### Client via CLI
`sh
ts-codegen generate \
--plugin client
--schema ./schema \
--out ./ts \
--name MyContractName
`#### React Query via CLI
Here is an example without optional client, using v3 for
react-query, without mutations:`sh
ts-codegen generate \
--plugin client \
--plugin react-query \
--schema ./schema \
--out ./ts \
--name MyContractName \
--version v3 \
--no-optionalClient \
--no-mutations
`Example with optional client, using v4, with mutations:
`sh
ts-codegen generate \
--plugin react-query \
--schema ./schema \
--out ./ts \
--name MyContractName \
--optionalClient \
--version v4 \
--mutations
`#### Recoil via CLI
`sh
ts-codegen generate \
--plugin recoil \
--schema ./schema \
--out ./ts \
--name MyContractName
`#### Message Composer via CLI
`sh
ts-codegen generate \
--plugin message-composer \
--schema ./schema \
--out ./ts \
--name MyContractName
`#### Message Builder via CLI
`sh
ts-codegen generate \
--plugin message-builder \
--schema ./schema \
--out ./ts \
--name MyContractName
`$3
We generate code from the JSON Schema exported from CosmWasm smart contracts.
$3
Currently you have to have the JSON Schema output. Here is an example to start.
First, get the Rust contracts and run
cargo build:`sh
git clone git@github.com:public-awesome/stargaze-contracts.git
cd stargaze-contracts
cargo build
`now build the schema with
cargo schema`sh
cd contracts/sg721/
cargo schema
`$3
####
cosmwasm v1.1 ExampleUsing the new
write_api method, you can export schemas:`rs
use cosmwasm_schema::write_api;use cw4_group::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
fn main() {
write_api! {
instantiate: InstantiateMsg,
execute: ExecuteMsg,
query: QueryMsg,
}
}
`####
cosmwasm_std ExampleHere is a legacy example:
`rs
use cosmwasm_std::{Addr, CosmosMsg, Empty};export_schema_with_title(&schema_for!(MinterData), &out_dir, "MinterResponse");
export_schema_with_title(&schema_for!(Addr), &out_dir, "StakingResponse");
export_schema_with_title(&schema_for!(Addr), &out_dir, "DaoResponse");
export_schema_with_title(
&schema_for!(CosmosMsg),
&out_dir,
"CosmosMsg_for_Empty",
);
`Developing
$3
`
yarn
yarn bootstrap
`$3
`
yarn build
`$3
Then
cd into a package and run the tests`
cd ./packages/ast
yarn test:watch
`$3
See the docs in the
@cosmwasm/ts-codegen-ast` package.A unified toolkit for building applications and smart contracts in the Interchain ecosystem ⚛️
| Category | Tools | Description |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| Chain Information | Chain Registry, Utils, Client | Everything from token symbols, logos, and IBC denominations for all assets you want to support in your application. |
| Wallet Connectors | Interchain Kitbeta, Cosmos Kit | Experience the convenience of connecting with a variety of web3 wallets through a single, streamlined interface. |
| Signing Clients | InterchainJSbeta, CosmJS | A single, universal signing interface for any network |
| SDK Clients | Telescope | Your Frontend Companion for Building with TypeScript with Cosmos SDK Modules. |
| Starter Kits | Create Interchain Appbeta, Create Cosmos App | Set up a modern Interchain app by running one command. |
| UI Kits | Interchain UI | The Interchain Design System, empowering developers with a flexible, easy-to-use UI kit. |
| Testing Frameworks | Starship | Unified Testing and Development for the Interchain. |
| TypeScript Smart Contracts | Create Hyperweb App | Build and deploy full-stack blockchain applications with TypeScript |
| CosmWasm Contracts | CosmWasm TS Codegen | Convert your CosmWasm smart contracts into dev-friendly TypeScript classes. |
🛠 Built by the Constructive team — makers of Hyperweb
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED “AS IS”, AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.